我想使用JwtAuthentication。我在Startup.cs类中进行了一些设置。 并将一个控制器设置为[授权],但是当我调用该控制器的响应是404而不是401时,为什么? 当我调用控制器生成令牌时,它生成成功,但由于某种原因也不能在邮递员中使用他,再次我得到错误404。 你知道为什么吗?
using AutoMapper;
using Test.Core;
using Test.Persistence;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace Test
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper();
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
config.Password.RequireDigit = false;
config.Password.RequiredLength = 4;
config.Password.RequireLowercase = false;
config.Password.RequireNonAlphanumeric = false;
config.Password.RequireUppercase = false;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// ===== Add Jwt Authentication ========
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateActor = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["JwtIssuer"],
ValidAudience = Configuration["JwtAudience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtKey"]))
};
});
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMvc();
}
}
}
生成令牌只是隐藏在
中的私有方法 [HttpPost]
[ActionName("login")]
public async Task<Object> Login([FromBody] LoginResource login)
{
var result = await _signInManager.PasswordSignInAsync(login.Email, login.Password, false, false);
if (result.Succeeded)
{
var appUser = _userManager.Users.SingleOrDefault(r => r.Email == login.Email);
return GenerateJwtToken(login.Email, appUser);
}
throw new ApplicationException("INVALID_LOGIN_ATTEMPT");
}
private object GenerateJwtToken(string email, IdentityUser user)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.NameIdentifier, user.Id)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expires = DateTime.Now.AddDays(Convert.ToDouble(_configuration["JwtExpireDays"]));
var token = new JwtSecurityToken(
_configuration["JwtIssuer"],
_configuration["JwtIssuer"],
claims,
expires: expires,
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
答案 0 :(得分:0)
使用 services.AddIdentityCore<ApplicationUser>
而不是 services.AddIdentity<ApplicationUser, IdentityRole>
应该可以解决这个问题。请注意,使用 AddIdentityCore 包含角色没有重载:
默认情况下不添加角色服务,但可以使用 AddRoles() 添加。
(^ 来自documentation for AddIdentityCore)
这可以这样实现:
services.AddIdentityCore<ApplicationUser>(config =>
{
config.Password.RequireDigit = false;
config.Password.RequiredLength = 4;
config.Password.RequireLowercase = false;
config.Password.RequireNonAlphanumeric = false;
config.Password.RequireUppercase = false;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
.AddRoles<IdentityRole>();