Search code examples
angularspring-bootsingle-sign-onauth0auth0-connection

Retrieve Access Token ID from Auth 0


I am trying to implement login with SSO functionality using Auth0, My server is with Spring Boot and my frontend is on Angular. Currently I have created a new application on Auth0 platform as single web page and added the necessary configs on my angular app (client_id, domain and redirect_uri). When clicking log in with sso the auth0 page opens the user logs in and then a response is returned with callback url containing code and state.

I am using this.auth.loginWithRedirect() method of AuthService from @auth0/auth0-angular library, after i recieve the code and state i tried to send these two on spring boot application and have an api call to retrieve access token

        HttpPost httpPost = new HttpPost("https://mydomain.auth0.com/oauth/token");        
        JSONObject requestBody = new JSONObject();
        requestBody.put("grant_type", "authorization_code");
        requestBody.put("client_id", "***************************************");
        requestBody.put("client_secret", "**************************************");
        requestBody.put("code", code);
        requestBody.put("redirect_uri", "http://localhost:4200"); 

        StringEntity entity = new StringEntity(requestBody.toString());
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json");

        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();`

This http call constantly returns me invalid authorization code even though I am sure the code is exactly how it was returned from the callback URL on front end and also the client_id, client_secret and redirect_uri are the same as the ones on auth0 platform.

DO you have any idea what is wrong here? And also should i create a new Application/Api on AUth0 platform for spring boot application in order to communicate or is there anything else missing.

I am trying to get access token via HTTP call after i have retrieved code and state from call back URL from auth0 when trying to login but i constantly get invalid authorization code


Solution

  • The pattern you are using (Angular configured as a "public" OAuth2 client) is now discouraged. According to the Spring Security team latest recommendations, you should be using "confidential" OAuth2 clients.

    An option I use is to configure spring-cloud-gateway with spring-boot-starter-oauth2-client and the TokenRelay= filter between your Angular app and Spring resource server. I wrote a tutorial for that there (and it works with Auth0 as you can see here).