首页 > 解决方案 > 授权属性在 JWT 和 asp.net core 2.1 中不起作用

问题描述

我已经为 .net 核心客户端实现了 JWT,但是当我放置授权属性时,它每次都会给我 401 未经授权的响应。我尝试在中间件的属性中提到模式名称。更改序列。通过堆栈溢出的大量链接。

下面是startup.cs

public void ConfigureServices(IServiceCollection services)
{
        services.AddSwaggerDocumentation();

        services.ConfigureCors();

        services.ConfigureIISIntegration();

        services.ConfigureLoggerService();

        services.ConfigureSqlContext(Configuration);

        services.ConfigureRepositoryWrapper();

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,

                ValidIssuer = "http://localhost:5000",
                ValidAudience = "http://localhost:4200/",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"))
            };
        });

        services.AddMvc();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerManager logger)
    {

        app.UseSwaggerDocumentation();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();                
        }

        app.UseHttpStatusCodeExceptionMiddleware();

        app.UseCors("CorsPolicy");

        app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.All
        });

        app.Use(async (context, next) =>
        {
            await next();

            if (context.Response.StatusCode == 404
                && !Path.HasExtension(context.Request.Path.Value))
            {
                context.Request.Path = "/index.html";
                await next();
            }
        });


        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseMvc();
    }

下面是 JWT 初始化的代码

if (userInfo.Any(c => c.ValidUser == "Y"))
                    {
                        var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"));

                        var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                        var claims = new List<Claim>
                            {
                                new Claim(ClaimTypes.Name, vsecGetPasswordByUserName.LoginId),
                                new Claim(ClaimTypes.Role, "Admin")
                            };

                        var tokeOptions = new JwtSecurityToken(
                            issuer: "http://localhost:5000",
                            audience: "http://localhost:4200",
                            claims: claims,
                            expires: DateTime.Now.AddMinutes(5),
                            signingCredentials: signinCredentials
                        );

                        var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);

                        return Ok(new { UserInfo = userInfo, TokenString = tokenString });
                    }
                    else
                    {
                        throw new HttpStatusCodeException(StatusCodes.Status401Unauthorized, @"User not valid");
                    }
                }

这是提到授权属性的控制器代码

[Authorize]
[EnableCors("CorsPolicy")]
[ApiController]
[Route("api/Utility")]
public class UtilityController : ControllerBase

标签: c#asp.netasp.net-corejwt

解决方案


请注意 your TokenValidationParameters, your audienceis ,它与令牌声明http://localhost:4200/中的 one( ) 不匹配:http://localhost:4200

所以只需将ValidAudiencein修改TokenValidationParameters为:

ValidAudience = "http://localhost:4200",

推荐阅读