Ocelot对接JWT和配置作用域
Ocelot对接JWT和配置作用域
一、疑:为什么需要在网关中集成Jwt? 正常不是应该在项目中进行校验。
答:因为我们可以在项目网关层中可以进行简单的校验,而不用让程序继续往下流转,这样就能及早发现并且处理,但是也是只能在网关中进行简单的检测,而更完整的校验还是需要在项目中进行校验。
二、Ocelot项目中代码配置
1. 和一般的API项目不一样,不需要配置如下,会报错:
app.UseAuthentication();
2. 配置Jwt ,如下:注意 UserGatewayKey,这个是要和网关中对应的
#region jwt校验 HS JWTTokenOptions tokenOptions = new JWTTokenOptions(); builder.Configuration.Bind("JWTTokenOptions", tokenOptions); string authenticationProviderKey = "UserGatewayKey"; builder.Services .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)//Bearer Scheme .AddJwtBearer(authenticationProviderKey, options => { options.TokenValidationParameters = new TokenValidationParameters { //JWT有一些默认的属性,就是给鉴权时就可以筛选了 ValidateIssuer = true,//是否验证Issuer ValidateAudience = true,//是否验证Audience ValidateLifetime = true,//是否验证失效时间---默认还添加了300s后才过期 ClockSkew = TimeSpan.FromSeconds(0),//token过期后立马过期 ValidateIssuerSigningKey = true,//是否验证SecurityKey ValidAudience = tokenOptions.Audience,//Audience,需要跟前面签发jwt的设置一致 ValidIssuer = tokenOptions.Issuer,//Issuer,这两项和前面签发jwt的设置一致 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey)),//拿到SecurityKey }; }); #endregion
3. 网关的配置文件中加入如下: 主要是: "AuthenticationProviderKey": "UserGatewayKey"
"AuthenticationOptions": { "AuthenticationProviderKey": "UserGatewayKey", "AllowedScopes": [ "UserWebAPIService", "UserMinimalAPIService" ] //这个是作用域,后面会讲解。 }
三、网关中配置作用域
1. 首先应该在网关的配置文件中加入Allowedscopes节点
"AuthenticationOptions": { "AuthenticationProviderKey": "UserGatewayKey", "AllowedScopes": [ "UserWebAPIService", "UserMinimalAPIService" ] }
2. 生成Token的时候加入如下一行代码:new Claim("scope", "UserWebAPIService")
var claims = new[] { new Claim("scope", "UserWebAPIService"),//为了微服务的Scope,必须小写 new Claim(ClaimTypes.Name, userModel.Name), new Claim("EMail", userModel.EMail), new Claim("Account", userModel.Account), new Claim("Age", userModel.Age.ToString()), new Claim("Id", userModel.Id.ToString()), new Claim("Mobile", userModel.Mobile), new Claim(ClaimTypes.Role,userModel.Role), new Claim("Role", "Assistant"),//这个不能默认角色授权,动态角色授权 new Claim("Sex", userModel.Sex.ToString())//各种信息拼装 };
这样就加入了作用域。
以上就是网关中的配置JWT和作用域
谢谢学习!!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2020-09-03 记录一下发送邮件的代码