ASP.NET Core中独立创建的JWT未被授权。
创始人
2024-11-12 03:00:27
0

在ASP.NET Core中,可以使用JWT(JSON Web Token)来进行身份验证和授权。如果独立创建的JWT未被授权,可以按照以下步骤进行解决:

  1. 确保在身份验证中间件中配置了JWT身份验证。在Startup.cs文件的ConfigureServices方法中添加以下代码:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "your-issuer",
            ValidAudience = "your-audience",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"))
        };
    });
  1. 在需要授权的Controller或Action上添加[Authorize]特性。例如:
[Authorize]
public class MyController : Controller
{
    // ...
}
  1. 在生成和验证JWT的代码中,确保使用正确的Issuer、Audience和签名密钥。例如:
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("your-secret-key");
var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(new Claim[]
    {
        new Claim(ClaimTypes.Name, "your-username")
    }),
    Expires = DateTime.UtcNow.AddHours(1),
    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var jwtToken = tokenHandler.WriteToken(token);
  1. 在请求中包含正确的JWT,在请求的Authorization头中添加"Bearer "前缀和JWT值。例如:
GET /api/myendpoint HTTP/1.1
Host: localhost:5000
Authorization: Bearer your-jwt-token

通过以上步骤,可以确保独立创建的JWT在ASP.NET Core中能够正确授权。

相关内容

热门资讯

透视辅助!wepoker底牌透... 透视辅助!wepoker底牌透视脚本怎样安装,wepoker透视底牌,AA德州教程(本来是真的有挂)...
透视挂透视!aapoker辅助... 【福星临门,好运相随】;透视挂透视!aapoker辅助插件工具,wepoker轻量版透视系统,总结教...
透视软件!aapoker辅助插... 透视软件!aapoker辅助插件工具,wepoker有透视吗,微扑克教程(真是有挂)是由北京得aap...
透视模拟器!aapkoer德州... 透视模拟器!aapkoer德州辅助挂下载,wepoker透视版下载,解说技巧(原本是真的有挂)是一款...
透视能赢!aapoker可以开... 透视能赢!aapoker可以开挂吗,wepoker轻量版书签,科技教程(原先真的有挂)准备好在aap...
透视计算!德普之星透视辅助io... 相信很多朋友都在电脑上玩过德普之星透视辅助ios吧,但是很多朋友都在抱怨用电脑玩起来不方便。为此小编...
透视有挂!wpk辅助插件叫什么... 透视有挂!wpk辅助插件叫什么,hhpoker可以控制牌吗,技巧教程(本然是有挂),支持语音通讯、好...
透视免费!hhpoker辅助软... 透视免费!hhpoker辅助软件,哈糖大菠萝有挂吗5个常用方法,AI教程(原先真的是有挂);亲真的是...
透视中牌率!wpk透视辅助方法... 透视中牌率!wpk透视辅助方法,wepoker开辅助能查到吗,系统教程(果然有挂);原来确实真的有挂...
透视真的!wpk透视辅助方法,... 透视真的!wpk透视辅助方法,wepoker开辅助能查到吗,科技教程(其实真的是有挂);wpk透视辅...