调用identityServer4服务端的自定义api接口

1、添加apiresource[下面标红的那一行]

        public static IEnumerable<ApiResource> GetApis()
        {
            var apiClients = SysCore.ConfigHelper.GetSectionApiSites();
            List<ApiResource> lstResult = new List<ApiResource>();
            foreach (var client in apiClients)
            {
                string displayName = client.ClientName;
                string scope = client.Scope;
                ApiResource oneResult = new ApiResource(scope, displayName);
                lstResult.Add(oneResult);
            }
            lstResult.Add(new ApiResource(IdentityServerConstants.LocalApi.ScopeName));
            return lstResult;
        }

2、在客户端里添加允许[下面标红的那一行]

                else if (client.ClientType == "html")
                {
                    Client oneResult = new Client
                    {
                        ClientId = client.ClientId,
                        ClientName = client.ClientName,
                        AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                        ClientSecrets = { new Secret("12121212".Sha256()) },
                        AllowOfflineAccess = true,
                        RequireConsent = false,
                        RequireClientSecret = false,
                        AllowedScopes =
                        {
                            IdentityServerConstants.StandardScopes.OpenId,
                            IdentityServerConstants.StandardScopes.Profile,
                            IdentityServerConstants.StandardScopes.OfflineAccess,
                            "role",
                            "CommonAPI",
                            IdentityServerConstants.LocalApi.ScopeName
                        }
                    };
                    lstResult.Add(oneResult);
                }

3、在需要验证的服务端自建的api上加

    [Authorize(LocalApi.PolicyName)]
    public class RoleController : ControllerBase
    {
        private readonly UserManager<IdentityUser> _userManager;
        private readonly RoleManager<IdentityRole> _roleManager;
     .......

 4、在ConfigureServices里添加下面的代码

            services.AddLocalApiAuthentication();
            services.AddAuthorization(options =>
            {
                options.AddPolicy(IdentityServerConstants.LocalApi.PolicyName, policy =>
                {
                    policy.AddAuthenticationSchemes(IdentityServerConstants.LocalApi.AuthenticationScheme);
                    policy.RequireAuthenticatedUser();
                });
            });

5、在Configure里添加下面这行

  app.UseAuthentication();

 

posted @ 2021-05-18 11:34  星星c#  阅读(305)  评论(0编辑  收藏  举报