Search code examples
javamodel-view-controlleroauthauth0spark-java

Logged in user null Auth0/Spark Java


I am trying to get Auth0 integrated into my web app which uses the spark-java framework. The problem is while the authentication works perfectly, including the callback(I see the new user created on Auth0's website and my website gets redirected), I can't access the logged in user info. I've tried several methods like SessionUtils.getAuth0User(request.raw()) and none of them are working. For example in the provided tutorial here: https://github.com/auth0-samples/auth0-servlet-sample/tree/master/01-Login they access the logged in user info like so:

        @Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    final Auth0User user = SessionUtils.getAuth0User(req);
    if (user != null) {
        req.setAttribute("user", user);
    }
    req.getRequestDispatcher("/WEB-INF/jsp/home.jsp").forward(req, res);
}

I've tried doing something similar with Spark but since the get works a bit differently in Spark I do this:

port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/spark/template/freemarker");
String clientId = System.getenv("AUTH0_CLIENT_ID");
String clientDomain = System.getenv("AUTH0_DOMAIN");
  get("/", (request, response) ->
  {
      Map<String, Object> attributes = new HashMap<>();
      Auth0User user = SessionUtils.getAuth0User(request.raw());
      if(user != null) {
          attributes.put("user", user);
          attributes.put("loggedIn" , true);
      }
      else
          attributes.put("loggedIn" , false);
      attributes.put("clientId" , clientId);
      attributes.put("clientDomain" , clientDomain);
      return new ModelAndView(attributes, "index.ftl");
  }, new FreeMarkerEngine());

The code is always reporting the user as null even though the user is created and stored in the database and the signin works properly with no runtime or console errors. The other methods I tried I replaced the line where I set the user variable and wrote the following.
Alternate Method 1:
Auth0User user = (Auth0User) request.session().attribute("auth0User");
Here auth0User is the same string literal Auth0 uses in their implementation of SessionUtils as shown in their source code referenced here: https://github.com/auth0/auth0-java-mvc-common/blob/master/src/main/java/com/auth0/SessionUtils.java

Alternate Method 2:
Auth0User user = (Auth0User) request.raw().getUserPrincipal();

In addition this is my javascript code running client side for the authentication:

    var lock = new Auth0Lock('${clientId}', '${clientDomain}', {
        auth: {
            redirectUrl: 'http://localhost:5000/build',
            responseType: 'code',
            params: {
            scope: 'openid user_id name nickname email picture'
            }
        }
    });

    $(document).ready(function()
    {
        $('.signup').click(function()
        {
            doSignup();
        });
    });

    function doSignup() {
        lock.show();
    }

I have no idea why user is being evaluated to null every time and I would love some feedback on what I'm doing wrong. Thanks.


Solution

  • In order for you to get a non null user instance from SessionUtils.getAuth0User(req) some piece of code must first call SessionUtils.setAuth0User. This should be done when you receive confirmation that the user authenticated with success.

    In the auth0-servlet-sample you were using as reference this is done by configuring an Auth0ServletCallback that will handle requests performed to /callback endpoint. Since the Auth0ServletCallback calls (see code below) the set user for you, in the servlet example you can then get the user with success.

    protected void store(final Tokens tokens, final Auth0User user, final HttpServletRequest req)
    {
        SessionUtils.setTokens(req, tokens);
        SessionUtils.setAuth0User(req, user);
    }
    

    At the moment the available samples (auth0-servlet-sample, auth0-servlet-sso-sample, auth0-spring-mvc-sample, auth0-spring-security-api-sample and auth0-spring-security-mvc-sample) don't include one for spark-java so I can't refer you to any sample.

    In order to solve this you have to include additional logic to process the result of the authentication operation in your spark-java application and in case of success call the SessionUtils.setAuth0User yourself if you then want to use the corresponding SessionUtils.getAuth0User method.

    For general guidance on integrating a web application with Auth0 check Integrating a Web App with Auth0.