首页 / 历史 / 近代史 / 正文

asp源代码(jwt-在asp.net core中使用jwt)

放大字体  缩小字体 来源:妙丽女鞋 2026-04-15 13:34  浏览次数:5

新建一个空的asp.net core项目:

新建一个类Const放置一些常量:

jwt-在asp.net core中使用jwtnerror="javascript:errorimg.call(this);">

public class Const{    public const string SecurityKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDSfLGu+kcFDcJUCV46J+SbgR0lNc2NqgCGzojQTWW9xqjuzPF3mpisvTggYZSGfBzN+88YLZYbBLrDTUMJ4nTieElbP6SHkBFu8F+7fFBi7w3UPsaAXDr2E2srQYU5ZlKAcFBoNajNWj3sfSVRoYRPdqDTj4WdJlUPSNGz0wgRrQIDAQAB";    public const string Domain = "http://localhost:5000";}
jwt-在asp.net core中使用jwtnerror="javascript:errorimg.call(this);">

Startup中向应用添加jwt验证服务:

jwt-在asp.net core中使用jwtnerror="javascript:errorimg.call(this);">

//添加jwt验证:services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)    .AddJwtBearer(options => {        options.TokenValidationParameters = new TokenValidationParameters        {            ValidateIssuer = true,//是否验证Issuer                        ValidateAudience = true,//是否验证Audience                        ValidateLifetime = true,//是否验证失效时间                        ClockSkew = TimeSpan.FromSeconds(30),            ValidateIssuerSigningKey = true,//是否验证SecurityKey                        ValidAudience = Const.Domain,//Audience                        ValidIssuer = Const.Domain,//Issuer,这两项和前面签发jwt的设置一致                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey))//拿到SecurityKey                    };    });
jwt-在asp.net core中使用jwtnerror="javascript:errorimg.call(this);">

管道中添加jwt验证:

//添加jwt验证app.UseAuthentication();

由于管道有执行顺序的特性,因此最好放在管道的开始位置。

添加登录获取token的接口:

jwt-在asp.net core中使用jwtnerror="javascript:errorimg.call(this);">

[ApiController][Route("[controller]")]public class AuthController : Controllerbase{    [AllowAnonymous]//指定此属性应用于的类或方法不需要授权。    [HttpGet]    public IActionResult Get(string userName, string pwd)    {        if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(pwd))        {            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.Name, userName)                };            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey));            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);            var token = new JwtSecurityToken(                issuer: Const.Domain,                audience: Const.Domain,                claims: claims,                expires: DateTime.Now.AddMinutes(30),                signingCredentials: creds);             return Ok(new            {                token = new JwtSecurityTokenHandler().WriteToken(token)            });        }        else        {            return BadRequest(new { message = "username or password is incorrect." });        }    }}
jwt-在asp.net core中使用jwtnerror="javascript:errorimg.call(this);">

方法中对用户名和密码的验证只是简单的验空,实际应用中会更复杂,也会与数据库中的数据比对。

接下来就是对jwt的应用了。

新建HomeController,用于验证jwt是否成功启用:

jwt-在asp.net core中使用jwtnerror="javascript:errorimg.call(this);">

[ApiController][Route("[controller]")]public class HomeController : Controllerbase{    [HttpGet]    [Route("api/value1")]    public ActionResult<IEnumerable<string>> Get()    {        return new string[] { "value1", "value1" };    }     [HttpGet]    [Route("api/value2")]    [Authorize]    public ActionResult<IEnumerable<string>> Get2()    {        return new string[] { "value2", "value2" };    }}
jwt-在asp.net core中使用jwtnerror="javascript:errorimg.call(this);">

其中Get()方法不需要验证,Get2()需要验证。


测试:

先测试Get()方法(接口名称时api/value1),因为此方法不用验证:

jwt-在asp.net core中使用jwtnerror="javascript:errorimg.call(this);">

验证成功!!!

接下来测试Get2():

jwt-在asp.net core中使用jwtnerror="javascript:errorimg.call(this);">

访问Get2()方法的接口名api/value2,粘贴上面获得的token到header中:

jwt-在asp.net core中使用jwtnerror="javascript:errorimg.call(this);">

验证成功!!!

总结:至此,使用asp.net core 自带的jwt方法就完成了。


源码地址:https://gitee.com/jingboweilanGO/Demo_jwt_core.git

说明:Demo-jwt-core是本篇文章涉及到的源码,是使用asp.net core 自带的jwt方法;

#红红火火过大年# 春节即将来临了,后天准备回老家了。可能不会及时的更新文章了。谢谢大家支持。

打赏
0相关评论
热门搜索排行
精彩图片
友情链接
声明:本站信息均由用户注册后自行发布,本站不承担任何法律责任。如有侵权请告知立立即做删除处理。
违法不良信息举报邮箱:115904045
头条快讯网 版权所有
中国互联网举报中心