Search code examples
keycloakkeycloak-rest-api

Keycloak frontend and backend clients


This is related to keycloak clients. My frontend is connected to public client and backend is connected to confidential client. I am able to login, get the code, as I am using response_type=code by turning on "Standard Flow Enabled". This code redirects and returns me Idtoken, refreshtoken and token. Now I need to communicate with backend which is confidential, I would like to authenticate user using some of the values which I have received from the frontend client.

How can I do that?

Here is my frontend and backend conf

FRONTEND

{
   "realm": "xyz",
   "auth-server-url": "http://localhost:8333/auth/",
   "ssl-required": "external",
   "resource": "frontend-app",
   "public-client": true,
   "confidential-port": 0,
   "enable-cors": true
}

BACKEND

keycloak.auth-server-url=http://localhost:8333/auth
keycloak.realm=xyz
keycloak.resource=backend-app
keycloak.principal-attribute=preferred_username
keycloak.bearer-only=true
keycloak.credentials.secret=xxx-xxx-xxx

this is from realm setting


Solution

  • This might help somebody. My backend service which is springboot project with spring security keycloakAuthenticationProvider does authenticate the token received from the frontend public client.

    Call from frontend

     axios({
                        method: 'GET',
                        url: '/api/authenticate',
                        headers:{'Authorization': 'Bearer '+keycloak.token+''}
    
                    }).then((r) => {
                        console.log("response",r)
                    })
    

    Call to backend

    @GetMapping("/api/authenticate")
        public ResponseEntity<SecureUserDto> authenticate() {
            String username = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
            User user = userRepository.findWithPrivilegesByUsername(username);
    
            return ResponseEntity.ok();
        }
    

    But i still was not able to get it right on postman at ../token end point provided by keycloak server. Anyways my work is done.