文章目录
- 目的
- 实现案例
- 一.项目所需包:
- 二.配置项目 appsettings.json 文件:
- 三.创建Model文件夹,添加AppConfig类和UserRole类
- 1.AppConfig类获取appsettings.json文件中的值
- 2.UserRole类用于区分用户信息和权限
- 四.主体代码案例:
- 1.LoginController 控制器,实现用户登录,JWT授权
- 2.HomeController 控制器,无需登录,游客模式也能访问
- 3.UserRoleController 控制器,用户登录之后可以访问
- 4.AdminController 控制器,管理员权限登录之后可以访问
- 5.在Program中注册JWT,swagge添加Jwt入口
- 五.项目运行
- 1.游客模式:
- 2.普通用户模式:
- 3.接着使用管理员账户登录,访问admin/hello
- 结果
目的
.Net6使用JWT实现登录认证和授权
接口分三种类型:
1.游客模式:没有登录也可以访问的接口
2.用户模式:普通用户登录,可以访问的接口(登录即可访问)
3.管理模式:鉴定Token权限,拥有管理员资格的用户,才能访问
https://gitee.com/hgcjd/JWTDemoTest.git
实现案例
一.项目所需包:
二.配置项目 appsettings.json 文件:
配置jwt所需信息
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"JwtTokenOptions": {
"Issuer": "http://xxxx.com",
"Audience": "http://xxxx.com",
"SecurityKey": "qwertyuiopasdfghjklzxcvbnm1234567890"
}
}
三.创建Model文件夹,添加AppConfig类和UserRole类
1.AppConfig类获取appsettings.json文件中的值
/// <summary>
/// 获取.NetCore配置文件信息
/// </summary>
public class AppConfig
{
public static string GetConfigInfo(string Key)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
IConfigurationRoot configuration = builder.Build();
string configStr = configuration.GetSection($"{Key}").Value;
if (!string.IsNullOrWhiteSpace(configStr))
{
return configStr;
}
return null;
}
}
2.UserRole类用于区分用户信息和权限
/// <summary>
/// 用户,权限
/// </summary>
public class UserRole
{
//权限
public int Role { get; set; }
/// <summary>
/// 用户名
/// </summary>
public string UserId { get; set; }
/// <summary>
/// 密码
/// </summary>
public string Password { get; set; }
}
四.主体代码案例:
1.LoginController 控制器,实现用户登录,JWT授权
[Route("login")]
[ApiController]
public class LoginController : ControllerBase
{
/// <summary>
/// 用户列表
/// </summary>
private readonly static List<UserRole> _Users = new List<UserRole>()
{
new UserRole{ Role = 1,UserId = "administrator",Password = "123456" }, //管理员
new UserRole{ Role = 0,UserId = "user",Password = "1"} //普通用户
};
/// <summary>
/// 管理权限配置
/// </summary>
private readonly static List<Claim> _administrator = new List<Claim>() {
new Claim(ClaimTypes.Name,"administrator"),
new Claim(ClaimTypes.Role,"administrator"),
new Claim(ClaimTypes.Role,"user"),
};
/// <summary>
/// 普通用户权限配置
/// </summary>
private readonly static List<Claim> _user = new List<Claim>() {
new Claim(ClaimTypes.Name,"user"),
new Claim(ClaimTypes.Role,"user"),
};
/// <summary>
/// 用户登录接口
/// </summary>
/// <param name="userid"></param>
/// <param name="password"></param>
/// <returns></returns>
[Route("login")]
[HttpPost]
public string Login(string userid,string password)
{
if (!string.IsNullOrWhiteSpace(userid) && !string.IsNullOrWhiteSpace(password))
{
var list = _Users.Where(e => e.UserId.ToString() == userid && e.Password == password).ToList();
if (list != null && list.Count > 0)
{
var userInfo = list[0];
var claims = new List<Claim>();
if (userInfo.Role == 1)
claims = _administrator;//管理权限
else
claims = _user;//普通用户
JwtSecurityToken token = new JwtSecurityToken(
issuer:AppConfig.GetConfigInfo("JwtTokenOptions:Issuer"),
audience: AppConfig.GetConfigInfo("JwtTokenOptions:Audience"),
claims: claims,
expires: DateTime.Now.AddMinutes(5),
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppConfig.GetConfigInfo("JwtTokenOptions:SecurityKey"))), SecurityAlgorithms.HmacSha256)
);
string tokenStr = new JwtSecurityTokenHandler().WriteToken(token);
return tokenStr;
}
}
return null;
}
}
2.HomeController 控制器,无需登录,游客模式也能访问
/// <summary>
/// 公共接口,游客也可以访问
/// </summary>
[Route("Home")]
[ApiController]
public class HomeController : ControllerBase
{
[Route("Hello")]
[HttpGet]
public async Task<string> HelloAction()
{
return "Hello People~";
}
}
3.UserRoleController 控制器,用户登录之后可以访问
通过 [Authorize]属性实现,该属性也可以放在单个接口上,使单个接口需要权限认证
/// <summary>
/// 登录后,用户权限是User的才能访问
/// </summary>
[Route("UserRole")]
[ApiController]
//[Authorize(Roles ="user")]
[Authorize]
public class UserRoleController : ControllerBase
{
[Route("Hello")]
[HttpGet]
public async Task<string> HelloUser()
{
return "Hello User~";
}
}
4.AdminController 控制器,管理员权限登录之后可以访问
通过 [Authorize(Roles = “administrator”)]实现,Roles 标注需要的权限类型,该属性也可以放在接口上
/// <summary>
/// 管理员登录,才能访问
/// </summary>
[Route("AdminRole")]
[ApiController]
[Authorize(Roles = "administrator")]
public class AdminController : ControllerBase
{
[Route("Hello")]
[HttpGet]
public async Task<string> HelloAdmin()
{
return "Hello Administrator~";
}
}
5.在Program中注册JWT,swagge添加Jwt入口
using JwtDemoTest.Model;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
#region 注册Jwt认证
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer("Bearer", o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,//是否验证签名,不验证的画可以篡改数据,不安全
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AppConfig.GetConfigInfo("JwtTokenOptions:SecurityKey"))),//解密的密钥
ValidateIssuer = true,//是否验证发行人,就是验证载荷中的Iss是否对应ValidIssuer参数
ValidIssuer = AppConfig.GetConfigInfo("JwtTokenOptions:Issuer"),//发行人,
ValidateAudience = true,//是否验证订阅人,就是验证载荷中的Aud是否对应ValidAudience参数
ValidAudience = AppConfig.GetConfigInfo("JwtTokenOptions:Audience")//订阅人
};
});
builder.Services.AddAuthorization();
#endregion
#region swagge添加Jwt认证
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My WebApi JwtDemoTest", Version = "v1" });
// 定义安全定义
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
// 添加认证要求
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});
#endregion
var app = builder.Build();
app.UseAuthentication();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();
五.项目运行
1.游客模式:
项目未登录,也可访问Home/Hello接口
2.普通用户模式:
普通用户登录获取Token,然后调用接口访问成功
首先调用login/login接口,获取普通用户权限token
接口携带token
携带普通用户登录后的token之后,访问 userrole/hello 接口成功
3.接着使用管理员账户登录,访问admin/hello
结果
.Net6 JWT搭建认证,授权,鉴权成功