日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

token验证失败_ASP.NET CORE WEBAPI JWT 带BEARER的TOKEN

發布時間:2023/11/27 生活经验 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 token验证失败_ASP.NET CORE WEBAPI JWT 带BEARER的TOKEN 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

JWT主要由三部分構成,header、 payload 、signature,下面給出詳細的TOKEN生成及使用代碼。

1、注冊JWT服務

public void ConfigureServices(IServiceCollection services)

{

//注冊JWT

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(opt => {

opt.TokenValidationParameters = new TokenValidationParameters

{

NameClaimType = JwtClaimTypes.Name,

RoleClaimType = JwtClaimTypes.Role,

ValidateIssuer = true,

ValidateAudience = true,

ValidateLifetime = true,

ValidateIssuerSigningKey = true,

ValidAudience = Configuration["JWT:Audience"],

ValidIssuer = Configuration["JWT:Issuer"],

//ClockSkew = TimeSpan.FromSeconds(300), //時間偏移量

ClockSkew = TimeSpan.Zero,

IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["JWT:SecurityKey"]))

};

});

}

2、配置JWT,啟用認證

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

{

//啟用驗證

app.UseAuthorization();

}

3、配置appsettings.json

"Logging": {

"LogLevel": {

"Default": "Information",

"Microsoft": "Warning",

"Microsoft.Hosting.Lifetime": "Information"

}

},

"JWT": {

"SecurityKey": "fcf6dc95-6ba4-48ff-b584-a10fd61a054b",

"Issuer": "robinxu",

"Audience": "robinxu"

},

"AllowedHosts": "*"

}

4、服務端生成Token

///

/// 生成Token

///

///

///

[AllowAnonymous]

[HttpPost]

[Route("Token")]

public IActionResult Token([FromBody]TokenRequest request)

{

if (request.userName == "robin" && request.password == "666666")

{

var claims = new[]

{

new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),

new Claim("name", request.userName)

};

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecurityKey"]));

var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);

var token = new JwtSecurityToken(

issuer: _configuration["JWT:Issuer"],

audience: _configuration["JWT:Audience"],

claims: claims,

notBefore: DateTime.Now,

expires: DateTime.Now.AddMinutes(30),

signingCredentials: creds);

return Ok(new

{

token = new JwtSecurityTokenHandler().WriteToken(token),

date = DateTime.Now.ToString()

});

}

else

{

return BadRequest("賬號或密碼驗證失敗");

}

}

public class TokenRequest

{

public string userName { get; set; }

public string password { get; set; }

}

5、獲取Token

請求:

{

"userName":"robin",

"password":"666666"

}

響應:

{

"token": "eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmZTczM2EyZC00MDYyLTRhOGEtOTNhZC00YThkMjliNDQyN2EiLCJuYW1lIjoicm9iaW4iLCJuYmYiOjE1ODE2ODEyMjQsImV4cCI6MTU4MTY4MzAyNCwiaXNzIjoieHVndW9odWkiLCJhdWQiOiJ4dWd1b2h1aSJ9.ttxs3NnZ3fTTvvcMymhpMPBTgP61oQuqc-klVwCYuoY",

"date": "2020/2/14 19:53:45"

}

6、驗證Token請求地址

//

/// 測試

///

///

[HttpGet]

[Route("Test")]

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

public string Test()

{

return Guid.NewGuid().ToString();

}

7、驗證Token請求圖示

swagger驗證token請求示例圖

postman驗證token請求示例圖

總結

以上是生活随笔為你收集整理的token验证失败_ASP.NET CORE WEBAPI JWT 带BEARER的TOKEN的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。