【发布时间】:2016-04-19 17:38:02
【问题描述】:
我正在使用 asp.net 声明将敏感信息添加到 OAuth 持有者令牌中。令牌由 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 和 role 声明添加到令牌。我正在使用这些角色来授予对 Web API 中特定信息的访问权限。
这种方法有多安全?我可以信任令牌中的信息吗?用户可以篡改令牌并更改角色吗?
如果是这样,我该如何防止这种情况发生?我应该使用数据库重新验证令牌中的所有信息吗?
【问题讨论】:
标签: asp.net-web-api oauth claims-based-identity bearer-token