gpt4 book ai didi

c# - 如何手动验证 JWT Asp.Net Core?

转载 作者:太空狗 更新时间:2023-10-29 17:57:52 26 4
gpt4 key购买 nike

有数百万的指南,但似乎没有一个能满足我的需要。我正在创建一个身份验证服务器,它只需要发布和验证/重新发布 token 。所以我无法创建中间件类来“验证”cookie 或 header 。我只是收到字符串的 POST,我需要以这种方式验证 token ,而不是 .net 核心提供的 Authorize 中间件。

我的初创公司由我可以开始工作的唯一 token 发行者示例组成。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

app.UseExceptionHandler("/Home/Error");

app.UseStaticFiles();
var secretKey = "mysupersecret_secretkey!123";
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));

var options = new TokenProviderOptions
{

// The signing key must match!
Audience = "AllApplications",
SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),

Issuer = "Authentication"
};
app.UseMiddleware<TokenProviderMiddleware>(Microsoft.Extensions.Options.Options.Create(options));

我可以在创建时使用中间件,因为我只需要拦截用户名和密码的正文。中间件从前面的 Startup.cs 代码中获取选项,检查请求路径并从下面看到的上下文中生成 token 。

private async Task GenerateToken(HttpContext context)
{
CredentialUser usr = new CredentialUser();

using (var bodyReader = new StreamReader(context.Request.Body))
{
string body = await bodyReader.ReadToEndAsync();
usr = JsonConvert.DeserializeObject<CredentialUser>(body);
}

///get user from Credentials put it in user variable. If null send bad request

var now = DateTime.UtcNow;

// Specifically add the jti (random nonce), iat (issued timestamp), and sub (subject/user) claims.
// You can add other claims here, if you want:
var claims = new Claim[]
{
new Claim(JwtRegisteredClaimNames.Sub, JsonConvert.SerializeObject(user)),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, now.ToString(), ClaimValueTypes.Integer64)
};

// Create the JWT and write it to a string
var jwt = new JwtSecurityToken(
issuer: _options.Issuer,
audience: _options.Audience,
claims: claims,
notBefore: now,
expires: now.Add(_options.Expiration),
signingCredentials: _options.SigningCredentials);
var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

///fill response with jwt
}

上面的这一大段代码将反序列化 CredentialUser json,然后执行返回用户对象的存储过程。然后我将添加三个 claim ,然后将其运回。

我能够成功生成一个 jwt,并使用像 jwt.io 这样的在线工具,我输入了 key ,该工具说它是有效的,有一个我可以使用的对象

    {
"sub": " {User_Object_Here} ",
"jti": "96914b3b-74e2-4a68-a248-989f7d126bb1",
"iat": "6/28/2017 4:48:15 PM",
"nbf": 1498668495,
"exp": 1498668795,
"iss": "Authentication",
"aud": "AllApplications"
}

我遇到的问题是了解如何根据签名手动检查声明。因为这是一个发布和验证 token 的服务器。设置 Authorize 中间件不是一个选项,就像大多数指南那样。下面我尝试验证 token 。

[Route("api/[controller]")]
public class ValidateController : Controller
{

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Validate(string token)
{
var validationParameters = new TokenProviderOptions()
{
Audience = "AllMyApplications",
SigningCredentials = new
SigningCredentials("mysupersecret_secretkey!123",
SecurityAlgorithms.HmacSha256),

Issuer = "Authentication"
};
var decodedJwt = new JwtSecurityTokenHandler().ReadJwtToken(token);
var valid = new JwtSecurityTokenHandler().ValidateToken(token, //The problem is here
/// I need to be able to pass in the .net TokenValidParameters, even though
/// I have a unique jwt that is TokenProviderOptions. I also don't know how to get my user object out of my claims
}
}

最佳答案

主要从ASP.Net Core源代码中借用了这段代码:https://github.com/aspnet/Security/blob/dev/src/Microsoft.AspNetCore.Authentication.JwtBearer/JwtBearerHandler.cs#L45

从该代码我创建了这个函数:

private string Authenticate(string token) {
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
List<Exception> validationFailures = null;
SecurityToken validatedToken;
var validator = new JwtSecurityTokenHandler();

// These need to match the values used to generate the token
TokenValidationParameters validationParameters = new TokenValidationParameters();
validationParameters.ValidIssuer = "http://localhost:5000";
validationParameters.ValidAudience = "http://localhost:5000";
validationParameters.IssuerSigningKey = key;
validationParameters.ValidateIssuerSigningKey = true;
validationParameters.ValidateAudience = true;

if (validator.CanReadToken(token))
{
ClaimsPrincipal principal;
try
{
// This line throws if invalid
principal = validator.ValidateToken(token, validationParameters, out validatedToken);

// If we got here then the token is valid
if (principal.HasClaim(c => c.Type == ClaimTypes.Email))
{
return principal.Claims.Where(c => c.Type == ClaimTypes.Email).First().Value;
}
}
catch (Exception e)
{
_logger.LogError(null, e);
}
}

return String.Empty;
}

validationParameters 需要与您的 GenerateToken 函数中的那些相匹配,然后它应该可以正常验证。

关于c# - 如何手动验证 JWT Asp.Net Core?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44808800/

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