我使用ROPC流创建了使用IdentityServer4保护的ASP.NET Core WebApi(使用此示例:
https://github.com/robisim74/AngularSPAWebAPI).
如何在没有密码的情况下从服务器手动生成access_token?
解决方法
[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] 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); }