jwt 中token的生成

1:安装依赖包

 

 

 

2:Program.cs注入

 

 

引入命名空间:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

 

var configuration = builder.Configuration;
builder.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

};

});

3:appsetting.json中配置

 

 

"Jwt": {
"SecretKey": "lisheng741@qq.com",
"Issuer": "http://localhost:5000",
"Audience": "http://localhost:5000"
}

 

4:生成token

 

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
namespace webapi_Token.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class UserController : ControllerBase
{
private readonly ILogger<UserController> _logger;
public UserController(ILogger<UserController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetUser")]
public IEnumerable<WeatherForecast> GetUser()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55)
})
.ToArray();
}

public class Const
{

public const string SecurityKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDSfLGu+kcFDcJUCV46J+SbgR0lNc2NqgCGzojQTWW9xqjuzPF3mpisvTggYZSGfBzN+88YLZYbBLrDTUMJ4nTieElbP6SHkBFu8F+7fFBi7w3UPsaAXDr2E2srQYU5ZlKAcFBoNajNWj3sfSVRoYRPdqDTj4WdJlUPSNGz0wgRrQIDAQAB";
public const string Domain = "http://localhost:5000";
}

[AllowAnonymous]//指定此属性应用于的类或方法不需要授权。
[HttpGet]
public IActionResult GetToken(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." });

}

}

}
}

5:验证token

 

 

 

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace webapi_Token.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class PersonController : ControllerBase
{
private readonly ILogger<UserController> _logger;
public PersonController(ILogger<UserController> logger)
{
_logger = logger;
}
[HttpGet]
public ActionResult<IEnumerable<string>> GetPerson1()
{

return new string[] { "value1", "value1" };
}
[HttpGet]
[Authorize]
public ActionResult<IEnumerable<string>> GetPerson2()

{

return new string[] { "value2", "value2" };

}
}
}

 

posted @ 2022-09-15 21:19  .net&new  阅读(914)  评论(0编辑  收藏  举报