ASP.NETCore中JWT授权出现问题。
创始人
2024-09-18 15:02:10
0
  1. 首先,在Startup.cs中添加JWT授权配置:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,

            ValidIssuer = Configuration["Jwt:Issuer"],
            ValidAudience = Configuration["Jwt:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
        };
    });

以上代码中,我们使用AddAuthentication来添加JWT授权,并指定授权方案为JwtBearerDefaults.AuthenticationScheme。然后,我们使用AddJwtBearer来添加JWT Bearer授权程序,并配置TokenValidationParameters,该参数允许我们指定哪些值需要验证以确保JWT有效。

  1. 接下来,在应用中使用JWT授权:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class MyProtectedController : ControllerBase
{
    // 使用授权验证进行身份验证和授权
    [HttpGet]
    public IActionResult Get()
    {
        // 可以在这里访问受保护的资源
        return Ok();
    }
}

使用Authorize特性,我们指定了授权方案为JwtBearerDefaults.AuthenticationScheme。这表示只有经过授权才能访问此控制器的操作。可以在该操作中访问受保护资源。

  1. 最后,在应用中生成JWT令牌:
private string GenerateJwtToken(User user)
{
    var claims = new List
    {
        new Claim(JwtRegisteredClaimNames.Sub, user.Email),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
        new Claim(ClaimTypes.Role, "Admin")
    };

    var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]));
    var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
    var expires = DateTime.Now.AddDays(Convert.ToInt32(Configuration["Jwt:ExpireDays"]));

    var token = new JwtSecurityToken(
        Configuration["Jwt:Issuer"],
        Configuration["Jwt:Audience"],
        claims,
        expires: expires,
        signingCredentials: credentials
    );

    return new JwtSecurityTokenHandler().WriteToken(token);
}

以上代码中,我们生成一个包含用户信息和声明的JWT令牌,其中我们使用SymmetricSecurityKey和SigningCredentials来对令牌进行加密,以确保令牌不会被篡改。最后,我们返回写入的令牌。

相关内容

热门资讯

安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
omi系统和安卓系统哪个好,揭... OMI系统和安卓系统哪个好?这个问题就像是在问“苹果和橘子哪个更甜”,每个人都有自己的答案。今天,我...
原生ios和安卓系统,原生对比... 亲爱的读者们,你是否曾好奇过,为什么你的iPhone和安卓手机在操作体验上有着天壤之别?今天,就让我...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...