fbede
fbede

Reputation: 901

Are there any IdentityServer4 services (not endpoints) for token handling?

I have IdentityServer4 and a web API in the same project, and I would like to use IdentityServer token handling in my own controllers, e.g. I want to issue tokens, refreshtokens, revoke tokens in my own controllers without calling other built in IdentityServer endpoints. Are there services for stuff like this I'm missing? Thanks

I need something like someIdentityServerService below

    [AllowAnonymous]
    [HttpPost("login")]
    public async Task<IActionResult> Login([FromBody] UserLoginRequestDto model)
    {
        var user = await _userManager.FindByEmailAsync(model.Email);
        if (user == null || !await _userManager.CheckPasswordAsync(user, model.Password))
        {
            return BadRequest("Wrong email or password!");
        }

        // do some other stuff

        var token = await someIdentityServerService.GetAccessTokenAsync(user);
        return Ok(token);
    }

Upvotes: 1

Views: 679

Answers (1)

d_f
d_f

Reputation: 4859

I do not think, it's a good idea to come inside the certified IdP and call the internals in your own order, not the order defined by the protocol.

Nevertheless you can do that by looking into the implementation and invoking or overriding. Identity Server is highly flexible, using standard DI you can override almost everything.

for instance

            var identityPricipal = await _principalFactory.CreateAsync(user);
            var identityUser = new IdentityServerUser(user.Id.ToString())
            {
                AdditionalClaims = identityPricipal.Claims.ToArray(),
                DisplayName = user.UserName,
                AuthenticationTime = DateTime.UtcNow,
                IdentityProvider = IdentityServerConstants.LocalIdentityProvider
            };
            var request = new TokenCreationRequest();
            request.Subject = identityUser.CreatePrincipal();
            request.IncludeAllIdentityClaims = true;
            request.ValidatedRequest = new ValidatedRequest();
            request.ValidatedRequest.Subject = request.Subject;
            request.ValidatedRequest.SetClient(Config.Clients().First());
            request.Resources = new Resources(Config.IdentityResources(), new List<ApiResource>());
            request.ValidatedRequest.Options = _options;
            request.ValidatedRequest.ClientClaims = identityUser.AdditionalClaims;
            var token = await _tokenService.CreateAccessTokenAsync(request);
            token.Issuer = "...";
            return await _tokenService.CreateSecurityTokenAsync(token);

More convenient way of creating tokens is to employ IdentityServerTools. However that's aim is to help calling external APIs from within IdSrv, not issuing any JWTs by external requests.

If you need to request JWTs from outside (and follow the protocol), you have to use predefined endpoints and signatures.

Upvotes: 1

Related Questions