Programmatically authenticate user with Keycloak in java
Programmatically authenticate user with Keycloak in java
I have been looking through the Keycloak documentation but cannot see how to do this. With Java, I'd like to take a valid userid and password and then generate a token. How can I do this?
1 Answer
1
--EDIT 2018-08-31--
You can use the Authorization Client Java API. Once you have created an AuthzClient object, you can pass the username and password to the AuthzClient#authorization(username, password) or AuthzClient#obtainAccessToken(username, password) method to authenticate the user and get the access token (and/or ID token in the first case):
// create a new instance based on the configuration defined in keycloak-authz.json
AuthzClient authzClient = AuthzClient.create();
// send the authorization request to the server in order to
// obtain an access token granted to the user
AccessTokenResponse response = authzClient.obtainAccessToken("alice", "alice");
On a side note, if possible, you'd rather reuse one of the Keycloak Java Adapters to cover more features, such as other authentication methods (the user is typically redirected to Keycloack WUI where you can enforce very flexible authentication and authorization policies).
I changed my answer. It should be more relevant to what you need. Let me know.
– Cyril Dangerville
Aug 31 at 12:28
Thanks for changing your answer. It looks like what I'm looking for. I tried to implement it and I get a runtime exception: could not find any keycloak.json file in classpath. Any ideas what I might be missing?
– user840930
Sep 2 at 17:13
okay, I think I understand what this keycloak.json file is and where it comes from, but now where does it go?
– user840930
Sep 2 at 17:36
According to documentation (check the first link in my answer), the keycloak.json must be on your application's classpath.
– Cyril Dangerville
Sep 2 at 18:10
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thanks for the reply. Okay. What I am looking for, is to use the Java API for keycloak to authenticate a user.
– user840930
Aug 31 at 2:26