Fetch Logged In Username in a webapp secured with Keycloak












16















I have secured an enterprise application with Keycloak using standard wildfly based Keycloak adapters. Issue that I am facing is that the rest web services when invoked, needs to know the username that is currently logged in. How do I get the logged in user information from Keycloak?



I tried using SecurityContext , WebListener etc. But none of them are able to give me the required details.










share|improve this question



























    16















    I have secured an enterprise application with Keycloak using standard wildfly based Keycloak adapters. Issue that I am facing is that the rest web services when invoked, needs to know the username that is currently logged in. How do I get the logged in user information from Keycloak?



    I tried using SecurityContext , WebListener etc. But none of them are able to give me the required details.










    share|improve this question

























      16












      16








      16


      6






      I have secured an enterprise application with Keycloak using standard wildfly based Keycloak adapters. Issue that I am facing is that the rest web services when invoked, needs to know the username that is currently logged in. How do I get the logged in user information from Keycloak?



      I tried using SecurityContext , WebListener etc. But none of them are able to give me the required details.










      share|improve this question














      I have secured an enterprise application with Keycloak using standard wildfly based Keycloak adapters. Issue that I am facing is that the rest web services when invoked, needs to know the username that is currently logged in. How do I get the logged in user information from Keycloak?



      I tried using SecurityContext , WebListener etc. But none of them are able to give me the required details.







      java jboss ejb keycloak






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Aug 6 '15 at 19:17









      aksappyaksappy

      1,93411534




      1,93411534
























          5 Answers
          5






          active

          oldest

          votes


















          24














          You get all user information from the security context.



          Example:



          public class Greeter {

          @Context
          SecurityContext sc;

          @GET
          @Produces(MediaType.APPLICATION_JSON)
          public String sayHello() {

          // this will set the user id as userName
          String userName = sc.getUserPrincipal().getName();

          if (sc.getUserPrincipal() instanceof KeycloakPrincipal) {
          KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) sc.getUserPrincipal();

          // this is how to get the real userName (or rather the login name)
          userName = kp.getKeycloakSecurityContext().getIdToken().getPreferredUsername();
          }

          return "{ message : "Hello " + userName + "" }";
          }


          For the security context to be propagated you have to have a security domain configured as described in the:
          JBoss/Wildfly Adapter configuration






          share|improve this answer





















          • 3





            KeyCloakPrincipal is available from keycloak-core, for those who don't know where it is from

            – aksappy
            Aug 7 '15 at 17:26













          • That did the trick.. Thank you @sebplorenz

            – aksappy
            Aug 8 '15 at 3:11






          • 7





            In case of Null Pointer Exceptions like I encountered when using the above with bearer token: Use getToken() instead of getIdToken()

            – devrys
            Apr 2 '16 at 23:22



















          16














          You may also set the principal-attribute property in the keycloak.json file of your web app to preferred_username.






          share|improve this answer





















          • 3





            Thank you! This is a much better answer than the accepted one because your answer allows a SessionContext.getCallerPrincipal.getName to work at the EJB layer if the entire project was packaged as an EAR.

            – j.con
            Jan 24 '17 at 18:43



















          1














          Need to add standalone.xml next line:



          <principal-attribute>preferred_username</principal-attribute>


          Example:



          <subsystem xmlns="urn:jboss:domain:keycloak:1.1">
          <secure-deployment name="war-name.war">
          <realm>realm-name</realm>
          <resource>resource-name</resource>
          <public-client>true</public-client>
          <auth-server-url>https://keycloak-hostname/auth</auth-server-url>
          <ssl-required>EXTERNAL</ssl-required>
          <principal-attribute>preferred_username</principal-attribute>
          </secure-deployment>
          </subsystem>





          share|improve this answer































            1














            In Keycloak 3.4.3 (may also work on earlier versions) I was able to map username to the sub token claim name. From the Keycloak admin interface this is done under Clients > [your-client] > Mappers > username and then enter sub in the Token Claim Name field. This has the advantage of actually changing the contents of the ID token returned by Keycloak rather than adjusting client-side as in the other answer. This is particularly nice when you're using a standard OpenID Connect library rather than an adapter provided by Keycloak.






            share|improve this answer































              0














              In my case i was taking the preferred user name from the token like this



              keycloakPrincipal.getKeycloakSecurityContext().getToken();
              token.getPreferredUsername();


              To work i had to go to keycloak and add on my client template the add builtins if not added preferred username came null.



              Check the username on the built ins, client template -> mappers.



              After that if worked!






              share|improve this answer























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f31864062%2ffetch-logged-in-username-in-a-webapp-secured-with-keycloak%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                5 Answers
                5






                active

                oldest

                votes








                5 Answers
                5






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                24














                You get all user information from the security context.



                Example:



                public class Greeter {

                @Context
                SecurityContext sc;

                @GET
                @Produces(MediaType.APPLICATION_JSON)
                public String sayHello() {

                // this will set the user id as userName
                String userName = sc.getUserPrincipal().getName();

                if (sc.getUserPrincipal() instanceof KeycloakPrincipal) {
                KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) sc.getUserPrincipal();

                // this is how to get the real userName (or rather the login name)
                userName = kp.getKeycloakSecurityContext().getIdToken().getPreferredUsername();
                }

                return "{ message : "Hello " + userName + "" }";
                }


                For the security context to be propagated you have to have a security domain configured as described in the:
                JBoss/Wildfly Adapter configuration






                share|improve this answer





















                • 3





                  KeyCloakPrincipal is available from keycloak-core, for those who don't know where it is from

                  – aksappy
                  Aug 7 '15 at 17:26













                • That did the trick.. Thank you @sebplorenz

                  – aksappy
                  Aug 8 '15 at 3:11






                • 7





                  In case of Null Pointer Exceptions like I encountered when using the above with bearer token: Use getToken() instead of getIdToken()

                  – devrys
                  Apr 2 '16 at 23:22
















                24














                You get all user information from the security context.



                Example:



                public class Greeter {

                @Context
                SecurityContext sc;

                @GET
                @Produces(MediaType.APPLICATION_JSON)
                public String sayHello() {

                // this will set the user id as userName
                String userName = sc.getUserPrincipal().getName();

                if (sc.getUserPrincipal() instanceof KeycloakPrincipal) {
                KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) sc.getUserPrincipal();

                // this is how to get the real userName (or rather the login name)
                userName = kp.getKeycloakSecurityContext().getIdToken().getPreferredUsername();
                }

                return "{ message : "Hello " + userName + "" }";
                }


                For the security context to be propagated you have to have a security domain configured as described in the:
                JBoss/Wildfly Adapter configuration






                share|improve this answer





















                • 3





                  KeyCloakPrincipal is available from keycloak-core, for those who don't know where it is from

                  – aksappy
                  Aug 7 '15 at 17:26













                • That did the trick.. Thank you @sebplorenz

                  – aksappy
                  Aug 8 '15 at 3:11






                • 7





                  In case of Null Pointer Exceptions like I encountered when using the above with bearer token: Use getToken() instead of getIdToken()

                  – devrys
                  Apr 2 '16 at 23:22














                24












                24








                24







                You get all user information from the security context.



                Example:



                public class Greeter {

                @Context
                SecurityContext sc;

                @GET
                @Produces(MediaType.APPLICATION_JSON)
                public String sayHello() {

                // this will set the user id as userName
                String userName = sc.getUserPrincipal().getName();

                if (sc.getUserPrincipal() instanceof KeycloakPrincipal) {
                KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) sc.getUserPrincipal();

                // this is how to get the real userName (or rather the login name)
                userName = kp.getKeycloakSecurityContext().getIdToken().getPreferredUsername();
                }

                return "{ message : "Hello " + userName + "" }";
                }


                For the security context to be propagated you have to have a security domain configured as described in the:
                JBoss/Wildfly Adapter configuration






                share|improve this answer















                You get all user information from the security context.



                Example:



                public class Greeter {

                @Context
                SecurityContext sc;

                @GET
                @Produces(MediaType.APPLICATION_JSON)
                public String sayHello() {

                // this will set the user id as userName
                String userName = sc.getUserPrincipal().getName();

                if (sc.getUserPrincipal() instanceof KeycloakPrincipal) {
                KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) sc.getUserPrincipal();

                // this is how to get the real userName (or rather the login name)
                userName = kp.getKeycloakSecurityContext().getIdToken().getPreferredUsername();
                }

                return "{ message : "Hello " + userName + "" }";
                }


                For the security context to be propagated you have to have a security domain configured as described in the:
                JBoss/Wildfly Adapter configuration







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Aug 7 '15 at 7:59

























                answered Aug 7 '15 at 5:28









                sebplorenzsebplorenz

                5392516




                5392516








                • 3





                  KeyCloakPrincipal is available from keycloak-core, for those who don't know where it is from

                  – aksappy
                  Aug 7 '15 at 17:26













                • That did the trick.. Thank you @sebplorenz

                  – aksappy
                  Aug 8 '15 at 3:11






                • 7





                  In case of Null Pointer Exceptions like I encountered when using the above with bearer token: Use getToken() instead of getIdToken()

                  – devrys
                  Apr 2 '16 at 23:22














                • 3





                  KeyCloakPrincipal is available from keycloak-core, for those who don't know where it is from

                  – aksappy
                  Aug 7 '15 at 17:26













                • That did the trick.. Thank you @sebplorenz

                  – aksappy
                  Aug 8 '15 at 3:11






                • 7





                  In case of Null Pointer Exceptions like I encountered when using the above with bearer token: Use getToken() instead of getIdToken()

                  – devrys
                  Apr 2 '16 at 23:22








                3




                3





                KeyCloakPrincipal is available from keycloak-core, for those who don't know where it is from

                – aksappy
                Aug 7 '15 at 17:26







                KeyCloakPrincipal is available from keycloak-core, for those who don't know where it is from

                – aksappy
                Aug 7 '15 at 17:26















                That did the trick.. Thank you @sebplorenz

                – aksappy
                Aug 8 '15 at 3:11





                That did the trick.. Thank you @sebplorenz

                – aksappy
                Aug 8 '15 at 3:11




                7




                7





                In case of Null Pointer Exceptions like I encountered when using the above with bearer token: Use getToken() instead of getIdToken()

                – devrys
                Apr 2 '16 at 23:22





                In case of Null Pointer Exceptions like I encountered when using the above with bearer token: Use getToken() instead of getIdToken()

                – devrys
                Apr 2 '16 at 23:22













                16














                You may also set the principal-attribute property in the keycloak.json file of your web app to preferred_username.






                share|improve this answer





















                • 3





                  Thank you! This is a much better answer than the accepted one because your answer allows a SessionContext.getCallerPrincipal.getName to work at the EJB layer if the entire project was packaged as an EAR.

                  – j.con
                  Jan 24 '17 at 18:43
















                16














                You may also set the principal-attribute property in the keycloak.json file of your web app to preferred_username.






                share|improve this answer





















                • 3





                  Thank you! This is a much better answer than the accepted one because your answer allows a SessionContext.getCallerPrincipal.getName to work at the EJB layer if the entire project was packaged as an EAR.

                  – j.con
                  Jan 24 '17 at 18:43














                16












                16








                16







                You may also set the principal-attribute property in the keycloak.json file of your web app to preferred_username.






                share|improve this answer















                You may also set the principal-attribute property in the keycloak.json file of your web app to preferred_username.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Aug 30 '16 at 11:38









                loki

                5,32552756




                5,32552756










                answered Aug 30 '16 at 11:05









                user3569718user3569718

                16314




                16314








                • 3





                  Thank you! This is a much better answer than the accepted one because your answer allows a SessionContext.getCallerPrincipal.getName to work at the EJB layer if the entire project was packaged as an EAR.

                  – j.con
                  Jan 24 '17 at 18:43














                • 3





                  Thank you! This is a much better answer than the accepted one because your answer allows a SessionContext.getCallerPrincipal.getName to work at the EJB layer if the entire project was packaged as an EAR.

                  – j.con
                  Jan 24 '17 at 18:43








                3




                3





                Thank you! This is a much better answer than the accepted one because your answer allows a SessionContext.getCallerPrincipal.getName to work at the EJB layer if the entire project was packaged as an EAR.

                – j.con
                Jan 24 '17 at 18:43





                Thank you! This is a much better answer than the accepted one because your answer allows a SessionContext.getCallerPrincipal.getName to work at the EJB layer if the entire project was packaged as an EAR.

                – j.con
                Jan 24 '17 at 18:43











                1














                Need to add standalone.xml next line:



                <principal-attribute>preferred_username</principal-attribute>


                Example:



                <subsystem xmlns="urn:jboss:domain:keycloak:1.1">
                <secure-deployment name="war-name.war">
                <realm>realm-name</realm>
                <resource>resource-name</resource>
                <public-client>true</public-client>
                <auth-server-url>https://keycloak-hostname/auth</auth-server-url>
                <ssl-required>EXTERNAL</ssl-required>
                <principal-attribute>preferred_username</principal-attribute>
                </secure-deployment>
                </subsystem>





                share|improve this answer




























                  1














                  Need to add standalone.xml next line:



                  <principal-attribute>preferred_username</principal-attribute>


                  Example:



                  <subsystem xmlns="urn:jboss:domain:keycloak:1.1">
                  <secure-deployment name="war-name.war">
                  <realm>realm-name</realm>
                  <resource>resource-name</resource>
                  <public-client>true</public-client>
                  <auth-server-url>https://keycloak-hostname/auth</auth-server-url>
                  <ssl-required>EXTERNAL</ssl-required>
                  <principal-attribute>preferred_username</principal-attribute>
                  </secure-deployment>
                  </subsystem>





                  share|improve this answer


























                    1












                    1








                    1







                    Need to add standalone.xml next line:



                    <principal-attribute>preferred_username</principal-attribute>


                    Example:



                    <subsystem xmlns="urn:jboss:domain:keycloak:1.1">
                    <secure-deployment name="war-name.war">
                    <realm>realm-name</realm>
                    <resource>resource-name</resource>
                    <public-client>true</public-client>
                    <auth-server-url>https://keycloak-hostname/auth</auth-server-url>
                    <ssl-required>EXTERNAL</ssl-required>
                    <principal-attribute>preferred_username</principal-attribute>
                    </secure-deployment>
                    </subsystem>





                    share|improve this answer













                    Need to add standalone.xml next line:



                    <principal-attribute>preferred_username</principal-attribute>


                    Example:



                    <subsystem xmlns="urn:jboss:domain:keycloak:1.1">
                    <secure-deployment name="war-name.war">
                    <realm>realm-name</realm>
                    <resource>resource-name</resource>
                    <public-client>true</public-client>
                    <auth-server-url>https://keycloak-hostname/auth</auth-server-url>
                    <ssl-required>EXTERNAL</ssl-required>
                    <principal-attribute>preferred_username</principal-attribute>
                    </secure-deployment>
                    </subsystem>






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered May 8 '18 at 15:38









                    Sergey SarabunSergey Sarabun

                    313




                    313























                        1














                        In Keycloak 3.4.3 (may also work on earlier versions) I was able to map username to the sub token claim name. From the Keycloak admin interface this is done under Clients > [your-client] > Mappers > username and then enter sub in the Token Claim Name field. This has the advantage of actually changing the contents of the ID token returned by Keycloak rather than adjusting client-side as in the other answer. This is particularly nice when you're using a standard OpenID Connect library rather than an adapter provided by Keycloak.






                        share|improve this answer




























                          1














                          In Keycloak 3.4.3 (may also work on earlier versions) I was able to map username to the sub token claim name. From the Keycloak admin interface this is done under Clients > [your-client] > Mappers > username and then enter sub in the Token Claim Name field. This has the advantage of actually changing the contents of the ID token returned by Keycloak rather than adjusting client-side as in the other answer. This is particularly nice when you're using a standard OpenID Connect library rather than an adapter provided by Keycloak.






                          share|improve this answer


























                            1












                            1








                            1







                            In Keycloak 3.4.3 (may also work on earlier versions) I was able to map username to the sub token claim name. From the Keycloak admin interface this is done under Clients > [your-client] > Mappers > username and then enter sub in the Token Claim Name field. This has the advantage of actually changing the contents of the ID token returned by Keycloak rather than adjusting client-side as in the other answer. This is particularly nice when you're using a standard OpenID Connect library rather than an adapter provided by Keycloak.






                            share|improve this answer













                            In Keycloak 3.4.3 (may also work on earlier versions) I was able to map username to the sub token claim name. From the Keycloak admin interface this is done under Clients > [your-client] > Mappers > username and then enter sub in the Token Claim Name field. This has the advantage of actually changing the contents of the ID token returned by Keycloak rather than adjusting client-side as in the other answer. This is particularly nice when you're using a standard OpenID Connect library rather than an adapter provided by Keycloak.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered May 11 '18 at 15:30









                            YerocYeroc

                            565816




                            565816























                                0














                                In my case i was taking the preferred user name from the token like this



                                keycloakPrincipal.getKeycloakSecurityContext().getToken();
                                token.getPreferredUsername();


                                To work i had to go to keycloak and add on my client template the add builtins if not added preferred username came null.



                                Check the username on the built ins, client template -> mappers.



                                After that if worked!






                                share|improve this answer




























                                  0














                                  In my case i was taking the preferred user name from the token like this



                                  keycloakPrincipal.getKeycloakSecurityContext().getToken();
                                  token.getPreferredUsername();


                                  To work i had to go to keycloak and add on my client template the add builtins if not added preferred username came null.



                                  Check the username on the built ins, client template -> mappers.



                                  After that if worked!






                                  share|improve this answer


























                                    0












                                    0








                                    0







                                    In my case i was taking the preferred user name from the token like this



                                    keycloakPrincipal.getKeycloakSecurityContext().getToken();
                                    token.getPreferredUsername();


                                    To work i had to go to keycloak and add on my client template the add builtins if not added preferred username came null.



                                    Check the username on the built ins, client template -> mappers.



                                    After that if worked!






                                    share|improve this answer













                                    In my case i was taking the preferred user name from the token like this



                                    keycloakPrincipal.getKeycloakSecurityContext().getToken();
                                    token.getPreferredUsername();


                                    To work i had to go to keycloak and add on my client template the add builtins if not added preferred username came null.



                                    Check the username on the built ins, client template -> mappers.



                                    After that if worked!







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Sep 3 '18 at 21:16









                                    cabaji99cabaji99

                                    51258




                                    51258






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f31864062%2ffetch-logged-in-username-in-a-webapp-secured-with-keycloak%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Costa Masnaga

                                        Fotorealismo

                                        Sidney Franklin