在自定义授权属性(.NET Core 2.2和Jason Web令牌)中,IsAuthenticated始终为false

时间:2020-01-17 11:01:55

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

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

我正在使用 Postman 调用Authorized API,这里我面临两个问题:

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

请注意,JWT的部分工作正常,正在使用正确的JWT创建一个Claims,并在{{3}上进行了检查}。

至于我的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的摘录

    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;
    }

注意:我知道这个问题之前已经问过很多次了,但是我尝试了其中的大多数,但对我没有任何帮助。

0 个答案:

没有答案