首页 > 解决方案 > IdentityServer4 checkPasswordAsync 更改默认错误消息(登录)

问题描述

我正在使用 IdentityServer4。我想在登录时更改固定的警告消息。我该怎么做。

   public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            var existUser = await _userManager.FindByEmailAsync(context.UserName);
            if (existUser == null) return;
            var passwordCheck = await _userManager.CheckPasswordAsync(existUser, context.Password);
            if (passwordCheck == false) return;

            context.Result = new GrantValidationResult(existUser.Id.ToString(), OidcConstants.AuthenticationMethods.Password);
   
        }

标签: asp.net-coreidentityserver4identity

解决方案


假设您使用默认模板 AspNetCore.Identity 和 IdentityServer4。

您需要覆盖 IdentityErrorDescriber 上的消息。

public class CustomIdentityErrorDescriber : IdentityErrorDescriber
{
    public override IdentityError DefaultError()
    {
        return new IdentityError
        {
            Code = nameof(DefaultError),
            Description = "Your custom message"
        };
    }
}

启动时在您的 AddIdentity 上添加 AddErrorDescriber:

  services.AddIdentity<IdentityUser, IdentityRole>()
     .AddErrorDescriber<CustomIdentityErrorDescriber>();

更新

它将打破 OIDC 规范......但我们开始吧。

添加一个 CustomResourceOwnerPasswordValidator

public class CustomResourceOwnerPasswordValidator<TUser> : IResourceOwnerPasswordValidator
       where TUser : class
    {
        private readonly SignInManager<TUser> _signInManager;
        private readonly UserManager<TUser> _userManager;
        private readonly ILogger<CustomResourceOwnerPasswordValidator<TUser>> _logger;

        /// <summary>
        /// Initializes a new instance of the <see cref="CustomResourceOwnerPasswordValidator{TUser}"/> class.
        /// </summary>
        /// <param name="userManager">The user manager.</param>
        /// <param name="signInManager">The sign in manager.</param>
        /// <param name="logger">The logger.</param>
        public CustomResourceOwnerPasswordValidator(
            UserManager<TUser> userManager,
            SignInManager<TUser> signInManager,
            ILogger<CustomResourceOwnerPasswordValidator<TUser>> logger)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
        }

        /// <summary>
        /// Validates the resource owner password credential
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public virtual async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            var user = await _userManager.FindByNameAsync(context.UserName);
            if (user != null)
            {
                var result = await _signInManager.CheckPasswordSignInAsync(user, context.Password, true);
                if (result.Succeeded)
                {
                    var sub = await _userManager.GetUserIdAsync(user);

                    _logger.LogInformation("Credentials validated for username: {username}", context.UserName);

                    context.Result = new GrantValidationResult(sub, OidcConstants.AuthenticationMethods.Password);
                    return;
                }
                else if (result.IsLockedOut)
                {
                    _logger.LogInformation("Authentication failed for username: {username}, reason: locked out", context.UserName);
                }
                else if (result.IsNotAllowed)
                {
                    _logger.LogInformation("Authentication failed for username: {username}, reason: not allowed", context.UserName);
                }
                else
                {
                    _logger.LogInformation("Authentication failed for username: {username}, reason: invalid credentials", context.UserName);
                }
            }
            else
            {
                _logger.LogInformation("No user found matching username: {username}", context.UserName);
            }

            context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant,"your custom message here");
        }
    }

启动时:

services.AddIdentityServer()
.AddResourceOwnerValidator<CustomResourceOwnerPasswordValidator<User>>();//Must be last, but before AddDeveloperSigningCredential

将返回:

"{"error":"invalid_grant","error_description":"your custom message here"}"

推荐阅读