更新时间:2022-12-06 16:52:10
你对 JWT 的理解不错.但这里有一些更正和一些建议.
Your understanding of JWTs is good. But here are a couple corrections and some recommendations.
您的 JWT 可以包含您想要的任何信息.用户名、生日、电子邮件等.您可以使用基于声明的授权来执行此操作.然后,您只需告诉您的提供商使用声明原则中的这些声明创建 JWT.以下代码来自该会员重启示例,它向您展示了这是如何完成的.
Your JWTs can contain any information you want. The users name, birthdate, email, etc. You do this with claims based authorization. You then just tell your provider to make a JWT with these claims from the Claims Principle. The following code is from that Membership Reboot example and it shows you how this is done.
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var svc = context.OwinContext.Environment.GetUserAccountService<UserAccount>();
UserAccount user;
if (svc.Authenticate("users", context.UserName, context.Password, out user))
{
var claims = user.GetAllClaims();
var id = new System.Security.Claims.ClaimsIdentity(claims, "MembershipReboot");
context.Validated(id);
}
return base.GrantResourceOwnerCredentials(context);
}
这使您可以精确控制谁在访问您的资源,而所有这些都不会影响您的处理器密集型身份验证服务.
This allows you to control with precision whom is accessing your resources, all without hitting your processor intensive authentication service.
实现令牌提供程序的一种非常简单的方法是使用 Microsoft 的 OAuth 授权服务器 在您的 WebAPI 项目中.它为您提供了为您的 API 制作 OAuth 服务器所需的基本知识.
A very easy way to implement a Token provider is to use Microsoft's OAuth Authorization Server in your WebAPI project. It give you the bare bones of what you need to make a OAuth server for your API.
您还可以查看 Thinktecture 的 Identity Server,它会给您带来很多好处更容易控制用户.例如,您可以使用身份服务器轻松实现刷新令牌,其中用户经过身份验证一次,然后在一定时间(可能是一个月)内,他们可以继续从身份服务器获取短期 JWT.刷新令牌很好,因为它们可以被撤销,而 JWT 不能.此解决方案的缺点是您需要设置另一台或两台服务器来托管身份服务.
You could also look into Thinktecture's Identity Server which would give you much easier control over users. For instance, you can easily implement refresh tokens with identity server where the user is authenticated once and then for a certain amount of time (maybe a month) they can continue getting short lived JWTs from the Identity Server. The refresh tokens are good because they can be revoked, whereas JWTs cannot. The downside of this solution is that you need to set up another server or two to host the Identity service.
要处理您的最后一点,即入侵者不应复制最后一个请求以访问资源,您必须至少使用 SSL. 这将保护令牌在运输中.
To deal with your last point, that an intruder should not be able to copy the last request to get access to a resource, you must use SSL at a bare minimum. This will protect the token in transport.
如果您要保护一些极其敏感的东西,您应该将令牌的生命周期保持在一个非常短的时间窗口内.如果您保护的是不那么敏感的东西,您可以延长使用寿命.如果令牌有效,则令牌越长,如果用户的机器受到威胁,攻击者将不得不冒充已验证用户的时间窗口就越大.
If you are protecting something extremely sensitive, you should keep the token lifetime to a very short window of time. If you are protecting something less sensitive, you could make the lifetime longer. The longer the token if valid, the larger the window of time a attacker will have to impersonate the authenticated user if the user's machine is compromised.