使用时是否可以检查IP地址?
System.IdentityModel.Tokens.Jwt
在ASP.NET核心Web API应用程序中?
我考虑添加一个声明,其中包含请求它的用户的IP,并以某种方式检查每个请求。通常我会用
OnActionExecuting
在ASP.NET MVC中。
是否有基于中间件/授权的解决方案?
我创建了这样的JWT令牌声明:
private IEnumerable<Claim> getStandardClaims(IdentityUser user)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim("ipaddress", HttpContext.Connection.RemoteIpAddress.ToString())
};
return claims;
}
这就是JWT数据的样子:
{
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "username",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier": "5a6b3eb8-ed7f-48c6-b10c-a279ffd4f7c8",
"sub": "username",
"jti": "44c95b53-bfba-4f33-b4c3-834127605432",
"ipaddress": "::1",
"exp": 1542707081,
"iss": "https://localhost:5001/",
"aud": "https://localhost:5001/"
}
编辑:JWT索赔的可能解决方案?
也许我必须阅读这样的声明(测试代码,无空检查等):
var auth = HttpContext.Request.Headers.FirstOrDefault(x => x.Key == "Authorization");
string token = auth.Value[0].Split(' ')[1];
JwtTokenService<RefreshToken, string> jwtService = new JwtTokenService<RefreshToken, string>(null);
var principal = jwtService.GetPrincipalFromExpiredToken(token, _config["Jwt:Key"]);
Claim ipClaim = principal.FindFirst(claim => claim.Type == "ipaddress");
这是GetPrincipalFromExpiredToken方法:
public ClaimsPrincipal GetPrincipalFromExpiredToken(string token, string securityKey)
{
var tokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey)),
ValidateLifetime = false
};
var tokenHandler = new JwtSecurityTokenHandler();
SecurityToken securityToken;
var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out securityToken);
var jwtSecurityToken = securityToken as JwtSecurityToken;
if (jwtSecurityToken == null || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
throw new SecurityTokenException("Invalid token");
return principal;
}