首页 文章

使用asp.net声明使用OAuth Bearer Tokens发送敏感信息

提问于
浏览
0

我正在使用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中的特定信息 .

这种方法有多安全?我可以信任令牌中的信息吗?用户可以篡改令牌并更改角色吗?

如果是这样,我怎么能阻止这个?我是否应该使用数据库重新验证令牌中的所有信息?

1 回答

相关问题