相关疑难解决方法(0)

ASP.NET 核心 JWT 身份验证总是抛出 401 未经授权

我正在尝试尽可能简单地在我的 asp.net 核心 webAPI 上实现 JWT 身份验证。我不知道我错过了什么,但即使使用正确的不记名令牌,它也总是返回 401 。

这是我的 configureServices 代码

public void ConfigureServices(IServiceCollection 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(Encoding.ASCII.GetBytes("A_VERY_SECRET_SECURITY_KEY_FOR_JWT_AUTH")),
                       ValidateAudience = false,
                       ValidateIssuer = false,
                   };
               }
                );
            services.AddControllers();

            services.AddDbContext<dingdogdbContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("dingdogdbContext")));
        }

Run Code Online (Sandbox Code Playgroud)

这就是我生成令牌的方式

        [AllowAnonymous]
        [HttpPost("/Login")]
        public ActionResult<User> Login(AuthModel auth)
        {
            var user = new User();
            user.Email = auth.Email; …
Run Code Online (Sandbox Code Playgroud)

asp.net asp.net-authorization jwt asp.net-web-api asp.net-core

13
推荐指数
4
解决办法
8550
查看次数