我正在嘗試使用我的 JWT 令牌解鎖我的端點(控制器),該令牌在用戶登錄時發送給用戶。目前注冊和登錄作業正常,用戶會收到一個 JWT 令牌。但是,當我使用郵遞員或我的移動應用程式將 JWT 發送到 API 時,我收到 401 Unauthorized 錯誤。我正在使用 Asp.net 6 Web API。我已經添加了我的身份驗證控制器和我的 program.cs。我的 appsettings.json 以及發行者和受眾中有我的 JWT 密鑰。我確定我的錯誤在我的 program.cs 中
驗證控制器
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using VelocityNetAPI.Models;
using System.Security.Cryptography;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using VelocityNetAPI.Data;
using Microsoft.AspNetCore.Authorization;
namespace VelocityNetAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
public static User user = new User();
private readonly IConfiguration configuration;
private readonly VelocityNetAPIContext context;
public AuthController(IConfiguration configuration, VelocityNetAPIContext context)
{
this.configuration = configuration;
this.context = context;
}
[HttpPost("Register")]
public async Task<ActionResult<User>> Register(UserDto request)
{
CreatePasswordHash(request.Password, out byte[] passwordHash, out byte[] passwordSalt);
user.Name = request.Username;
user.PasswordHash = passwordHash;
user.PasswordSalt = passwordSalt;
user.Role = "User";
context.User.Add(user);
await context.SaveChangesAsync();
return Ok(user);
}
[HttpPost("Login")]
public async Task<ActionResult<string>> Login(UserDto request)
{
//search for user
var user = context.User.FirstOrDefault(u => u.Name == request.Username);
if (user == null)
{
return BadRequest("User not found");
}
if(!VerifyPasswordHash(request.Password, user.PasswordHash, user.PasswordSalt))
{
return BadRequest("Wrong Password");
}
string token = CreateToken(user);
return Ok(token);
}
private string CreateToken(User user)
{
List<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.Role, user.Role),
};
var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(configuration["Jwt:key"]));
var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha512);
var token = new JwtSecurityToken(
claims: claims,
expires: DateTime.Now.AddDays(1),
signingCredentials: cred);
var jwt = new JwtSecurityTokenHandler().WriteToken(token);
return jwt;
}
private void CreatePasswordHash(String password, out byte[] passwordHash, out byte[] passwordSalt)
{
using (HMACSHA512 hmac = new HMACSHA512())
{
passwordSalt = hmac.Key;
passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
}
}
private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
{
using (HMACSHA512 hmac = new HMACSHA512(passwordSalt))
{
var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
return computedHash.SequenceEqual(passwordHash);
}
}
}
}
程式.cs
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using VelocityNetAPI.Data;
using Microsoft.IdentityModel.Tokens;
using System.Configuration;
using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.OpenApi.Models;
using Microsoft.AspNetCore.Authorization;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<VelocityNetAPIContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("VelocityNetAPIContext")));
var conf = builder.Configuration;
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = true;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = conf["Jwt:Issuer"].ToString(),
ValidAudience = conf["Jwt:Audience"].ToString(),
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(conf["Jwt:Key"]))
};
});
//Configuration.GetSection("AppSettings:Token").Value)
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
如果您需要更多資訊,請告訴我
uj5u.com熱心網友回復:
你設定ValidateIssuer和ValidateAudience 真實。但是在您的CreateToken方法中,您不使用Issuer和Audience生成令牌。
您可以更改您的CreateToken方法,如下所示:
var token = new JwtSecurityToken(configuration["Jwt:Issuer"],
configuration["Jwt:Audience"],
claims: claims,
expires: DateTime.Now.AddDays(1),
signingCredentials: cred);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/380255.html
標籤:asp.net核心 jwt .net-6.0 asp.net-授权 asp.net-身份验证
上一篇:帶引數的Node.js路由
下一篇:C#編譯器是否將陣列元素與相同型別的變數區別對待?!(System.ArrayTypeMismatchException)
