I am adding sensitive information into a OAuth Bearer Token using asp.net claims. The token is generated by wep api and sent by the client to api for every request.
Here is the function that generates the token
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();
}
In the code above, I am adding userId and role claims to the token. I am using the roles to give access to specific information in the web API.
How safe is this approach? Can I trust the information in the token? can the user tamper with the token and change the role?
If so, how can I prevent from this? Should I be re-validating all information in the token with database?