最近想整合IdentityServer4跟API,但网上找到的都是各种坑,踩都踩不玩!

花了点时间终于整合好了,记录下。

新建空的asp.net core 项目

使用NuGet安装IdentityServer4最新版4.1.0。安装完成新建Config.cs类。内容如下:

using IdentityServer4;
using IdentityServer4.Models;
using IdentityServer4.Test;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace IdsAPI
{
    public static class Config
    {
        /// <summary>
        /// 客户端
        /// </summary>
        /// <returns></returns>
        internal static IEnumerable<Client> Clients()
        {
            yield return new Client
            {
                ClientId = "test-id",
                ClientName = "Test client (Code with PKCE)",

                RedirectUris = new[] {
                    "http://localhost:5000/resource-server/swagger/oauth2-redirect.html", // Kestrel
                },

                ClientSecrets = { new Secret("test-secret".Sha256()) },
                RequireConsent = true,

                AllowedGrantTypes = GrantTypes.Code,
                RequirePkce = true,
                AllowedScopes = new[] { "api",IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile},
            };
        }
        /// <summary>
        /// api资源
        /// </summary>
        /// <returns></returns>
        internal static IEnumerable<ApiResource> ApiResources()
        {
            return new List<ApiResource>
           {
                new ApiResource("api","my api")
                {
                    Scopes ={"api"},//重要,不配置返回 invalid_scope
                }
           };
        }
        /// <summary>
        /// api范围
        /// </summary>
        /// <returns></returns>
        internal static IEnumerable<ApiScope> GetApiScopes()
        {
            return new List<ApiScope>
           {
                new ApiScope("api")
           };
        }
        internal static IEnumerable<IdentityResource> GetIdentityResourceResources()
        {
            return new List<IdentityResource>
           {
               new IdentityResources.OpenId(),
               new IdentityResources.Profile()
           };
        }
        /// <summary>
        /// 测试用户
        /// </summary>
        /// <returns></returns>
        internal static List<TestUser> TestUsers()
        {
            return new List<TestUser>
            {
                new TestUser
                {
                    SubjectId = "joebloggs",
                    Username = "admin",
                    Password = "123456"
                }
            };
        }
    }
}
View Code

相关文章:

  • 2021-09-30
  • 2021-12-24
  • 2021-12-15
  • 2021-10-31
  • 2021-10-24
猜你喜欢
  • 2022-01-05
  • 2022-01-20
  • 2018-12-12
  • 2022-12-23
  • 2021-11-27
  • 2019-01-12
相关资源
相似解决方案