# Create AccessToken inside custom SPI

**URL:** <https://forum.keycloak.org/t/create-accesstoken-inside-custom-spi/248>\
**Category:** Extending the server\
**Created:** [October 29, 2019, 10:42am UTC](https://forum.keycloak.org/t/create-accesstoken-inside-custom-spi/248 "2019-10-29T10:42:54Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![antonio-giovannetti](https://yyz2.discourse-cdn.com/free1/user_avatar/forum.keycloak.org/antonio-giovannetti/32/95_2.png) [@antonio-giovannetti](https://forum.keycloak.org/u/antonio-giovannetti)\
**Post date:** [October 29, 2019, 10:42am UTC](https://forum.keycloak.org/t/create-accesstoken-inside-custom-spi/248/1 "2019-10-29T10:42:54Z")

</div>

Hello  
I am writing a custom SPI to implement `EventListenerProvider`. I want to create inside it’s implementation an AccessToken to invoke a client (SSO secured) belonging to current realm; I need the access token to invoke the client’s REST Api.  
Any idea?

Thanks

---

<div class="post-metadata">

**Author:** ![stianst](https://yyz2.discourse-cdn.com/free1/user_avatar/forum.keycloak.org/stianst/32/16_2.png) [@stianst](https://forum.keycloak.org/u/stianst)\
**Post date:** [October 31, 2019, 2:43pm UTC](https://forum.keycloak.org/t/create-accesstoken-inside-custom-spi/248/2 "2019-10-31T14:43:22Z")

</div>

There’s private APIs in Keycloak that can create a token, but I would probably rather try to use a service account and get tokens using client credentials grant. It may also be better to not use bearer tokens for this as it could easily be a bit of a chicken and an egg kinda thing.

---

<div class="post-metadata">

**Author:** ![joao-rebelo](https://yyz2.discourse-cdn.com/free1/user_avatar/forum.keycloak.org/joao-rebelo/32/3487_2.png) [@joao-rebelo](https://forum.keycloak.org/u/joao-rebelo)\
**Post date:** [May 20, 2020, 11:48am UTC](https://forum.keycloak.org/t/create-accesstoken-inside-custom-spi/248/3 "2020-05-20T11:48:46Z")

</div>

Is there any example / documentation on how to get the tokens of such a service account programmatically.  
In my case I have an authentication plugin that needs to make a call to a client within the realm, and I would like to authenticate the service account to get the tokens and make the call.

Additionally wondering if we can cache / keep it active between plugin calls (different authentication requests)

Regards  
João

---

<div class="post-metadata">

**Author:** ![mashedpotatoes](https://avatars.discourse-cdn.com/v4/letter/m/90db22/32.png) [@mashedpotatoes](https://forum.keycloak.org/u/mashedpotatoes)\
**Post date:** [May 22, 2020, 7:55am UTC](https://forum.keycloak.org/t/create-accesstoken-inside-custom-spi/248/4 "2020-05-22T07:55:08Z")

</div>

Hi,  
+1

I need to perform some setup tasks in another app since registration should be done in keycloak from now on.

I tried using the client credentials grant routine from `org.keycloak.protocol.oidc.endpoints.TokenEndpoint` in my EventListenerProvider implementation but end up duplicating a lot of code and ultimately get a `java.lang.NoClassDefFoundError: org/keycloak/services/managers/AuthenticationSessionManager`  
The keycloak services artifact is included with scope `provided` in my module.  
Also I do not want the service account login to be linked to the user session in any way, which I am not sure of with this method.

Best regards

---

<div class="post-metadata">

**Author:** ![alvaroarenashel](https://avatars.discourse-cdn.com/v4/letter/a/46a35a/32.png) [@alvaroarenashel](https://forum.keycloak.org/u/alvaroarenashel)\
**Post date:** [December 1, 2020, 10:27am UTC](https://forum.keycloak.org/t/create-accesstoken-inside-custom-spi/248/5 "2020-12-01T10:27:49Z")

</div>

Is there some documentation regarding this topic?

---

<div class="post-metadata">

**Author:** ![trotman23](https://yyz2.discourse-cdn.com/free1/user_avatar/forum.keycloak.org/trotman23/32/821_2.png) [@trotman23](https://forum.keycloak.org/u/trotman23)\
**Post date:** [December 1, 2020, 7:56pm UTC](https://forum.keycloak.org/t/create-accesstoken-inside-custom-spi/248/6 "2020-12-01T19:56:17Z")

</div>

> Is there some documentation regarding this topic?

The [keycloak-quickstarts](https://github.com/keycloak/keycloak-quickstarts) repository has an example [action-token-authenticator](https://github.com/keycloak/keycloak-quickstarts/tree/latest/action-token-authenticator), but it’s not specifically for access tokens.

> In my case I have an authentication plugin that needs to make a call to a client within the realm, and I would like to authenticate the service account to get the tokens and make the call.

We had this same use-case on my team. We started with a service account and client credentials grant as @stianst described, but it felt clunky so we ended up using the private APIs previously referred to.

Within your authenticator, you can create an `AccessToken` from [its representation](https://github.com/keycloak/keycloak/blob/11.0.3/core/src/main/java/org/keycloak/representations/AccessToken.java), and then sign it using the [`JWSBuilder`](https://github.com/keycloak/keycloak/blob/11.0.3/core/src/main/java/org/keycloak/jose/jws/JWSBuilder.java) and contextual data from the [`KeycloakSession`](https://github.com/keycloak/keycloak/blob/11.0.3/server-spi/src/main/java/org/keycloak/models/KeycloakSession.java).

A modified snippet from our implementation:

```java
import org.keycloak.authentication.AuthenticationFlowContext;
import org.keycloak.authentication.Authenticator;
import org.keycloak.jose.jws.JWSBuilder;
import org.keycloak.models.KeyManager;
import org.keycloak.representations.AccessToken;
import org.keycloak.services.Urls;

class ExampleToken implements Authenticator {

    @Override
    void authenticate(AuthenticationFlowContext context) {
        // build token and set required attributes
        AccessToken token = new AccessToken();
        token.audience("foo");
        token.subject("bar");
        token.issuedFor("baz");
        token.type("Bearer");
        token.setOtherClaims("foobar", "foobaz");
        token.issuer(
                Urls.realmIssuer(
                        context.getUriInfo().getBaseUri(), context.getRealm().getName()
                )
        );
        token.issuedNow();
        token.expiration((int) (token.getIat() + 120L)); // 2 minute lifespan
        
        // sign token
        KeyManager.ActiveRsaKey key = context.getSession().keys().getActiveRsaKey(context.getRealm());
        String signedToken = new JWSBuilder()
                .kid(key.getKid())
                .type("JWT")
                .jsonContent(token)
                .rsa256(key.getPrivateKey());
    }
}

```

Disclaimer: this was written a few years ago and relies on some _deprecated_ methods.

---

<div class="post-metadata">

**Author:** ![alvaroarenashel](https://avatars.discourse-cdn.com/v4/letter/a/46a35a/32.png) [@alvaroarenashel](https://forum.keycloak.org/u/alvaroarenashel)\
**Post date:** [December 2, 2020, 3:40pm UTC](https://forum.keycloak.org/t/create-accesstoken-inside-custom-spi/248/7 "2020-12-02T15:40:33Z")

</div>

Thank you @trotman23 for the quick reply. I will check into it.
