using Microsoft.IDentityModel.Tokens; //生成jwt tokenusing Microsoft.AspNetCore.Authentication.JwtBearer; // jwt auth 认证,需要用negut包安装using Microsoft.AspNetCore.Authorization; // 认证using System.Security.Claims; // 声明身份using Microsoft.IDentityModel.Tokens; //Tokensusing System.Text; //编码jwt token 生成
using System;using System.Collections.Generic;using System.linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Authentication;using Microsoft.IDentityModel.Tokens;using System.IDentityModel.Tokens.Jwt;using System.Security.Claims;using System.Text;namespace authtest.Controllers{ [Route("[controller]/[action]")] public class JwtAuthController : Controller { public IActionResult Login() { var claims = new[] { new Claim(JwtRegisteredClaimnames.Sub,"test"),new Claim(JwtRegisteredClaimnames.Jti,GuID.NewGuID().ToString()),new Claim(ClaimTypes.Role,"user"),new Claim("org","true") }; var key = new SymmetricSecurityKey(EnCoding.UTF8.GetBytes("test6666666666666666666")); var creds = new SigningCredentials(key,SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken(null,null,claims,expires: DateTime.Now.AddMinutes(30),signingCredentials: creds); var test = new JwtSecurityTokenHandler().Writetoken(token); return Json(test); } }}自定义策略验证方式(Policy = "")
/// <summary> /// 用户认证需求 /// </summary> internal class UserRequirement : IAuthorizationRequirement { public string UserIDentity { get; private set; } public UserRequirement(string UserIDentityname) { UserIDentity = UserIDentityname; } } /// <summary> /// 使用的用户认证方法 /// </summary> internal class UserAuthorizationHandler: AuthorizationHandler<UserRequirement> { protected overrIDe Task HandleRequirementAsync(AuthorizationHandlerContext context,UserRequirement requirement) { try { if (context.User.FindFirst(requirement.UserIDentity).Value.Equals("true")) { context.Succeed(requirement); } else { context.Fail(); } } catch { context.Fail(); } return Task.CompletedTask; } }startUp.cs 服务里添加服务
services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(option => { option.TokenValIDationParameters = new Microsoft.IDentityModel.Tokens.TokenValIDationParameters { IssuerSigningKey = new SymmetricSecurityKey(EnCoding.UTF8.GetBytes("test6666666666666666666")),ValIDateAudIEnce = false,ValIDateIssuer = false,ValIDateIssuerSigningKey = true,// 签名校对 ValIDatelifetime = true,// 时间校对 }; }); services.AddAuthorization(options => { options.AddPolicy("org",policy => { policy.Requirements.Add(new UserRequirement("org")); }); options.AddPolicy("std",policy => { policy.Requirements.Add(new UserRequirement("std")); }); options.AddPolicy("head",policy => { policy.Requirements.Add(new UserRequirement("head")); }); });最后只要再需要权限验证的接口上添加特性
[Authorize(Policy="{可以是org可以是std可以是head}")]总结
以上是内存溢出为你收集整理的ASP.NET Core 2.2 JWT AUTH全部内容,希望文章能够帮你解决ASP.NET Core 2.2 JWT AUTH所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)