【问题标题】:IsAuthenticated is always false in Custom Authorization Attribute (.NET Core 2.2 and JSON Web Token)IsAuthenticated 在自定义授权属性(.NET Core 2.2 和 JSON Web 令牌)中始终为 false
【发布时间】:2020-05-04 06:23:26
【问题描述】:

我正在尝试在 .net core 2.2 中使用 JSON Web Token JWT 构建我自己的自定义授权属性。

我正在使用 Postman 调用授权 API,我在这里遇到了两个问题:

  1. 发送的JWT 中的声明未收到
  2. IsAuthenticated 属性在 User.Identity.IsAuthenticated 中始终为 false。

请注意,JWT 的部分工作正常,JWT 正在按照我想要的正确Claims 创建,我已经在https://jwt.io 上进行了检查。

至于我的Startup.cs,我正在使用app.UseAuthentication()

这是我将JWTAuthentication 添加到services 的方法:

        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(x=>
        {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = true,
                ValidateAudience = false
            };
        });
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<AppIdentityDbContext>()
            .AddDefaultTokenProviders();

这是MyCustomAuthorizationAttribute.cs的sn-p

    public string Permissions { get; set; } //Permission string to get from controller

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        //Validate if any permissions are passed when using attribute at controller or action level
        if (string.IsNullOrEmpty(Permissions))
        {
            //Validation cannot take place without any permissions so returning unauthorized
            context.Result = new UnauthorizedResult();
            return;
        }


        //The below line can be used if you are reading permissions from token
        var permissionsFromToken = context.HttpContext.User.Claims.Where(x => x.Type == "Permissions").Select(x => x.Value).ToList();

        var requiredPermissions = Permissions.Split(','); //Multiple permissiosn can be received from controller, delimiter "," is used to get individual values
        foreach (var x in requiredPermissions)
        {
            if (permissionsFromToken.Contains(x))
                return; //User Authorized. Wihtout setting any result value and just returning is sufficent for authorizing user
        }

        context.Result = new UnauthorizedResult();
        return;
    }

注意:我知道这个问题以前被问过很多次,但我尝试了其中的大部分,但对我没有任何帮助。

【问题讨论】:

  • 您是如何在MyCustomAuthorizationAttribute 中获得Permissions 的?请注意,您需要设置ValidateIssuer 和ValidateAudience。并确保您已添加类型为@987654341 的声明@.参考:stackoverflow.com/a/58163087/11398810
  • 是的,您提到的所有内容都已经存在,但令人惊讶的是,问题只是在Startup.cs 中订购中间件,并且权限是根据登录的用户从数据库中获取的。

标签: asp.net-core .net-core jwt


【解决方案1】:

我发现将中间件服务放入Startup.cs 的顺序很重要。正如我们在上面的代码 sn-p 中看到的那样。在使用 AddAuthentication() 和 AddJwtBearer() 之后,我正在使用 AddIdentity() 中间件,这以某种方式删除了 JWT 身份验证提供程序。

解决方案只是将AddIdentity() 中间件及其所有子方法放在AddAuthentication() 和AddJWTBearer() 中间件之前。

【讨论】:

    猜你喜欢
    • 2019-07-31
    • 2021-07-19
    • 2017-05-22
    • 1970-01-01
    • 2020-01-28
    • 2020-04-11
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    相关资源
    最近更新 更多