使用 ASP.NET Core Identity 和 JWT 令牌授权不在 API 中工作

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

我需要紧急 nelp ...我正在使用 ASP.NET Core 8.0,这是我的

Program.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();

这是我的控制器和操作方法(有

[Authorize]
):

[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();
}

响应始终是错误 HTTP 404 或 HTTP 302(我在 TalentApiTester - Swagger - Postman 中测试...)

问题是什么?我试了5个小时...

这是我的测试:

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

我在 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 issuer =  _config["Jwt:Issuer"];
            var audience =  _config["Jwt:Audience"];
            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.