gpt4 book ai didi

c# - ASP.NET 中的 JWT token 验证

转载 作者:行者123 更新时间:2023-11-30 21:35:12 29 4
gpt4 key购买 nike

我正在 ASP.NET 中编写一个 API,它公开两个端点:一个用于生成 JWT token ,另一个用于验证给定的 token 。

token 生成似乎工作正常:

 [HttpPost]
public IHttpActionResult Token()
{
var headerAuth = HttpContext.Current.Request.Headers["Authorization"];
if (headerAuth.ToString().StartsWith("Basic"))
{
var credValue = headerAuth.ToString().Substring("Basic".Length).Trim();
var usernameAndPassEnc = Encoding.UTF8.GetString(Convert.FromBase64String(credValue));
var usernameAndPass = usernameAndPassEnc.Split(':');

LdapAuthentication ldap = new LdapAuthentication();

if (ldap.IsAuthenticated(usernameAndPass[0], usernameAndPass[1]))
{
var claimsData = new[] { new Claim(ClaimTypes.Name, usernameAndPass[0]) };
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secret"));
var signInCred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);
var tokenString = new JwtSecurityToken(
issuer: "http://my.website.com",
audience: "http://my.tokenissuer.com",
expires: DateTime.Now.AddMinutes(1),
claims: claimsData,
signingCredentials: signInCred
);

var token = new JwtSecurityTokenHandler().WriteToken(tokenString);
return Ok(token);
}
}

return BadRequest("Bad request");
}

但我不知道如何验证给定的 token ,在 ASP.NET Core 中我在这个 whay 中实现它(效果很好):

public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "http://my.website.com",
ValidAudience = "http://my.tokenissuer.com",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secret"))
};
});
services.AddMvc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseAuthentication();
app.UseMvc();
}

那么,如何在 ASP.NET 中验证 JWT token ?

最佳答案

为此,您可以编写中间件或使用现有的授权过滤器并覆盖它。使用以下方式验证token

    public static bool ValidateToken(string authToken) // Retrieve token from request header
{
var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = this.GetValidationParameters();

SecurityToken validatedToken;
IPrincipal principal = tokenHandler.ValidateToken(authToken, validationParameters, out validatedToken);
Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
return true;
}

private static TokenValidationParameters GetValidationParameters()
{
return new TokenValidationParameters
{
IssuerSigningToken = new System.ServiceModel.Security.Tokens.BinarySecretSecurityToken(symmetricKey), //Key used for token generation
ValidIssuer = issuerName,
ValidAudience = allowedAudience,
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true
};
}

关于c# - ASP.NET 中的 JWT token 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49407749/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com