标签:result wstring packages api family size 查看 操作系统 datetime
public ActionResult<IEnumerable<string>>Get() { //创建声明Token数组 var claim =newClaim[] { newClaim(ClaimTypes.Name,"ylc"), newClaim(JwtRegisteredClaimNames.Email,"1234567@11.com"), newClaim(JwtRegisteredClaimNames.Sub,"Sub") }; //实例化一个token对象 var token =newJwtSecurityToken(claims:claim); //生成token var jwtToken =newJwtSecurityTokenHandler().WriteToken(token); returnnewstring[]{ jwtToken }; }
publicJwtSecurityToken(string issuer =null, string audience =null, IEnumerable<Claim> claims =null, DateTime? notBefore =default(DateTime?), DateTime? expires =default(DateTime?), SigningCredentials signingCredentials =null) { if(expires.HasValue && notBefore.HasValue && notBefore >= expires) { throw LogHelper.LogExceptionMessage(newArgumentException(LogHelper.FormatInvariant("IDX12401: Expires: ‘{0}‘ must be after NotBefore: ‘{1}‘.", expires.Value, notBefore.Value))); } Payload =newJwtPayload(issuer, audience, claims, notBefore, expires); Header =newJwtHeader(signingCredentials); RawSignature = string.Empty; }
我们就声明五个参数
[HttpGet] public ActionResult<IEnumerable<string>>Get() { //创建声明Token数组 var claim =newClaim[] { newClaim(ClaimTypes.Name,"ylc"), newClaim(JwtRegisteredClaimNames.Email,"1234567@11.com"), newClaim(JwtRegisteredClaimNames.Sub,"Sub") }; var key =newSymmetricSecurityKey(Encoding.UTF8.GetBytes("yanglingcong@qq.com"));//密钥大小要超过128bt,最少要16位 //实例化一个token对象 var token =newJwtSecurityToken( issuer:"http://localhost:5000",//发起人:当前项目 audience:"http://localhost:5000",//订阅:我们需要谁去使用这个Token claims: claim,//声明的数组 expires:DateTime.Now.AddDays(1),//当前时间加一小时,一小时后过期 signingCredentials:newSigningCredentials(key,SecurityAlgorithms.HmacSha256)//数字签名 第一部分是密钥,第二部分是加密方式 ); var jwtToken =newJwtSecurityTokenHandler().WriteToken(token); returnnewstring[]{ jwtToken }; }
var claim =newClaim[] { newClaim(ClaimTypes.Name,"ylc"), newClaim(JwtRegisteredClaimNames.Email,"1234567@11.com"), newClaim(JwtRegisteredClaimNames.Sub,"Sub") };
[HttpGet("{str}")] public ActionResult<IEnumerable<string>>Get(string str) { ///获取Token的三种方式 //第一种直接用JwtSecurityTokenHandler提供的read方法 var jwtHander =newJwtSecurityTokenHandler(); JwtSecurityToken jwtSecurityToken = jwtHander.ReadJwtToken(str); //第二种 通过User对象获取 var sub = User.FindFirst(d => d.Type =="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")?.Value; //第三种 通过Httpcontext上下文中直接获取 var name = _accessor.HttpContext.User.Identity.Name; var Claims = _accessor.HttpContext.User.Claims; var claimstype =(from item in Claims where item.Type == JwtRegisteredClaimNames.Email select item.Value).ToList(); returnnewstring[]{ JsonConvert.SerializeObject(jwtSecurityToken), sub, name, JsonConvert.SerializeObject(claimstype)}; }
publicvoidConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddSingleton<IHttpContextAccessor,HttpContextAccessor>(); var keyBase64 ="yanglingcong@qq.com"; var keyByeArray = Encoding.ASCII.GetBytes(keyBase64); var signkey =newSymmetricSecurityKey(keyByeArray); var tokenValidationParameters =newTokenValidationParameters//生成了一个Token验证的参数 { ValidateIssuerSigningKey =true, IssuerSigningKey = signkey,//数字签名 ValidateIssuer =true, ValidIssuer ="http://localhost:5000",//发行人 ValidateAudience =true, ValidAudience ="http://localhost:5000",//订阅人 ValidateLifetime =true, ClockSkew = TimeSpan.FromSeconds(30), RequireExpirationTime =true, }; services.AddAuthentication("Bearer")//注入服务 1.开启Bearer认证 2.注册Bearer服务 .AddJwtBearer(o => { o.TokenValidationParameters = tokenValidationParameters; }); }
app.UseAuthentication();//开启中间件
还差最后一步就是登录,只有登录认证了Bearer才能将Token转化成相应的服务
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();//把 JwtSecurityToken清除
标签:result wstring packages api family size 查看 操作系统 datetime
原文地址:https://www.cnblogs.com/cg-ww/p/12654364.html