(Configuration.GetSection(\"JwtSettings\")); //由于初始化的时候我们就需要⽤,所以使⽤Bind的⽅式读取配置 //将配置绑定到JwtSettings实例中 var jwtSettings = new JwtSettings();Configuration.Bind(\"JwtSettings\", jwtSettings);
//添加⾝份验证
services.AddAuthentication(options => {
//认证middleware配置
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; })
.AddJwtBearer(o => {
//jwt token参数设置
o.TokenValidationParameters = new TokenValidationParameters {
NameClaimType = JwtClaimTypes.Name, RoleClaimType = JwtClaimTypes.Role, //Token颁发机构
ValidIssuer = jwtSettings.Issuer, //颁发给谁
ValidAudience = jwtSettings.Audience, //这⾥的key要进⾏加密
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey)), /***********************************TokenValidationParameters的参数默认值***********************************/ // RequireSignedTokens = true, // SaveSigninToken = false, // ValidateActor = false,
// 将下⾯两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。 // ValidateAudience = true, // ValidateIssuer = true,
// ValidateIssuerSigningKey = false,
// 是否要求Token的Claims中必须包含Expires // RequireExpirationTime = true, // 允许的服务器时间偏移量
// ClockSkew = TimeSpan.FromSeconds(300),
// 是否验证Token有效期,使⽤当前时间与Token的Claims中的NotBefore和Expires对⽐ // ValidateLifetime = true }; }); #endregion //mvc路由配置
services.AddMvc(options => {
options.Filters.Add(new ActionFilter());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage(); } else {
app.UseHsts(); }
//⾝份授权认证
app.UseAuthentication(); app.UseHttpsRedirection(); app.UseMvc(); }
我们新建⼀个⽤户的实体类app_mobile_user
public class app_mobile_user {
public long id { get; set; } /// /// ⼿机号///
public string phone { get; set; } /// /// 密码///
public string password { get; set; } }
接下来在Controllers⽂件夹下新建控制器userController.cs,完整代码如下
namespace Mms.Api.Controllers{
[Route(\"[controller]\")] [ApiController]
public class userController : ControllerBase {
//获取JwtSettings对象信息
private JwtSettings _jwtSettings;
public userController(IOptions _jwtSettingsAccesser) {_jwtSettings = _jwtSettingsAccesser.Value; }
/// /// 获取token ///
///
private object Token(app_mobile_user model) {
//测试⾃⼰创建的对象
var user = new app_mobile_user {
id = 1,
phone = \"138000000\",
password = \"e10adc3949ba59abbe56e057f20f883e\" };
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(_jwtSettings.SecretKey); var authTime = DateTime.Now;//授权时间
var expiresAt = authTime.AddDays(30);//过期时间 var tokenDescripor = new SecurityTokenDescriptor {
Subject = new ClaimsIdentity(new Claim[] {
new Claim(JwtClaimTypes.Audience,_jwtSettings.Audience), new Claim(JwtClaimTypes.Issuer,_jwtSettings.Issuer), new Claim(JwtClaimTypes.Name, user.phone.ToString()), new Claim(JwtClaimTypes.Id, user.id.ToString()),
new Claim(JwtClaimTypes.PhoneNumber, user.phone.ToString()) }),
Expires = expiresAt,
//对称秘钥SymmetricSecurityKey
//签名证书(秘钥,加密算法)SecurityAlgorithms
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) };
var token = tokenHandler.CreateToken(tokenDescripor); var tokenString = tokenHandler.WriteToken(token); var result = new {
access_token = tokenString, token_type = \"Bearer\", profile = new {
id = user.id,
name = user.phone, phone = user.phone, auth_time = authTime, expires_at = expiresAt } };
return result; }
[Route(\"get_token\")] [HttpPost]
public IActionResult GetToken() {
return Ok(Token(null)); }
[Authorize]
[Route(\"get_user_info\")] [HttpPost]
public IActionResult GetUserInfo() {
//获取当前请求⽤户的信息,包含token信息 var user = HttpContext.User; return Ok();
} }
接下来就开始做验证!PostMan测试获取token
这样可以成功获取token,下⾯来做权限校验在需要授权的api上新增 [Authorize] 标记
我们分别使⽤携带token和不携带token访问get_user_info接⼝ 1.未携带token,返回401
2.携带token访问,返回了想要的数据
如果查看token信息到官⽅:
项⽬中需要解析token可以调⽤HttpContext.User
转: