Web API - JWT - 匿名访问的默认用户

时间:2015-07-29 20:40:04

标签: c# authentication asp.net-web-api jwt

我正在使用Web API和JSON Web令牌设置网站。但是,该站点的一部分是开放的匿名访问,因此最终用户可以提交各种问题/答案的信息。一切都很好,但我想防止恶意用户篡改另一个正在进行的提交。

为每个匿名用户提供"默认"在声明集合中具有随机哈希值的用户有助于防止这种情况发生?然后,可以将哈希值与在与数据库交互时将其作为查询条件的一部分使用的任何请求进行比较。

public class CustomOAuthProvider : OAuthAuthorizationServerProvider
{
    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
        return Task.FromResult<object>(null);
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        ApplicationUser user;
        if ((string.IsNullOrWhiteSpace(context.UserName) || context.UserName.ToLower() == "undefined") 
            && (string.IsNullOrWhiteSpace(context.Password) || context.Password.ToLower() == "undefined"))
        {
            user = await userManager.FindAsync(@"guest", @"somePassword");
        }
        else
        {
            user = await userManager.FindAsync(context.UserName, context.Password);
        }

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        var oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
        var ticket = new AuthenticationTicket(oAuthIdentity, null);            
        context.Validated(ticket);
    }
}

在匿名用户的声明集合中设置ClaimTypes.Hash值,以便随每个后续请求一起传递。

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);

        if (!userIdentity.HasClaim(x => x.Type == ClaimTypes.Hash))
        {
            var bytes = new byte[16];
            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(bytes);
                userIdentity.AddClaim(new System.Security.Claims.Claim(ClaimTypes.Hash, BitConverter.ToString(bytes).Replace("-", "").ToLower()));
            }
        }

        return userIdentity;
    }
}

此方法和/或更好的替代方案是否存在任何问题?

0 个答案:

没有答案
相关问题