【发布时间】:2021-03-25 15:08:32
【问题描述】:
我正在尝试为我的 web-api 设置基于令牌的身份验证。截至目前,我正在正确生成令牌,但我在使用令牌进行授权时遇到问题。使用邮递员,我在所有帖子上都收到 401 Unauthorized。我目前已将 Jwt 配置如下:
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
private IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey =
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
services.AddMvc();
services.AddControllers();
services.AddSingleton<ITitleDataService, TitleDataService>();
services.AddSingleton<IPersonDataService, PersonDataService>();
services.AddSingleton<IUserDataService, UserDataService>();
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddControllersWithViews()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
services.AddMvc().AddControllersAsServices();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRequestLogging();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseFileServer();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
这是我的控制器:
//LOGIN
[HttpPost("user/login/")]
public IActionResult Login(UserDto userDto)
{
var user = _dataService.Login(userDto.Username, userDto.Password);
IActionResult response = Unauthorized();
if (user)
{
var tokenStr = GenerateJSONWebToken(userDto);
response = Ok(new {tokenStr});
}
else
{
return BadRequest("User not authorized");
}
return response;
}
[Authorize]
[HttpPost("post")]
public string Post()
{
var identity = HttpContext.User.Identity as ClaimsIdentity;
IList<Claim> claim = identity.Claims.ToList();
Console.WriteLine(claim.Count);
var username = claim[0].Value;
Console.WriteLine(username);
return "Welcome to " + username;
}
[Authorize]
[HttpGet("GetValue")]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] {"Value1", "Value2", "Value3"};
}
private string GenerateJSONWebToken(UserDto userDto)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, userDto.Username),
new Claim(JwtRegisteredClaimNames.Email, userDto.Password),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
var token = new JwtSecurityToken(
issuer: "Issuer",
audience: "Issuer",
claims,
expires: DateTime.Now.AddMinutes(120),
signingCredentials: credentials);
var encodetoken = new JwtSecurityTokenHandler().WriteToken(token);
return encodetoken;
}
我尝试重新安排中间件管道,但没有任何运气。我对令牌的经验很少,因此对如何解决这个问题非常迷茫。非常感谢所有建议!
最好的问候, 杰斯珀
【问题讨论】:
标签: c# asp.net-web-api jwt