使用IdentityServer4生成访问令牌,无需密码

时间:2017-05-25 04:22:53

标签: asp.net-core identityserver4

我使用ROPC流创建了使用IdentityServer4保护的ASP.NET Core WebApi(使用此示例:https://github.com/robisim74/AngularSPAWebAPI)。

如何在没有密码的情况下从服务器手动生成access_token?

5 个答案:

答案 0 :(得分:14)

[HttpPost("loginas/{id}")]
[Authorize(Roles = "admin")]
public async Task<IActionResult> LoginAs(int id, [FromServices] ITokenService TS, 
    [FromServices] IUserClaimsPrincipalFactory<ApplicationUser> principalFactory,
    [FromServices] IdentityServerOptions options)
{
    var Request = new TokenCreationRequest();                        
    var User = await userManager.FindByIdAsync(id.ToString());
    var IdentityPricipal = await principalFactory.CreateAsync(User);
    var IdServerPrincipal = IdentityServerPrincipal.Create(User.Id.ToString(), User.UserName, IdentityPricipal.Claims.ToArray());

    Request.Subject = IdServerPrincipal;
    Request.IncludeAllIdentityClaims = true;
    Request.ValidatedRequest = new ValidatedRequest();
    Request.ValidatedRequest.Subject = Request.Subject;
    Request.ValidatedRequest.SetClient(Config.GetClients().First());
    Request.Resources = new Resources(Config.GetIdentityResources(), Config.GetApiResources());
    Request.ValidatedRequest.Options = options;
    Request.ValidatedRequest.ClientClaims = IdServerPrincipal.Claims.ToArray();

    var Token = await TS.CreateAccessTokenAsync(Request);
    Token.Issuer = "http://" + HttpContext.Request.Host.Value;

    var TokenValue = await TS.CreateSecurityTokenAsync(Token);
    return Ok(TokenValue);
}

对于新发布的IdentityServer 2.0.0,代码需要进行一些修改:

[HttpPost("loginas/{id}")]
[Authorize(Roles = "admin")]
public async Task<IActionResult> LoginAs(int id, [FromServices] ITokenService TS, 
    [FromServices] IUserClaimsPrincipalFactory<ApplicationUser> principalFactory, 
    [FromServices] IdentityServerOptions options)
{
    var Request = new TokenCreationRequest();
    var User = await userManager.FindByIdAsync(id.ToString());
    var IdentityPricipal = await principalFactory.CreateAsync(User);
    var IdentityUser = new IdentityServerUser(User.Id.ToString());
    IdentityUser.AdditionalClaims = IdentityPricipal.Claims.ToArray();
    IdentityUser.DisplayName = User.UserName;
    IdentityUser.AuthenticationTime = System.DateTime.UtcNow;
    IdentityUser.IdentityProvider = IdentityServerConstants.LocalIdentityProvider;
    Request.Subject = IdentityUser.CreatePrincipal();
    Request.IncludeAllIdentityClaims = true;
    Request.ValidatedRequest = new ValidatedRequest();
    Request.ValidatedRequest.Subject = Request.Subject;
    Request.ValidatedRequest.SetClient(Config.GetClients().First());
    Request.Resources = new Resources(Config.GetIdentityResources(), Config.GetApiResources());
    Request.ValidatedRequest.Options = options;
    Request.ValidatedRequest.ClientClaims = IdentityUser.AdditionalClaims;
    var Token = await TS.CreateAccessTokenAsync(Request);
    Token.Issuer = HttpContext.Request.Scheme + "://" + HttpContext.Request.Host.Value;
    var TokenValue = await TS.CreateSecurityTokenAsync(Token);
    return Ok(TokenValue);
}

答案 1 :(得分:3)

这是实现此目的的另一种方法:

首先创建一个名为loginBy

的自定义授予
    public class LoginByGrant : ICustomGrantValidator
    {
        private readonly ApplicationUserManager _userManager;

        public string GrantType => "loginBy";

        public LoginByGrant(ApplicationUserManager userManager)
        {
            _userManager = userManager;
        }     

        public async Task<CustomGrantValidationResult> ValidateAsync(ValidatedTokenRequest request)
        {

            var userId = Guid.Parse(request.Raw.Get("user_id"));

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
                return await Task.FromResult<CustomGrantValidationResult>(new CustomGrantValidationResult("user not exist"));

            var userClaims = await _userManager.GetClaimsAsync(user.Id);

            return
                await Task.FromResult<CustomGrantValidationResult>(new CustomGrantValidationResult(user.Id.ToString(), "custom", userClaims));

        }
    }

然后在身份启动类中添加此自定义授予

    factory.CustomGrantValidators.Add(
                        new Registration<ICustomGrantValidator>(resolver => new LoginByGrant(ApplicaionUserManager)));

最后是您的api

      public async Task<IHttpActionResult> LoginBy(Guid userId)
       {
        var tokenClient = new TokenClient(Constants.TokenEndPoint, Constants.ClientId, Constants.Secret);

        var payload = new { user_id = userId.ToString() };

        var result = await tokenClient.RequestCustomGrantAsync("loginBy", "customScope", payload);

        if (result.IsError)
            return Ok(result.Json);

        return Ok(new { access_token = result.AccessToken, expires_in = result.ExpiresIn});
       }

答案 2 :(得分:2)

继续我对你原来问题的评论。在隐式/混合流中实现模拟功能。如果用户被确定为“超级管理员”,则在身份验证之后向他们提供额外的步骤,以允许他们输入/选择他们希望模拟的帐户。完成后,只需在身份服务器上以所选用户身份建立会话(并可能存储其他声明,表示它是模拟会话以及谁正在进行模拟)。然后将发出任何令牌,就像您是该用户一样,而且无需知道密码。

此外,如果您希望自己创建令牌,请查看IdSrv4提供的ITokenCreationService。您可以将其注入您自己的控制器/服务/中,并使用CreateTokenAsync(令牌令牌)生成带有您喜欢的任何声明的签名JWT。

答案 3 :(得分:1)

使用此:
http://docs.identityserver.io/en/latest/topics/tools.html

使用身份服务器随附的此工具:
在构造函数中声明,以便通过依赖注入进行接收。
IdentityServer4.IdentityServerTools _identityServerTools


    var issuer = "http://" + httpRequest.Host.Value;  
    var token = await _identityServerTools.IssueJwtAsync(  
        30000,  
        issuer,  
        new System.Security.Claims.Claim[1]   
        {  
            new System.Security.Claims.Claim("cpf", cpf)  
        }  
    );

答案 4 :(得分:0)

回答有点晚了。

在我的 Generating Access Token Without Password 情况下,还有另一个 identity server 作为组织 sso,我们的实现已经使用了 IdentityServer,因此我们需要从第二个 IdentityServer 获取用户令牌(在用户登录并重定向到我们的应用程序后),提取sub,检查它是否已经存在(如果没有插入我们本地的IdentityServer),最后选择用户并使用新的grant 为用户获取令牌. 您的客户应该将此 granttype 作为 Allowed Grant 类型(此处为 userexchange):

请参阅:identity server docsduende docs 了解更多信息

    public class TokenExchangeGrantValidator : IExtensionGrantValidator {

        protected readonly UserManager<ToranjApplicationUser> _userManager;
        private readonly IEventService _events;

        public TokenExchangeGrantValidator(ITokenValidator validator, IHttpContextAccessor httpContextAccessor, UserManager<ToranjApplicationUser> userManager
            , IEventService events) {
            _userManager = userManager;
            _events = events;
        }


        public async Task ValidateAsync(ExtensionGrantValidationContext context) {
            var userName = context.Request.Raw.Get("uname");

            if (string.IsNullOrEmpty(userName)) {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
                return;
            }

            var user = await _userManager.FindByNameAsync(userName);
            // or use this one, if you are sending userId
            //var user = await _userManager.FindByIdAsync(userId);
            if (null == user) {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
                return;
            }

            await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id.ToString(), user.UserName, false, context.Request.ClientId));
            var customResponse = new Dictionary<string, object>
                {
                {OidcConstants.TokenResponse.IssuedTokenType, OidcConstants.TokenTypeIdentifiers.AccessToken}
            };
            context.Result = new GrantValidationResult(
                subject: user.Id.ToString(),
                authenticationMethod: GrantType,
                customResponse: customResponse);
        }

        public string GrantType => "userexchange";
    }

在您的 startupConfigureServices 之后的 var builder = services.AddIdentityServer(...) 添加您新创建的类。

    builder.AddExtensionGrantValidator<TokenExchangeGrantValidator>();

调用它来获取令牌很简单:

POST /connect/token

grant_type=userexchange&
scope=yourapi&
uname=yourusername&
client_id=yourClientId
client_secret=secret