IdentityServer4密码模式

Oatuth2协议的密码模式介绍

    • 用户会将用户名,密码给予客户端,但是客户端不保存此信息,客户端带着用户的密码请求认证服务器,认证服务器密码验证通过后后将token返回给客户端。

    •  这里借用下阮一峰老师画的图(博客地址=》http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html)

 

IdentityServer4密码模式实现

  • 我们不需要修改资源服务器,我们在客户端模式下的认证服务器的Config配置中,添加一个Client,允许我们使用密码模式访问授权服务器获取token,再添加一个测试用户。同时修改我们的startup,在ConfigureServices方法中配置测试用户,代码如下所示:

 //定义可以访问该API的客户端
        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
            {
                new Client()
                {
                    ClientId = "client",
                    AllowedGrantTypes = GrantTypes.ClientCredentials,  //设置模式,客户端模式
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },
                    AllowedScopes = { "api1" }
                },
                new Client()
                {
                    ClientId="pwdClient",
                    AllowedGrantTypes=GrantTypes.ResourceOwnerPassword, //密码模式
                    ClientSecrets= {new Secret("secret".Sha256()) },
                    AllowedScopes= { "api1" }
                }
            };
        }
        public static List<TestUser> GetTestUsers()
        {
            return new List<TestUser>
            {
                new TestUser
                {
                    SubjectId="1",
                    Username="lmc",
                    Password="123456"
                }
            };
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryApiResources(Config.GetApiResources())  //配置资源
                .AddInMemoryClients(Config.GetClients())            //配置客户端
                .AddTestUsers(Config.GetTestUsers());            //配置测试用户
            services.AddMvc();
        }

此时我们使用我们定义的用户名和密码来访问我们的授权服务器(这里使用postman 要注意body的数据格式为x-www-form-urlencoded)=》

带着我们拿到的token,去访问资源=》

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值