Keycloak: Retrieving Attributes from JSON API after Authentication - keycloak

Use case is client, SAML or OIDC, will authenticate users via Identity Provider (OIDC say Google; or SAML) - on return of authentication from the Identity Provider, Keycloak will call out to an external JSON API, to obtain further attributes on the user (say lookup by email for telephone number).
Is above possible? Any hints on how to approach will be greatly appreciated.
I was referencing keycloak-json-remote-claim/README.md at master · groupe-sii/keycloak-json-remote-claim · GitHub as an OIDC example – not sure if I’m in correct ballpark.

If you want to add additional user attributes from an external service you should:
Create your own auth flow
Create plugin with Authenticator and AuthenticatorFactory
Implement all logic in Authenticator
Add AuthenticatorFactory to the new flow
Assign new flow to your main client
After these steps your Authenticator will invoke external service and put all needed attrs to the user, each time when user logs in through your main client

Related

How can I create a new social User on KeyCloak via REST APIs?

I have a working KeyCloak installation, and a Laravel backend that uses this to authenticate Users.
The KeyCloack server is already configured with some external ("social") identity providers.
Now I want to create, from PHP backend, new "social" Users on KeyCloak via REST API before they attempt to login the first time.
My goal is to create new Users on backend database with their all profile data, in order to have all the user set-up already done once the user will first login on my app.
Is there a way to do this?
Have I to create the user firsty on KeyCloak and then link it to a social provider in some way?
Or something other?
Thanks
There are essentially two steps required:
You have to create a login-flow, that maps the SAML-User to the local user.
This must contain the "Detect Existing Broker User" and the "Automatically Set Existing User" Execution as Required.
Your Identity Providermust use this as login flow.
Then you have to configure your SAML Identity-Provider to identify the SANL-Atrribute to match the user. Feal free to ask if you need further help for this.

WSO2 Identity Server - Get Tenant ID in JWT

Refer to this link I can add Tenant Domain Name information to our JWT token in sub like username#carbon.super
But I need a way to put Tenand ID info in JWT like a claim. How can I do this for IS 5.10.0 ?
It is not supported by IS OOTB. But you can write a custom claim provider sample and deploy it into the Identity Server. Refer this sample to know how to write a custom claim provider. https://github.com/wso2/samples-is/tree/master/etc/custom-claim-provider.
if it is authorizationcode grant or refresh token grant flow,
Refer this implementation https://github.com/wso2/samples-is/blob/master/etc/custom-claim-provider/src/main/java/org/wso2/carbon/identity/custom/claim/provider/CustomClaimProvider.java#L57 and
additionalClaims.put("tenantName", oAuthTokenReqMessageContext.getOauth2AccessTokenReqDTO().getTenantDomain());
additionalClaims.put("tenantId", OAuth2Util.getTenantId(oAuthTokenReqMessageContext.getOauth2AccessTokenReqDTO().getTenantDomain()));
If it is an implicit granttype or hybrid flow, then refer this and
https://github.com/wso2/samples-is/blob/master/etc/custom-claim-provider/src/main/java/org/wso2/carbon/identity/custom/claim/provider/CustomClaimProvider.java#L44
additionalClaims.put("tenantName", oAuthAuthzReqMessageContext.getTenantDomain());
additionalClaims.put("tenantId", OAuth2Util.getTenantId(oAuthAuthzReqMessageContext.getTenantDomain()));

Flask-OIDC | How to call a specific function after the user logged in

