.Net Core 3.0 IdentityServer4 快速入门02

.Net Core 3.0 IdentityServer4 快速入门

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

一、前言

  OAuth2.0默认有四种授权模式(GrantType):

    1)授权码模式

    2)简化模式

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

    4)客户端模式(client_credentials)

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

  认证步骤:

    

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

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

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

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

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

二、创建授权服务器

  

  1)安装Id4  

 

  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)看到如下发现文档算是成功的

三、创建Api资源

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

  2)安装包

  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资源

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

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

六、自定义用户验证

  在创建授权服务器的时候我们在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配置类中,修改如下:

  

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

七、通过refresh_token 获取 Token

  1)refresh_token

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

八、参考文献

  http://docs.identityserver.io/en/latest/index.html

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

原文地址:https://www.cnblogs.com/haoxiaozhang/p/11738194.html

时间: 2024-07-29 07:43:08

.Net Core 3.0 IdentityServer4 快速入门02的相关文章

.Net Core 3.0 IdentityServer4 快速入门

原文:.Net Core 3.0 IdentityServer4 快速入门 .Net Core 3.0 IdentityServer4 快速入门 一.简介 IdentityServer4是用于ASP.NET Core的OpenID Connect和OAuth 2.0框架. 将IdentityServer4部署到您的应用中具备如下特点: 1).认证服务 2).单点登陆 3).API访问控制 4).联合网关 5).专注于定制 6).成熟的开源系统 7).免费和商业支持 二.整体部署 目前大多数的应用

NSIS 2.0界面快速入门

NSIS 2.0 版本支持定制的用户界面.所谓的 Modern UI(下称 MUI) 就是一种模仿最新的 Windows 界面风格的界面系统.MUI 改变了 NSIS 脚本的编写习惯,它使用 NSIS 的宏来表达,指定 MUI 的属性需要使用宏.所以,诸如 LicenseText, Icon, CheckBitmap, InstallColors 在 MUI 中失去意义. MUI 的内置向导页面 和安装程序有关的向导页面 MUI_PAGE_WELCOME 该向导页面显示欢迎信息 MUI_PAGE

Chapter 0.SymmetricDS快速入门指南( Quick Start Guide)

本文档是SymmetricDS3.6.14文档的第一章节Quick Start Guide文档的翻译,的目的是帮助读者快速搭建一个SymmetricDS集群并普及一些基本概念术语. 本文档描述了如何在两个SymmetricDS节点之间同步两个相同schema的数据库.下面的例子构建了一个分销业务模型,有一个中央数据库(我们叫它root或者corp节点)和多个零售商店的数据库(我们叫它client或者store节点).对于本教程,我们将只有一个store(商店)节点,如下图.如果你愿意,可以再教程

.Net Core 2.0 EntityFrameworkCore CodeFirst入门教程

最近难得有时间闲下来,研究了一下.net core 2.0,总的来说,目前除了一些第三方的库不支持外,基本上可以满足我们的项目需求了! 我们就以一个网站开发为例,搭建一个简单的三层架构,先熟悉一下.net core 2.0的开发流程!  一 .搭建项目框架 首先,我们新建项目,如图: 然后,我们分别添加.net core类库项目,NetCoreDemo.Repository(数据访问层)和NetCoreDemo.Service(服务层),项目结构如下:  二 .初始化数据库 项目中, NetCo

vue2.0组件快速入门

前言 最近开始在学vue相关的内容.组件这章的内容比较多.看了http://www.cnblogs.com/keepfool/p/5625583.html这篇博客,博主总结的还比较全面也挺清晰,可是这篇博客的知识点跟实例都是基于vue 1.0版本的,所以参考这篇博客,我将vue2.0版本中的相关知识点做了一个总结.算是自己学习的一个笔记 什么是组件? 组件 (Component) 是 Vue.js 最强大的功能之一.组件可以扩展 HTML 元素,封装可重用的代码.我们可以将组件看成是封装好的HT

UML建模快速入门02 UML介绍

2015/03/21 - 16:12 [声明]欢迎转载,但请保留文章原始出处:http://blog.csdn.net/yelangjueqi/article/details/44724765 1,UML概述 1.1,统一建模语言(Unified Modeling Language,UML)是一种绘制软件蓝图的标准语言.可以用uml对软件密集型系统的制品进行可视化.详述.构造和文档化. 1.2,要学习uml,一个有效的出发点是形成该语言的概念模型,这要求学习三个要素:uml的基本构造块, 支配这

.NET Core实战项目之CMS 第二章 入门篇-快速入门ASP.NET Core看这篇就够了

作者:依乐祝 原文链接:https://www.cnblogs.com/yilezhu/p/9985451.html 本来这篇只是想简单介绍下ASP.NET Core MVC项目的(毕竟要照顾到很多新手朋友),但是转念一想不如来点猛的(考虑到急性子的朋友),让你通过本文的学习就能快速的入门ASP.NET Core.既然是快速入门所以过多过深的内容我这里就一笔带过了!然后在后面的一些列文章中再慢慢的对其中的概念进行阐述. 本文已收录至.NET Core实战项目之CMS 第一章 入门篇-开篇及总体规

UML建模快速入门00 Outline

Preface UML建模,其重要性不言而喻,本人虽然大学期间就早已知其大名,无奈因各种因素总是拿起又放下,未能持续研究,几经断断续续,一直未持续深入读完一本书.最近越发觉得逆向工程(由代码生成UML)在日常整理中的重要性及方便性,便又捡起书本,觉得应该好好看看,边看边画,对很多概念又有了较深入的理解,对以前模糊的概念更加明晰些了.说实在的,这次拿起书本来看,主要有两个原因:一是觉得UML建模确实应该作为码工具备的一个技能,二是为了提升下逼格. 为了记录个人历经的路程,后续将推出系列快速入门读书

Python快速入门02-0529

数据类型转换: 显示 隐式 dir(__builtin__)可以查看内建的函数 callable()可用于测试函数是否可以调用 字典:kv集合 {"a":31,"b":545} 每个模块都有一个名为__name__的内建变量,此变量值会根据调用时 如果模块被导入,__name__的值是模块的名字 如果模块被直接执行,__name__的值是"__main__" class:通常在自定义类型是使用 type:内置变量 instance:实例化 类:数