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和作用域

谢谢学习!!!

 
posted @ 2022-09-03 20:33  锦大大的博客呀!  阅读(279)  评论(0编辑  收藏  举报