一、导入NuGet包 Microsoft.AspNetCore.Authentication.JwtBearer
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.6" />
二、添加身份认证相关服务到容器中
#region JWT
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = false,
ValidateIssuerSigningKey = true,
ValidIssuer = "ruxing",
ValidAudience = "ruxing",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secretsecretsecret"))
};
});
#endregion
三、添加Swagger服务到容器中
#region Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v0.1.0",
Title = "demoManageSys",
Description = "框架说明文档",
Contact = new OpenApiContact { Name = "RUXING", Email = "ruxingxing@xakcdz.com" }
});
var basePath = AppContext.BaseDirectory;
var xmlPath = Path.Combine(basePath, "demoManageSys.xml");
c.IncludeXmlComments(xmlPath, true);
#region swagger中加入jwt
var scheme = new OpenApiSecurityScheme()
{
Scheme = JwtBearerDefaults.AuthenticationScheme,
BearerFormat = "JWT",
In = ParameterLocation.Header,
//头名称
Name = "",
Type = SecuritySchemeType.ApiKey,
Description = "Bearer Token"
};
c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, scheme);
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
#endregion
});
#endregion
四、将身份认证加入到管道中
//身份认证中间件(踩坑:授权中间件必须在认证中间件之前)
app.UseAuthentication();
五、在需要授权的资源上加入Authorize
/// <summary>
/// 获取天气
/// </summary>
/// <returns></returns>
[HttpGet]
[Authorize(Roles = "admin")]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
六、登录验证
public interface ICustomAuthenticationManager
{
string Authenticate(string username, string password);
IDictionary<string, string> Tokens { get; }
}
public class CustomAuthenticationManager : ICustomAuthenticationManager
{
private readonly IDictionary<string, string> users = new Dictionary<string, string>
{
{ "admin", "admin" },
{ "jonny", "jonny" },
{ "xhl", "xhl" },
{ "james", "james" }
};
public IDictionary<string, string> Tokens { get; } = new Dictionary<string, string>();
public string Authenticate(string username, string password)
{
var claimsIdentity = new ClaimsIdentity(new[]{
new Claim(ClaimTypes.Name,username)
});
if (!users.Any(u => u.Key == username && u.Value == password))
{
return null;
}
if (username == "admin")
{
claimsIdentity.AddClaims(new[]
{
new Claim( ClaimTypes.Email, "xhl.jonny@gmail.com"),
new Claim( "ManageId", "admin"),
new Claim(ClaimTypes.Role,"admin")
});
}
var handler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = claimsIdentity,
Expires = DateTime.Now.AddMinutes(3),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secretsecretsecret")), SecurityAlgorithms.HmacSha256),
};
var securityToken = handler.CreateToken(tokenDescriptor);
var token = handler.WriteToken(securityToken);
Tokens.Add(token, username);
return token;
}
}