如何使用密码授予流更改IdentityServer4的默认错误消息

时间:2019-04-29 10:13:20

标签: c# asp.net-core asp.net-identity identityserver4

将IdentityServer4与资源所有者密码流和asp.net Identity一起使用时,如果登录失败,它将始终返回相同的错误消息。密码无效或用户已被锁定都没关系。

{
    "error": "invalid_grant",
    "error_description": "invalid_username_or_password"
}

这是身份和身份服务器的配置:

services.AddIdentityCore<User>()
    .AddEntityFrameworkStores<ApplicationDBContext>()
    .AddDefaultTokenProviders()
    .AddUserManager<UserManager<User>>()
    .AddSignInManager<ApplicationSignInManager>();

var builder = services.AddIdentityServer()
    .AddInMemoryIdentityResources(Config.IdentityResources)
    .AddInMemoryApiResources(Config.Apis)
    .AddInMemoryClients(Config.Clients)
    .AddAspNetIdentity<User>();

当我使用具有asp.net身份的资源所有者密码流时,没有用于登录用户的自定义用户服务。那么如何根据登录过程中发生的情况显示错误消息?

1 个答案:

答案 0 :(得分:0)

我需要这样做。请参阅下面的实现示例。

using IdentityServer4.Validation;
using IdentityServerAspNetIdentity.Models;
using Microsoft.AspNetCore.Identity;
using System;
using System.Threading.Tasks;

public class PasswordValidator : IResourceOwnerPasswordValidator
{

    private readonly UserManager<ApplicationUser> _userManager;

    public PasswordValidator(UserManager<ApplicationUser> userMan)
    {
        _userManager = userMan;
    }

    /// <summary>
    /// Use this method to customise responses back from password grant
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
    {
        var user = await _userManager.FindByNameAsync(context.UserName);
        bool isLockedOut = await _userManager.IsLockedOutAsync(user);

        if (isLockedOut)
        {
            context.Result.Error = "User is locked out";
        }

    }
}

此外,将其添加到startup.cs。在AddAspNetIdentity之后添加:

services.AddTransient<IResourceOwnerPasswordValidator, PasswordValidator>();