Search code examples
keycloak

Keycloack Custom Identity provider


I'm trying to create a new idp for my purposes. I created all, it get shown on "identity providers" and i can enable it, so on login screen i see my new Idp. I implemented "performLogin" to do a redirect to my service, then my service redirect back to keycloak with some query data that i will read on "callback" implemented as "Endpoint". I can get all i need from "callback", i can create a new user from that, assign a role etc What i'm missing is to authenticate the user:

session.getContext().getAuthenticationSession() // it's empty
callback.getAndVerifyAuthenticationSession() // I'm unable to make it work

Some help? Seems like i have to return a "BrokeredIdentityContext identity" in "return callback.authenticated(identity)" after set an AuthenticationSessionModel.


Solution

  • You are right. If you implement your callback e.g., like this:

    class MyIdentityProvider extends AbstractIdentityProvider<IdentityProviderModel> {
    
        ....
    
        @Override
        public Object callback(RealmModel realm, org.keycloak.broker.provider.IdentityProvider.AuthenticationCallback callback, EventBuilder event) {
          return new MyAuthenticationEndpoint(realm, callback, event, this, session);
        }
    
    }
    

    you can do all sorts of stuff in MyAuthenticationEndpoint, but you have to create a BrokeredIdentityContext:

    @GET
    public Response handleMyResponse(
        @QueryParam("state") String state,
        @QueryParam("parameter1") String parameter1,
        @QueryParam("parameter2") String parameter2,
        @QueryParam("parameter2") String parameter3
    ) {
      // your service has to provide the keycloak's state back, once finished with the processing, so keycloak can pick it up again
      AuthenticationSessionModel authenticationSessionModel = this.callback.getAndVerifyAuthenticationSession(state);
      // Retrieve all kinds of data from our service in order to create the (new) user    
    
      BrokeredIdentityContext brokerContext = new BrokeredIdentityContext(theUserId);
      brokerContext.setAuthenticationSession(authenticationSessionModel);
      brokerContext.setIdpConfig(myIdentityProvider.getConfig());
      brokerContext.setIdp(myIdentityProvider);
      brokerContext.setToken(theTokenFromMyService);
    
      return callback.authenticated(brokerContext);
    }