上下文
我有一个工作的WebApi2应用程序,它使用开箱即用的令牌验证,就像在最初的Visual项目模板中一样。
我想将一个自定义数据添加到生成的令牌中,然后在随后的api调用发生呈现此令牌的情况时检查该自定义数据。
例如,我想在创建令牌时存储调用方的IP地址,然后在验证令牌时检查使用令牌的调用是否具有完全相同的IP。
我找到了定制类
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
在我的项目中,我还看到OAuthOptions
被配置为在启动时使用自定义类。
我想在哪里添加自定义令牌数据( ip):
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
在这里,我可以将它作为自定义数据添加到票据属性中。
问题
但是,我无法找出在哪种方法中对令牌进行检查是否有此数据,并且它与实际调用的ip相匹配,如果不匹配,则认为令牌无效吗?
发布于 2017-02-16 01:09:08
当您决定实现OAuthAuthorizationServerProvider
时,您是完全正确的。现在,您需要添加这样的内容:
private ClaimsIdentity CreateIdentity(User user, string authenticationType)
{
var identity = new ClaimsIdentity(authenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, user.Login));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.UserID.ToString())); // or ip instead of user.UserID if you need
return identity;
}
然后在Grant...
方法(例如GrantResourceOwnerCredentials
)中使用它,如下所示:
ClaimsIdentity identity = CreateIdentity(user, context.Options.AuthenticationType);
context.Validated(identity);
然后,当请求到达webapi控制器时,您可以在自定义属性中检查数据:
Claim userIdClaim = ((ClaimsIdentity)actionContext.ControllerContext.RequestContext.Principal.Identity)
.Claims
.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
希望能帮上忙。
https://stackoverflow.com/questions/42247628
复制相似问题