ASP.NET Core WebAPI中使用JWT Bearer认证和授权
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了ASP.NET Core WebAPI中使用JWT Bearer认证和授权,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4509字,纯文字阅读大概需要7分钟。
内容图文
1、添加包
Microsoft.AspNetCore.Authentication.JwtBearer
2、在Startup类的ConfigureServices方法里面注入服务:
public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { SaveSigninToken = true,//保存token,后台验证token是否生效(重要) ValidateIssuer = true,//是否验证Issuer ValidateAudience = true,//是否验证Audience ValidateLifetime = true,//是否验证失效时间 ValidateIssuerSigningKey = true,//是否验证SecurityKey ValidAudience = "sukcore",//Audience ValidIssuer = "sukcore",//Issuer,这两项和前面签发jwt的设置一致 IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("BB3647441FFA4B5DB4E64A29B53CE525")) }; options.Events = new JwtBearerEvents() { OnChallenge = context => { context.HandleResponse(); context.Response.Clear(); context.Response.ContentType = "application/json"; context.Response.StatusCode = 401; context.Response.WriteAsync(new { message = "授权未通过", status = false, code = 401 }.Serialize()); return Task.CompletedTask; } }; }); }public void ConfigureServices(IServiceCollection services)
3、在Startup类的Configure方法里面添加
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //身份验证 app.UseAuthentication(); //授权 app.UseAuthorization(); }public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
4、接下来做权限校验
在需要授权的api控制器或者Action上新增 [Authorize] 标记
public class TokenService : ITokenService { private readonly JwtSetting _jwtSetting; public TokenService(IOptions<JwtSetting> option) { _jwtSetting = option.Value; } public string GetToken(UserEntity user) { //创建用户身份标识,这里可以随意加入自定义的参数,key可以自己随便起 var claims = new[] { new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") , new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"), new Claim(ClaimTypes.NameIdentifier, user.username.ToString()), new Claim("Id", user.id.ToString()), new Claim("Name", user.username.ToString()) }; //sign the token using a secret key.This secret will be shared between your API and anything that needs to check that the token is legit. var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSetting.SecurityKey)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); //.NET Core’s JwtSecurityToken class takes on the heavy lifting and actually creates the token. var token = new JwtSecurityToken( //颁发者 issuer: _jwtSetting.Issuer, //接收者 audience: _jwtSetting.Audience, //过期时间 expires: DateTime.Now.AddMinutes(30), //签名证书 signingCredentials: creds, //自定义参数 claims: claims ); var jwtToken = new JwtSecurityTokenHandler().WriteToken(token); return jwtToken; } }public string GetToken(UserEntity user)
/// <summary> /// 权限(获取Token) /// </summary> [Route("api/[controller]/[action]")] public class AuthController : ApiController { private readonly ITokenService _tokenService; /// <summary> /// /// </summary> public AuthController(ITokenService tokenService) { _tokenService = tokenService; } /// <summary> /// 获取Token /// </summary> /// <param name="user"></param> /// <returns></returns> [HttpPost] public MethodResult GetToken(UserEntity user) { var token = _tokenService.GetToken(user); var response = new { Status = true, Token = token, Type = "Bearer" }; return new MethodResult(response); } }public class AuthController : ApiController
public class UserEntity { /// <summary> /// ID /// </summary> public int id { get; set; } /// <summary> /// 姓名 /// </summary> public string username { get; set; } /// <summary> /// 密码 /// </summary> public string password { get; set; } }public class UserEntity
public class JwtSetting { /// <summary> /// 颁发者 /// </summary> public string Issuer { get; set; } /// <summary> /// 接收者 /// </summary> public string Audience { get; set; } /// <summary> /// 令牌密码 /// </summary> public string SecurityKey { get; set; } /// <summary> /// 过期时间 /// </summary> public long ExpireSeconds { get; set; } /// <summary> /// 签名 /// </summary> public SigningCredentials Credentials { get { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecurityKey)); return new SigningCredentials(key, SecurityAlgorithms.HmacSha256); } } }public class JwtSetting
参考如下链接
https://www.cnblogs.com/ZhengHengWU/p/12574045.html
内容总结
以上是互联网集市为您收集整理的ASP.NET Core WebAPI中使用JWT Bearer认证和授权全部内容,希望文章能够帮你解决ASP.NET Core WebAPI中使用JWT Bearer认证和授权所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。