授权不在使用 ASP Net Identity 和 JWT 令牌的 API 中工作

问题描述 投票:0回答:1

我需要紧急帮助... 我使用 ASP.Net Core 8.0 和

这是我的程序.cs

builder.Services.AddControllers();
        builder.Services.AddEndpointsApiExplorer(); 
        builder.Services.AddSwaggerGen();   
        builder.Services.AddDbContext<Context>
             (optn => optn.UseSqlServer(builder.Configuration.GetConnectionString("SqlServer")));
        builder.Services.AddIdentity<UserIdentityCustom,IdentityRole>(opt =>
        {
            opt.User.RequireUniqueEmail = true; //eror
            opt.Lockout.DefaultLockoutTimeSpan = new TimeSpan(100, 1, 1, 1);
            opt.SignIn.RequireConfirmedPhoneNumber = false;
            opt.SignIn.RequireConfirmedEmail = false;               
        })  
            .AddEntityFrameworkStores<Context>()                                      
            .AddDefaultTokenProviders();
        builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(option =>
        {
            option.SaveToken = true;
            option.TokenValidationParameters = new TokenValidationParameters
            {
                RequireExpirationTime = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey  
                (Encoding.UTF8.GetBytes(builder.Configuration["JWT:IssuerSigningKey"]))
            };
        });
        var app = builder.Build();
        app.UseSwagger();
        app.UseSwaggerUI();
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseAuthorization();
        app.MapControllers();
        app.Run();

这是我的控制器和操作(已[授权]):

    [ApiController]
    [Route("[controller]")]
    public class UploadController : ControllerBase
    {
        [Authorize]
        [HttpPost("[action]")]
        public IActionResult Uploadtest()
        {
            return Ok("Uploaded !");
        }
}

JWT 令牌将通过此操作创建:

public async Task<IActionResult> Login([FromBody] UsersLoginModel model) {
    if (ModelState.IsValid) 
    {        
        ResultIdentity = True; //ResultIdentity = Check By UserMannager
        if (ResultIdentity.Succeeded == true) 
        {
            var key = _config["JWT:IssuerSigningKey"]; 
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
            var tokenObject = new JwtSecurityToken(
                claims: new List<Claim>() {new Claim("id", model.Username)},
                expires: DateTime.Now.AddMinutes(10),
                signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256));
            var ResultJwt = new JwtSecurityTokenHandler().WriteToken(tokenObject);
            if (ResultJwt == null) return Unauthorized();
            return Ok(ResultJwt);
        }
       
    }
    return Unauthorized();
}

始终响应是这样的:404-错误或302-错误(我测试过:TalentApiTester - Swagger - Postman...) 什么问题?我累了5个小时... 这是我的测试:

asp.net asp.net-core authentication jwt asp.net-identity
1个回答
0
投票

我在 Jwt 中添加了“Issuer”、“Audience”, 尝试修改如下代码:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(option =>
        {
            option.SaveToken = true;
            option.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidIssuer = builder.Configuration["Jwt:Issuer"],
                ValidAudience = builder.Configuration["Jwt:Audience"],
                RequireExpirationTime = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey  
                (Encoding.UTF8.GetBytes(builder.Configuration["JWT:IssuerSigningKey"]))
            };
        });

然后修改如下:

public async Task<IActionResult> Login([FromBody] UsersLoginModel model) {
    if (ModelState.IsValid) 
    {        
        ResultIdentity = True; //ResultIdentity = Check By UserMannager
        if (ResultIdentity.Succeeded == true) 
        {
            var key = _config["JWT:IssuerSigningKey"]; 
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
 var tokenDescriptor = new SecurityTokenDescriptor
 {
     Subject = new ClaimsIdentity(new[]
     { new Claim("id", model.Username) 
     }),
     Expires= DateTime.Now.AddMinutes(10),
     Issuer = issuer,
     Audience = audience,
     SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
     
 };
 var tokenObject = new JwtSecurityTokenHandler().CreateToken(tokenDescriptor);
            var ResultJwt = new JwtSecurityTokenHandler().WriteToken(tokenObject);
            if (ResultJwt == null) return Unauthorized();
            return Ok(ResultJwt);
        }
       
    }
    return Unauthorized();
}

结果:

© www.soinside.com 2019 - 2024. All rights reserved.