I built a login system using Flask OIDC and Keycloak. In my system, there is some endpoints decorated with oidc.require_login() that calls the Keycloak login page.
My goal is, after the user successfully logged in, my system checks if the user name exists in a specific database.
How can I set a function to be called every time someone successfully logged in with Keycloak and do this verification at the database?
According to your needs there are several ways to create the user in the backend.
The easiest way would be to just check the JWT token on every request. OIDC is based on JWT and that token is available on any request (which should already be done to find user roles etc). So your application can check that JWT and extract the username from it (see here for details about the JWT format). With the username you can check your internal database and create the user, if it doesnt exist. But at that time you'll not have access to any user credentials any more. It is just SSO and you need to trust Keycloak and the JWT... Also - you'll never be informed, if the user will be deleted in Keycloak, which could be an issue.
There is a callback API in Keycloak in form of the Admin URL per client. But the documentation is not clear. It says: It’s used by the Keycloak server to send backend requests to the application for various tasks, like logout users or push revocation policies. But I cannot find a complete list of "tasks". I saw only logout events. see Keycloak documentation and the documentation only talks about that. If I add an admin url to a test client, I did not get any requests at login time.
a different but more complicated way would be to create your own UserStorage SPI in Keycloak. It would be Java of course, but only some classes. There is an HTTP example or have a look at the LDAP user storage SPI, which supports registration too. If you choose that for your realm and a user tries to login to Keycloak (Login form), the SPI can call your backend to check the user. It also could be "used" to create the user in the backend by checking the Keycloak local storage and only if there is a local Keycloak user, call the backend. That isn't the reason, why you should implement the UserStorage SPI, but it's possible. If you think, this is a good idea, I would prefer to use your backend storage as the one and only storage or build a different one, that then could call your real backend in case of a new user. I would use this one by not using Keycloak local stored users but, by using your own database.
next (maybe last one). You can write an EventListener SPI to read all events and only filter the login events, see here and here. I think, that would be the easiest one. But be aware. In that case, the HTTP call to your backend coming from the event itself is based on a normal HTTP request (without OIDC at that time).
The last two examples create a JAR (which is explained in the links). That JAR with the SPI must be deployed in keycloaks standalone/deployments folder. The EventListener should be active by default, the UserStorage SPI must be activated per realm.
But - be aware - Keycloak/SSO/JWT - should not be used by creating users in multiple backends. Syncing the users between all backends in a SSO environment is maybe the wrong way. Most information is located in the JWT or can be called by a backend from one central user identity management. Do not store a user more then once. If you need the user reference in your backend - link just to the username or userid (string) instead of a complete entity.
There is no direct way of doing this, other sotfware like Openam, Okta allow you to trigger specific flows in a post-login configuration.
In keycloak, you can try to create your custom authn flow(using Default Identity Provider, its the only option that allow a redirect), and then select this flow in your Identity provider in post login flow.
The idea here is that after login, the user will be redirected to a link ( an api call that will verify his presence on the external database, and sent him back to keycloak once the verification is done.
More info here

Keycloak as IDP with custom authenticator cant read http POST params login_hint

I have a saml Keycloak client which contains an Authentication Flow Override to a custom keycloak SPI authenticator built in java and deployed in the keycloak env. The authenticator is pretty simple, it displays a username field and takes that username, does a 3rd party check, then returns a verdict (go/nogo, yes/no, etc.)
I have a SAML SP sending a request to this keycloak client (as an IDP). The SP request has a LoginHint. When the Custom Authenticator receives this request in the authenticate method, it cannot retrieve the HTTP Post parameters because there are none.
When user enters their information into the custom authenticators form and clicks submit, and when the action method takes over, the new HTTP POST params are there.
I need to retrieve the loginHint in the authenticate method from the incoming SP SAML request.
anyone know how to do this? i cant read in the login_hint for the life of me.
login_hint and variations thereof belong to OpenID Connect (OIDC) implementations. In SAML you have to use RelayState (recommended) or an authentication request extension.

How to use the metadata file (saml2)

I am working on a project that needs to be integrating SAML2.0. I was thrown into this project suddenly, i need to make it work.
Here is the background: We have created the files and wanted Client Company to integrate using SAML2 to get to our web site. We have sent them the meta datafile.
Now the client company had sent their metadata file. I dont know how and what to do with that file. Any help will be appreciated.
ASP.NET, Framework 4.0
The metadata file basically provides you information of your client. Such as entityID, credential, and so on. If it is an IdP then it also contain couple URLs so that you know where to send different request, e.g. login request, attribute query request. You need to give this metadata to your SAML component so that it know which client it should talk to.
Another main purpose is to establish a trust relationship between SP and IdP.
It's kind of old question but I would like to add some additional information and resources for .NET.
SAML Metadata is used to exchange configuration information between Service Provider and Identity Provider and vice versa. The information can include:
Binging location
Organization name
Contact Person
Single Sign On Url
Single Logout Url
The Metadata can be signed and encrypted so that the information is sent securely. The other side may need the corresponding public key to validate and decrypt it and then can be used to understand and establish the connection with the SP or IdP.
You can see some more info at the following blog posts:
http://samlcomponent.net/constructing-saml-metadata-xml-for-single-sign-on-idp/
http://samlcomponent.net/how-to-create-saml-metadata-xml-for-service-provider/
Security Assertion Markup Language (SAML) is a standard for logging users into applications based on their sessions in another context. This single sign-on (SSO) login standard has significant advantages over logging in using a username/password:
1.No need to type in credentials
2.No need to remember and renew passwords
3.No weak passwords
It is easy to manage all applications in one tree using SAML SSO login.
How actually SAML works:
The user accesses the remote application using a link on an intranet, a bookmark, or similar and the application loads.
The application identifies the user’s origin (by application subdomain, user IP address, or similar) and redirects the user back to the identity provider, asking for authentication. This is the authentication request.
The user either has an existing active browser session with the identity provider or establishes one by logging into the identity provider.
The identity provider builds the authentication response in the form of an XML-document containing the user’s username or email address, signs it using an X.509 certificate, and posts this information to the service provider.
The service provider, which already knows the identity provider and has a certificate fingerprint, retrieves the authentication response and validates it using the certificate fingerprint.
The identity of the user is established and the user is provided with app access.
Take a look at the metadata SAML 2.0 specification to check what elements must be read by your implementation.
If you are looking for a SAML2 .Net Tookit, take a look to this thread of stackoverflow
Also take a look on SAML open source implementations to learn how others resolved this problem before:
SimpleSAMLphp (PHP implementation Idp/SP). (Metadata parser)
Shibboleth IdP (Java) (opensaml2) / SP (C)
spring-security-saml: SP (Java) (metadata files)
Jboss (Java)
Metadata is nothing but the xml file containing all the information required by your SAML implementation to talk with host. you can extract information from this meta to get the desired information required. Like public/private keys.
I hope you are also using certificate to talk with host on secure manner.
This key is required for handshaking with unknown host system.