如何在一个项目中实现自定义集成IdentityServer4?

2026-05-05 20:242阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计983个文字,预计阅读时间需要4分钟。

如何在一个项目中实现自定义集成IdentityServer4?

OAuth 2.0 协议简介

OAuth 2.0 是一种授权框架,允许第三方应用在用户授权的情况下访问用户资源。在开始使用之前,我们需要对一些认证授权协议有所了解。

简单来说,OAuth 2.0 允许用户授权第三方应用访问他们的资源,而无需将用户名和密码直接提供给应用。这样既保护了用户隐私,又方便了应用开发。

如何在一个项目中实现自定义集成IdentityServer4?

更多详细内容,请参考以下链接:- OAuth 2.0 设计原理:http://www.ruanyifeng.com/blog/2019/04/oauth_design.- 理解 OAuth 2.0:https://www.ruanyifeng.com/blog/2014/%E2%80%9D

OAuth2.0协议

在开始之前呢,需要我们对一些认证授权协议有一定的了解。

OAuth 2.0 的一个简单解释
www.ruanyifeng.com/blog/2019/04/oauth_design.html

理解 OAuth 2.0
www.ruanyifeng.com/blog/2014/05/oauth_2_0.html

GitHub OAuth 第三方登录示例教程
www.ruanyifeng.com/blog/2019/04/github-oauth.html

IdentityService4 配置说明

当然,前提是我希望你已经对一些官方示例进行了实践,如果没有,下面链接中有中文的案例演示

www.identityserver.com.cn/

在官方文档中我们可以在导航栏看到一些配置项,其实常用的只有Client这一项

identityserver4.readthedocs.io/en/latest/index.html

开始操作

先简单概述一下我们需要做的事情:

1、存储IdentityService4配置信息
2、存储用户数据 (采用ASP.NET Core Identity)

针对上面两项,官方都有实现,都有针对各自的案例,我们只需要做一个简单的集合,按需集合进项目中。

建立一个空web项目

.NET Core 版本不做要求 3.1、 5.0、 6.0 都可以实现 ,需要注意的是6.0版本的IdentityService4已经没有升级了,有一些Nuget包可能是过时的,当出现时,根据提示改为自己需要的版本即可。

我个人喜欢建立MVC,因为方便,中间件都有,懒得一个个引用了

添加所需NuGet包

Startup.cs文件中注册Identity

// 配置cookie策略 (此配置下方会讲解) builder.Services.Configure<CookiePolicyOptions>(options => { //让IdentityService4框架在github.com/domaindrivendev/Swashbuckle.AspNetCore#add-security-definitions-and-requirements /// </summary> public void Apply(OpenApiOperation operation, OperationFilterContext context) { bool hasAuthorize = context.MethodInfo.DeclaringType?.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any() == true || context.MethodInfo.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any(); bool hasAllowAnonymous = context.MethodInfo.DeclaringType?.GetCustomAttributes(true).OfType<AllowAnonymousAttribute>().Any() == true || context.MethodInfo.GetCustomAttributes(true).OfType<AllowAnonymousAttribute>().Any(); if (hasAuthorize && !hasAllowAnonymous) { operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" }); operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" }); OpenApiSecurityScheme oAuthScheme = new OpenApiSecurityScheme() { Reference = new OpenApiReference() { Type = ReferenceType.SecurityScheme, Id = "oauth2" } }; operation.Security = new List<OpenApiSecurityRequirement> { new OpenApiSecurityRequirement { [oAuthScheme] =new []{ "Perfect.Api" } } }; } } }

在Startup中注册,客户端ID、和客户端密钥 来自步骤 “添加测试种子数据” 中

//configuration["xx"]是来自配置文件的取值 //添加Swagger文档 services.AddSwaggerGen(c => { c.SwaggerDoc(configuration["Perfect:Swagger:Name"], new OpenApiInfo { Title = configuration["Perfect:Swagger:Title"], Version = configuration["Perfect:Swagger:Version"], Description = configuration["Perfect:Swagger:Description"], Contact = new OpenApiContact { Name = configuration["Perfect:Swagger:Contact:Name"], Email = configuration["Perfect:Swagger:Contact:Email"] } }); c.OperationFilter<SecurityRequirementsOperationFilter>(); c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, Flows = new OpenApiOAuthFlows { AuthorizationCode = new OpenApiOAuthFlow { AuthorizationUrl = new Uri($"{identityServerUrl}/connect/authorize"), TokenUrl = new Uri($"{identityServerUrl}/connect/token"), Scopes = new Dictionary<string, string> { { "openapi", "接口访问权限" }, } } } }); });

在中间件管道中使用

app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint(string.Format("/swagger/{0}/swagger.json", configuration["Perfect:Swagger:Name"]), configuration["Perfect:Swagger:Title"]); c.OAuthClientId(configuration["Perfect:Swagger:ClientId"]); c.OAuthClientSecret(configuration["Perfect:Swagger:ClientSecret"]); c.OAuthAppName(configuration["Perfect:Swagger:AppName"]); c.OAuthUsePkce(); }); 编译运行,打开swagger页面

源码地址:github.com/dreamdocker/zerostack

以上教学来自零度课堂,本人只是分享,无其他意义,开会员记得找我哦!

