10.4.1. Authentication

Warning

You are looking at documentation for an older release. Not what you want? See the current release documentation.

Almost all the Rest operations (methods) require authentication. An authenticated user is used to check the access permission to the requested resource, but not only for that. For example, a POST to /rest/private/v1/social/spaces will create a space and set the authenticated user as the space manager.

At server side, within the method's code, the authenticated user Id is typically got via ConversationState:

String currentUserId = ConversationState.getCurrent().getIdentity().getUserId();

From the client, you can use Basic Authentication to have a user authenticated.

If the user is requesting a resource via your gadget, or just by hitting the URL in a browser, using /rest/private is the way to make sure he/she gets prompted to enter username and password, rather than getting an Unauthorized error.

Via a tool like curl, you can use -u option: curl -X GET -uroot:gtn http://localhost:8080/rest/private/v1/calendar.

If you are developing a Java application using URLConnection, basically you have to add "Authorization" header to every request:

URL url = new URL("http://localhost:8080/rest/private/v1/calendar/calendars");

String auth = new sun.misc.BASE64Encoder().encode("root:gtn".getBytes());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Basic " + auth);
connection.connect();

In the Java examples of these tutorials, the application is a standalone that serves a single user at once. In this case, the procedure above can be automatically done by setting a default Authenticator:

import java.net.Authenticator;

import java.net.PasswordAuthentication;
//...
@SuppressWarnings("restriction")
  public static void login(String username, String password) {
    final String username_ = username;
    final String password_ = password;
    Authenticator.setDefault(new Authenticator() {
      @Override
      public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username_, password_.toCharArray());
      }
    });
  }

Notice with this method, the first signed username is cached (during the live time of the JVM) and will not be unset by calling login() with another user. So if you want to switch to another user, you need to clear the AuthCache first:

sun.net.www.protocol.http.AuthCacheValue.setAuthCache(new sun.net.www.protocol.http.AuthCacheImpl());
Copyright ©. All rights reserved. eXo Platform SAS
blog comments powered byDisqus