我刚刚使用此Github指南https://github.com/cuongle/WebApi.Jwt添加了Jwt身份验证。但是,我不确定是否已正确实施。
这是我使用邮递员进行测试的方式
验证用户身份后,我将获得身份验证令牌并将其粘贴到授权区域中以进行另一个请求。然后,我调用具有JwtAuthenticate属性的下一个函数(函数A)。结果按预期返回。
但是,当我从授权区域中删除令牌并将请求重新发送给函数时,我仍然得到与仍然经过验证相同的结果。我尝试打开一个新标签页,然后再试一次,但同样的事情发生了。
我不确定我是否正确实施了此操作。
这是我的代码
ApiController
[HttpGet]
[AllowAnonymous]
public String Authenticate(String Username, String Password)
{
LoginDTO lgdto = new LoginDTO
{
Email = Username,
Password = Password
};
if (accountsData.Authenticate(lgdto))
{
return JwtManager.JwtManager.GenerateToken(Username);
}
else
{
return AspNetEventLogs.AccessDenied;
}
}
[JwtAuthenticate]
[HttpGet]
public String Validate()
{
return "Validated";
}
我的JwtAuthenticate文件
public class JwtAuthenticate : 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;
if (authorization == null || authorization.Scheme != "Bearer")
{
context.ErrorResult = new AuthenticationFailureResult("Incorrect Scheme", request);
return;
}
if (string.IsNullOrEmpty(authorization.Parameter))
{
context.ErrorResult = new AuthenticationFailureResult("Missing Jwt Token", request);
return;
}
var token = authorization.Parameter;
var principal = await AuthenticateJwtToken(token);
if (principal == null)
context.ErrorResult = new AuthenticationFailureResult("Invalid token", request);
else
context.Principal = principal;
}
private static bool ValidateToken(string token, out string username)
{
username = null;
var simplePrinciple = JwtManager.JwtManager.GetPrincipal(token);
var identity = simplePrinciple?.Identity as ClaimsIdentity;
if (identity == null)
return false;
if (!identity.IsAuthenticated)
return false;
var usernameClaim = identity.FindFirst(ClaimTypes.Name);
username = usernameClaim?.Value;
if (string.IsNullOrEmpty(username))
return false;
// More validate to check whether username exists in system
return true;
}
protected Task<IPrincipal> AuthenticateJwtToken(string token)
{
string username;
if (ValidateToken(token, out username))
{
// based on username to get more information from database in order to build local identity
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username)
// Add more claims if needed: Roles, ...
};
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);
}
}