我自是年少,韶华倾负。

本文共计983个文字,预计阅读时间需要4分钟。

如何在一个项目中实现自定义集成IdentityServer4?

OAuth 2.0 协议简介

OAuth 2.0 是一种授权框架,允许第三方应用在用户授权的情况下访问用户资源。在开始使用之前,我们需要对一些认证授权协议有所了解。

简单来说,OAuth 2.0 允许用户授权第三方应用访问他们的资源,而无需将用户名和密码直接提供给应用。这样既保护了用户隐私,又方便了应用开发。

如何在一个项目中实现自定义集成IdentityServer4?

更多详细内容,请参考以下链接:- OAuth 2.0 设计原理:http://www.ruanyifeng.com/blog/2019/04/oauth_design.- 理解 OAuth 2.0:https://www.ruanyifeng.com/blog/2014/%E2%80%9D

OAuth2.0协议

在开始之前呢,需要我们对一些认证授权协议有一定的了解。

OAuth 2.0 的一个简单解释
www.ruanyifeng.com/blog/2019/04/oauth_design.html

理解 OAuth 2.0
www.ruanyifeng.com/blog/2014/05/oauth_2_0.html

GitHub OAuth 第三方登录示例教程
www.ruanyifeng.com/blog/2019/04/github-oauth.html

IdentityService4 配置说明

当然,前提是我希望你已经对一些官方示例进行了实践,如果没有,下面链接中有中文的案例演示

www.identityserver.com.cn/

在官方文档中我们可以在导航栏看到一些配置项,其实常用的只有Client这一项

identityserver4.readthedocs.io/en/latest/index.html

开始操作

先简单概述一下我们需要做的事情:

1、存储IdentityService4配置信息
2、存储用户数据 (采用ASP.NET Core Identity)

针对上面两项,官方都有实现,都有针对各自的案例,我们只需要做一个简单的集合,按需集合进项目中。

建立一个空web项目

.NET Core 版本不做要求 3.1、 5.0、 6.0 都可以实现 ,需要注意的是6.0版本的IdentityService4已经没有升级了,有一些Nuget包可能是过时的,当出现时,根据提示改为自己需要的版本即可。

我个人喜欢建立MVC,因为方便,中间件都有,懒得一个个引用了

添加所需NuGet包

Startup.cs文件中注册Identity

// 配置cookie策略 (此配置下方会讲解) builder.Services.Configure<CookiePolicyOptions>(options => { //让IdentityService4框架在github.com/domaindrivendev/Swashbuckle.AspNetCore#add-security-definitions-and-requirements /// </summary> public void Apply(OpenApiOperation operation, OperationFilterContext context) { bool hasAuthorize = context.MethodInfo.DeclaringType?.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any() == true || context.MethodInfo.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any(); bool hasAllowAnonymous = context.MethodInfo.DeclaringType?.GetCustomAttributes(true).OfType<AllowAnonymousAttribute>().Any() == true || context.MethodInfo.GetCustomAttributes(true).OfType<AllowAnonymousAttribute>().Any(); if (hasAuthorize && !hasAllowAnonymous) { operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" }); operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" }); OpenApiSecurityScheme oAuthScheme = new OpenApiSecurityScheme() { Reference = new OpenApiReference() { Type = ReferenceType.SecurityScheme, Id = "oauth2" } }; operation.Security = new List<OpenApiSecurityRequirement> { new OpenApiSecurityRequirement { [oAuthScheme] =new []{ "Perfect.Api" } } }; } } }

在Startup中注册,客户端ID、和客户端密钥 来自步骤 “添加测试种子数据” 中

//configuration["xx"]是来自配置文件的取值 //添加Swagger文档 services.AddSwaggerGen(c => { c.SwaggerDoc(configuration["Perfect:Swagger:Name"], new OpenApiInfo { Title = configuration["Perfect:Swagger:Title"], Version = configuration["Perfect:Swagger:Version"], Description = configuration["Perfect:Swagger:Description"], Contact = new OpenApiContact { Name = configuration["Perfect:Swagger:Contact:Name"], Email = configuration["Perfect:Swagger:Contact:Email"] } }); c.OperationFilter<SecurityRequirementsOperationFilter>(); c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, Flows = new OpenApiOAuthFlows { AuthorizationCode = new OpenApiOAuthFlow { AuthorizationUrl = new Uri($"{identityServerUrl}/connect/authorize"), TokenUrl = new Uri($"{identityServerUrl}/connect/token"), Scopes = new Dictionary<string, string> { { "openapi", "接口访问权限" }, } } } }); });

在中间件管道中使用

app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint(string.Format("/swagger/{0}/swagger.json", configuration["Perfect:Swagger:Name"]), configuration["Perfect:Swagger:Title"]); c.OAuthClientId(configuration["Perfect:Swagger:ClientId"]); c.OAuthClientSecret(configuration["Perfect:Swagger:ClientSecret"]); c.OAuthAppName(configuration["Perfect:Swagger:AppName"]); c.OAuthUsePkce(); }); 编译运行,打开swagger页面

源码地址:github.com/dreamdocker/zerostack

以上教学来自零度课堂,本人只是分享,无其他意义,开会员记得找我哦!

我自是年少,韶华倾负。