How to integrate or make use of KeyCloak user database in my application?

隐身守侯 提交于 2019-12-03 20:32:57

I'm in the process of a conversion almost exactly like this. I had users and roles in a home grown database and used Wildfly security via a custom UsernamePasswordLoginModule. I'm now moving to Keycloak.

I too had database referential integrity for users to other things. What I've done is to not remove the user table completely but to move all of the user attributes over to Keycloak. I maintain a user table with a very minimal amount of information and a primary key that is the Keycloak "user name" (a GUID). You can get that from getting the principal:

@Context
private SecurityContext sc;

...

String userId = sc.getUserPrincipal().getName();

Now I have a key that I can use with JPA to get a user and tie them to anything they need to be tied to.

There will be a further step where I get more data from Keycloak about the user. Right now I have enough in the AccessToken:

KeycloakPrincipal<KeycloakSecurityContext> kcPrincipal = (KeycloakPrincipal<KeycloakSecurityContext>)(sc.getUserPrincipal());
AccessToken accessToken = kcPrincipal.getKeycloakSecurityContext().getToken();

String firstName = accessToken.getGivenName();
String lastName = accessToken.getFamilyName();

but I will eventually have custom user attributes pushed over to the Keycloak side that I'll need to get access to.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!