(九)ReactAntDesignPro+.Net5WebApi:后端环境搭建-IdentityServer4-简单配置

博客 动态
0 169
羽尘
羽尘 2022-03-22 14:57:06
悬赏:0 积分 收藏

(九)React Ant Design Pro + .Net5 WebApi:后端环境搭建-IdentityServer4-简单配置

.net core IdentityServer4 认证授权 token

一、简介

IdentityServer4 是用于 ASP.NET Core 的 OpenID Connect 和 OAuth 2.0 框架,通过中间件的方式集成。JWT(json web token)本身是一个格式,不是一个框架,在ids4中也用到了这种格式,而在很多公司的项目里(包括我们)使用JWT来完成鉴权机制,是在这个token格式的基础上用代码实现生成、颁发、校验、刷新、过期等功能。这是IdentityServer4JWT的区别。

二、配置

(1)新建一个空Api项目作为认证鉴权中心,Nuget安装 IdentityServer4 包(2)Startup Configure 启用 ids4,ConfigureServices 配置 ApiResources资源、Clients客户端、ApiScopes作用域 等等,调用新建的 InMemoryConfig 配置类

public class InMemoryConfig{    public static IEnumerable<IdentityResource> IdentityResources =>    new IdentityResource[]    {        new IdentityResources.OpenId(),        new IdentityResources.Profile(),    };    /// <summary>    /// ApiResource 资源列表    /// </summary>    public static IEnumerable<ApiResource> GetApiResources()    {        return new[]        {            new ApiResource("Users", "获取用户信息API")            {                Scopes={ "scope1" }//必须            }        };    }    /// <summary>    /// ApiScopes 作用域    /// </summary>    public static IEnumerable<ApiScope> GetApiScopes()    {        return new ApiScope[]          {            new ApiScope("scope1")          };    }    /// <summary>    /// Client 客户端    /// </summary>    public static IEnumerable<Client> GetClients()    {        return new[]        {            new Client            {                ClientId = "HomeJok.Authentication",                        //客户端唯一标识                ClientName = "Authentication",                              //客户端名称                ClientSecrets = new [] { new Secret("wintersir".Sha256()) },//客户端密码,进行了加密                AllowedGrantTypes = GrantTypes.ClientCredentials,           //授权方式,客户端认证 ClientId+ClientSecrets                AllowedScopes = new [] { "scope1" },                        //允许访问的资源                Claims = new List<ClientClaim>(){                    new ClientClaim(IdentityModel.JwtClaimTypes.Role,"Admin"),                    new ClientClaim(IdentityModel.JwtClaimTypes.NickName,"WinterSir"),                    new ClientClaim("email","641187567@qq.com")                }            }        };    }}

三、测试 Token

以上就可以获取到 token 了,启动认证服务dotnet run urls=http://*:5000,用 Postman 测试 token,在 jwt.io 里解析内容。

四、Api服务集成 ids4 认证

(1)上述操作完成了ids4认证服务,下面回到Api项目进行调用,Nuget安装 IdentityServer4.AccessTokenValidation
(2)startup 配置 ids4 认证,在Api方法上启用鉴权(3)启动Api服务dotnet run urls=http://*:8000用 Postman 获取最新的 token,再调用 Api GetUserInfo

五、总结

可以看到,没有添加 token 的请求返回401无权限,在添加 token 后正常获取用户列表。这篇算是一个Demo,接下来还要学习常用的几种授权模式、SSO、持久化等。

六、前人栽树,后人乘凉

https://identityserver4.readthedocs.io/en/latest/index.html
https://www.cnblogs.com/cwsheng/p/13611036.html
https://www.cnblogs.com/stulzq/p/8119928.html

posted @ 2022-03-22 14:25 冬先生 阅读(0) 评论(0) 编辑 收藏 举报
回帖
    羽尘

    羽尘 (王者 段位)

    2335 积分 (2)粉丝 (11)源码

     

    温馨提示

    亦奇源码

    最新会员