gpt4 book ai didi

c# - 在 .NET Core Web API 中使用自定义属性的 JWT 身份验证

转载 作者:行者123 更新时间:2023-12-04 13:39:41 24 4
gpt4 key购买 nike

我目前正在将我的 Web API 2.0 转换为 .NET Core Web API,但有一个部分我正在努力解决。

在我现有的 API 中,我有一个包含以下代码的属性:

public class JwtAuthentication : Attribute, IAuthenticationFilter
{
public string Realm { get; set; }

public bool AllowMultiple => false;

public async Task AuthenticateAsync(
HttpAuthenticationContext context,
CancellationToken cancellationToken)
{
var request = context.Request;

var authorization = request.Headers.Authorization;

// checking request header value having required scheme "Bearer" or not.
if (authorization == null ||
authorization.Scheme.ToLowerInvariant() != "bearer" ||
string.IsNullOrEmpty(authorization.Parameter))
{
context.ErrorResult = new AuthenticationFailureResult("JWT Token is Missing", request);
return;
}

// Getting Token value from header values.
var token = authorization.Parameter;
var principal = await AuthJwtToken(token);

if (principal == null)
{
context.ErrorResult = new AuthenticationFailureResult("Invalid JWT Token", request);
}
else
{
context.Principal = principal;
}
}

private static bool ValidateToken(string token, out ICollection<Claim> claims)
{
claims = null;

var simplePrinciple = JwtAuthManager.GetPrincipal(token);

if (simplePrinciple == null)
{
return false;
}

var identity = simplePrinciple.Identity as ClaimsIdentity;

if (identity == null)
{
return false;
}

if (!identity.IsAuthenticated)
{
return false;
}

var usernameClaim = identity.FindFirst(ClaimTypes.Name);
var emailClaim = identity.FindFirst(ClaimTypes.Email);

var username = usernameClaim?.Value;
var email = emailClaim?.Value;

if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(email))
{
return false;
}

claims = identity.Claims.ToList();

return true;
}

protected Task<IPrincipal> AuthJwtToken(string token)
{
if (ValidateToken(token, out var claims))
{
var identity = new ClaimsIdentity(claims, "Jwt");

IPrincipal user = new ClaimsPrincipal(identity);

return Task.FromResult(user);
}

return Task.FromResult<IPrincipal>(null);
}

public Task ChallengeAsync(
HttpAuthenticationChallengeContext context,
CancellationToken cancellationToken)
{
Challenge(context);
return Task.FromResult(0);
}

private void Challenge(HttpAuthenticationChallengeContext context)
{
string parameter = null;

if (!string.IsNullOrEmpty(Realm))
{
parameter = "realm=\"" + Realm + "\"";
}

context.ChallengeWith("Bearer", parameter);
}
}

如果我理解正确,在 ASP.NET Core 中,我所要做的就是在我的启动中定义以下内容:
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:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});

我不确定我是否需要以下内容,但它看起来像:
services.AddMvc(); 

我所能做的就是使用 [Authorize] 属性,但是如果我想复制我在 ASP.NET MVC Web API 2.0 中使用的属性怎么办?

我是不是该?我喜欢这样一个事实,即我可以看到 token 出现问题的地方。如果可以以相同的方式使用它并假设可以这样做,我该怎么做?在谷歌搜索解决方案时,我没有找到任何有用的东西?

谢谢。

最佳答案

基于@dropoutcoder 的回答,

Eventsoptions.Events为空,我收到错误 object reference not set...为了解决这个问题,我改用了以下内容:

options.Events = new JwtBearerEvents()
{
OnMessageReceived = context =>
{
return Task.CompletedTask;
},
OnAuthenticationFailed = context =>
{
return Task.CompletedTask;
},
OnTokenValidated = context =>
{
return Task.CompletedTask;
},
OnChallenge = context =>
{
return Task.CompletedTask;
},
OnForbidden = context =>
{
return Task.CompletedTask;
}
};

关于c# - 在 .NET Core Web API 中使用自定义属性的 JWT 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59331249/

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