我正在使用asp.net声明将敏感信息添加到OAuth Bearer Token中。令牌由wep api生成,并由客户端发送给每个请求的api。
以下是生成令牌
的函数public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
using (var applicationDb = new ApplicationDbContext())
using (var userStore = new UserStore<AppUser>(applicationDb))
{
IApplicationUserService applicationUserService = new ApplicationUserService(userStore, null, null, null);
try
{
var appUser = await applicationUserService.AuthenticateUserAsync(context.UserName, context.Password);
if (appUser == null)
context.SetError("InvalidCredentials", "The email or password that you entered is incorrect.");
else if (!appUser.EmailConfirmed)
context.SetError("EmailVerification", "You must verify your email address before signing in.");
else
{
var roles = applicationUserService.GetUserRoles(appUser.Id);
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.UserId, appUser.Id));
identity.AddClaim(new Claim(ClaimTypes.Roles, string.Join(",", roles.ToArray())));
context.Validated(identity);
}
}
catch (Exception exception)
{
context.SetError("server error", "Server error! Please try again later.");
}
}
}
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
在上面的代码中,我将userId和角色声明添加到令牌。我使用角色来访问Web API中的特定信息。
这种方法有多安全?我可以信任令牌中的信息吗?用户可以篡改令牌并更改角色吗?
如果是这样,我该如何防止这种情况发生?我是否应该使用数据库重新验证令牌中的所有信息?
答案 0 :(得分:0)
只要令牌已签名且签名有效,您就可以了。如果用户篡改了令牌,则签名将不再有效。根据令牌类型,此签名以各种方式完成。这是一篇关于这个主题的精彩文章:
http://www.cloudidentity.com/blog/2014/03/03/principles-of-token-validation/
您可能还会发现这些线程很有用:
Are OAuth2 bearer tokens signed?
How to validate an OAuth 2.0 access token for a resource server?