欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.Net Core 3.0 IdentityServer4 快速入门02

程序员文章站 2022-07-09 21:14:05
.Net Core 3.0 IdentityServer4 快速入门 —— resource owner password credentials(密码模式) 一、前言 OAuth2.0默认有四种授权模式(GrantType): 1)授权码模式 2)简化模式 3)密码模式(resource owne ......

.net core 3.0 identityserver4 快速入门

              —— resource owner password credentials(密码模式)

一、前言

  oauth2.0默认有四种授权模式(granttype):

    1)授权码模式

    2)简化模式

    3)密码模式(resource owner password credentials)

    4)客户端模式(client_credentials)

  接受了 客户端模式 ,本小节将介绍 密码模式,oauth2.0资源所有者密码授权功能允许客户端将用户名和密码发送到授权服务器,并获得该用户的访问令牌

  认证步骤:

    .Net Core 3.0 IdentityServer4 快速入门02

    1)用户将用户名和密码提供给客户端

    2)客户端再将用户名和密码发送给授权服务器(id4)请求令牌

    3)授权服务器(id4)验证用户的有效性,返回给客户端令牌

    4)api资源收到第一个(首次)请求之后,会到授权服务器(id4)获取公钥,然后用公钥验证token是否合法,如果合法将进行后面的有效性验证,后面的请求都会用首次请求的公钥来验证(jwt去中心化验证的思想)

    resource owner 其实就是user,密码模式相较于客户端模式,多了一个参与者,就是user,通过user的用户名和密码向identity server 申请访问令牌,这种模式下要求客户端不得存储密码,但我们并不能确保客户端是否存储了密码,所以该模式仅仅适用于受信任的客户端。因此该模式不推荐使用

二、创建授权服务器

  .Net Core 3.0 IdentityServer4 快速入门02

   1)安装id4  

.Net Core 3.0 IdentityServer4 快速入门02 

  2)创建一个config类模拟配置要保护的资源和可以访问的api客户端服务器

 1 using identityserver4;
 2 using identityserver4.models;
 3 using identityserver4.test;
 4 using system.collections.generic;
 5 
 6 namespace identityserver02
 7 {
 8     public static class config
 9     {
10         /// <summary>
11         /// 需要保护的api资源
12         /// </summary>
13         public static ienumerable<apiresource> apis =>
14             new list<apiresource>
15             {
16                 new apiresource("api1","my api")
17             };
18         public static ienumerable<client> clients =>
19             new list<client>
20             {
21                 //客户端
22                 new client
23                 {
24                     clientid="client",
25                     clientsecrets={ new secret("aju".sha256())},
26                     allowedgranttypes=granttypes.resourceownerpassword,
27                     //如果要获取refresh_tokens ,必须在scopes中加上offlineaccess
28                     allowedscopes={ "api1", identityserverconstants.standardscopes.offlineaccess},
29                     allowofflineaccess=true
30                 }
31             };
32 
33         public static list<testuser> users = new list<testuser>
34         {
35             new testuser
36             {
37                 subjectid="001",
38                 password="aju_001",
39                 username="aju_001"
40             },
41             new testuser
42             {
43                  subjectid="002",
44                 password="aju_002",
45                 username="aju_002"
46             }
47         };
48     }
49 }

  与客户端模式不一致的地方就在于(allowedgranttypes=granttypes.resourceownerpassword)此处设置为资源所有者(密码模式)

  3)配置startup

 1 using microsoft.aspnetcore.builder;
 2 using microsoft.aspnetcore.hosting;
 3 using microsoft.extensions.dependencyinjection;
 4 using microsoft.extensions.hosting;
 5 
 6 namespace identityserver02
 7 {
 8     public class startup
 9     {
10         // this method gets called by the runtime. use this method to add services to the container.
11         // for more information on how to configure your application, visit https://go.microsoft.com/fwlink/?linkid=398940
12         public void configureservices(iservicecollection services)
13         {
14             var builder = services.addidentityserver()
15                 .addinmemoryapiresources(config.apis)
16                 .addinmemoryclients(config.clients)
17                 .addtestusers(config.users);19             builder.adddevelopersigningcredential();
20         }
21 
22         // this method gets called by the runtime. use this method to configure the http request pipeline.
23         public void configure(iapplicationbuilder app, iwebhostenvironment env)
24         {
25             if (env.isdevelopment())
26             {
27                 app.usedeveloperexceptionpage();
28             }
29             // app.userouting();
30             app.useidentityserver();
31         }
32     }
33 }

  5)验证配置是否成功

  在浏览器中输入(http://localhost:5000/.well-known/openid-configuration)看到如下发现文档算是成功的

.Net Core 3.0 IdentityServer4 快速入门02

 三、创建api资源

  1)步骤如创建授权服务的1)

  2)安装包

.Net Core 3.0 IdentityServer4 快速入门02

   3)创建一个受保护的apicontroller

 1 using microsoft.aspnetcore.authorization;
 2 using microsoft.aspnetcore.mvc;
 3 using system.linq;
 4 
 5 namespace api02.controllers
 6 {
 7     [route("api")]
 8     [authorize]
 9     public class apicontroller : controllerbase
10     {
11         public iactionresult get()
12         {
13             return new jsonresult(from c in user.claims select new { c.type, c.value });
14         }
15     }
16 }

  4)配置startup

 1 using microsoft.aspnetcore.builder;
 2 using microsoft.aspnetcore.hosting;
 3 using microsoft.extensions.configuration;
 4 using microsoft.extensions.dependencyinjection;
 5 using microsoft.extensions.hosting;
 6 
 7 namespace api02
 8 {
 9     public class startup
10     {
11         public startup(iconfiguration configuration)
12         {
13             configuration = configuration;
14         }
15 
16         public iconfiguration configuration { get; }
17 
18         // this method gets called by the runtime. use this method to add services to the container.
19         public void configureservices(iservicecollection services)
20         {
21             services.addcontrollers();
22             services.addauthentication("bearer").addjwtbearer("bearer", options =>
23             {
24                 options.authority = "http://localhost:5000";
25                 options.requirehttpsmetadata = false;
26                 options.audience = "api1";
27             });
28         }
29 
30         // this method gets called by the runtime. use this method to configure the http request pipeline.
31         public void configure(iapplicationbuilder app, iwebhostenvironment env)
32         {
33             if (env.isdevelopment())
34             {
35                 app.usedeveloperexceptionpage();
36             }
37 
38             app.userouting();
39 
40             app.useauthentication();//认证
41             app.useauthorization();//授权
42 
43 
44             app.useendpoints(endpoints =>
45             {
46                 endpoints.mapcontrollers();
47             });
48         }
49     }
50 }

四、创建客户端(控制台 模拟客户端)

 1 using identitymodel.client;
 2 using newtonsoft.json.linq;
 3 using system;
 4 using system.net.http;
 5 using system.threading.tasks;
 6 
 7 namespace client02
 8 {
 9     class program
10     {
11         static async task main(string[] args)
12         {
13             // console.writeline("hello world!");
14             var client = new httpclient();
15             var disco = await client.getdiscoverydocumentasync("http://localhost:5000");
16             if (disco.iserror)
17             {
18                 console.writeline(disco.error);
19                 return;
20             }
21             var tokenresponse = await client.requestpasswordtokenasync(
22                 new passwordtokenrequest
23                 {
24                     address = disco.tokenendpoint,
25                     clientid = "client",
26                     clientsecret = "aju",
27                     scope = "api1 offline_access",
28                     username = "aju",
29                     password = "aju_password"
30                 });
31             if (tokenresponse.iserror)
32             {
33                 console.writeline(tokenresponse.error);
34                 return;
35             }
36             console.writeline(tokenresponse.json);
37             console.writeline("\n\n");
38             //call api
39             var apiclient = new httpclient();
40             apiclient.setbearertoken(tokenresponse.accesstoken);
41             var response = await apiclient.getasync("http://localhost:5001/api");
42             if (!response.issuccessstatuscode)
43             {
44                 console.writeline(response.statuscode);
45             }
46             else
47             {
48                 var content = await response.content.readasstringasync();
49                 console.writeline(jarray.parse(content));
50             }
51             console.readline();
52         }
53     }
54 }

五、验证

  1)直接获取api资源

.Net Core 3.0 IdentityServer4 快速入门02

  出现了401未授权提示,这就说明我们的api需要授权

  2)运行客户端访问api资源

.Net Core 3.0 IdentityServer4 快速入门02

六、自定义用户验证

  在创建授权服务器的时候我们在config中默认模拟(写死)两个用户,这显得有点不太人性化,那我们就来自定义验证用户信息

  1)创建 自定义 验证 类 resourceownervalidator 

 1 using identitymodel;
 2 using identityserver4.models;
 3 using identityserver4.validation;
 4 using system.threading.tasks;
 5 
 6 namespace identityserver02
 7 {
 8     public class resourceownervalidator : iresourceownerpasswordvalidator
 9     {
10         public task validateasync(resourceownerpasswordvalidationcontext context)
11         {
12             if (context.username == "aju" && context.password == "aju_password")
13             {
14                 context.result = new grantvalidationresult(
15                     subject: context.username,
16                     authenticationmethod: oidcconstants.authenticationmethods.password);
17             }
18             else
19             {
20                 context.result = new grantvalidationresult(tokenrequesterrors.invalidgrant, "无效的秘钥");
21             }
22             return task.fromresult("");
23         }
24     }
25 }

  2)在授权服务器startup配置类中,修改如下:

  .Net Core 3.0 IdentityServer4 快速入门02

    3)在客户端中将 用户名 和 密码 修改成 我们在自定义 用户 验证类 中写的用户名和密码,进行测试

七、通过refresh_token 获取 token

  1)refresh_token 

    获取请求授权后会返回 access_token、expire_in、refresh_token 等内容,每当access_token 失效后用户需要重新授权,但是有了refresh_token后,客户端(client)检测到token失效后可以直接通过refresh_token向授权服务器申请新的token

.Net Core 3.0 IdentityServer4 快速入门02

八、参考文献

  

  如果对您有帮助,请点个推荐(让更多需要的人看到哦)

.Net Core 3.0 IdentityServer4 快速入门02

 

上一篇: Go语言系列开发之延迟调用和作用域

下一篇: