Skip to content

Commit

Permalink
add flag to use legacy auth methods with /oauth/token
Browse files Browse the repository at this point in the history
  • Loading branch information
lbalmaceda committed Dec 21, 2016
1 parent 0f9ec49 commit 09f9370
Show file tree
Hide file tree
Showing 2 changed files with 182 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ public class AuthenticationAPIClient {
private final Gson gson;
private final com.auth0.android.request.internal.RequestFactory factory;
private final ErrorBuilder<AuthenticationException> authErrorBuilder;
private boolean useOAuth2;


/**
Expand Down Expand Up @@ -137,6 +138,17 @@ private AuthenticationAPIClient(Auth0 auth0, RequestFactory factory, OkHttpClien
}
}

/**
* Use OAuth 2.0 Authorization API on legacy authentication endpoints. You will need to enable this setting in the Auth0 Dashboard first: Go to Account (top right), Account Settings, click Advanced and check the toggle at the bottom.
* This setting affects the methods {@link AuthenticationAPIClient#login(String, String, String)}, {@link AuthenticationAPIClient#tokenInfo(String)}, {@link AuthenticationAPIClient#signUp(String, String, String)} and {@link AuthenticationAPIClient#signUp(String, String, String, String)}.
* Default is {@code false}.
*
* @param use if Lock will use the OAuth 2.0 API or the legacy one.
*/
public void useOAuth2(boolean use) {
this.useOAuth2 = use;
}

/**
* Log every Request and Response made by this client.
* You shouldn't enable logging in release builds as it may leak sensitive information.
Expand Down Expand Up @@ -192,6 +204,12 @@ public void setUserAgent(String userAgent) {
*/
@SuppressWarnings("WeakerAccess")
public AuthenticationRequest login(@NonNull String usernameOrEmail, @NonNull String password, @NonNull String connection) {
if (useOAuth2) {
AuthenticationRequest login = login(usernameOrEmail, password);
login.setRealm(connection);
return login;
}

Map<String, Object> requestParameters = ParameterBuilder.newAuthenticationBuilder()
.set(USERNAME_KEY, usernameOrEmail)
.set(PASSWORD_KEY, password)
Expand Down Expand Up @@ -402,7 +420,9 @@ public Request<UserProfile, AuthenticationException> userInfo(@NonNull String ac
}

/**
* Fetch the token information from Auth0
* Fetch the token information from Auth0.
* If {@link AuthenticationAPIClient#useOAuth2} is set to true, userInfo endpoint will be used instead.
* <p>
* Example usage:
* <pre><code>
* client.tokenInfo("{id_token}")
Expand All @@ -422,6 +442,10 @@ public Request<UserProfile, AuthenticationException> userInfo(@NonNull String ac
@SuppressWarnings("WeakerAccess")
@Deprecated
public Request<UserProfile, AuthenticationException> tokenInfo(@NonNull String idToken) {
if (useOAuth2) {
return userInfo(idToken);
}

HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder()
.addPathSegment(TOKEN_INFO_PATH)
.build();
Expand Down Expand Up @@ -497,7 +521,7 @@ public DatabaseConnectionRequest<DatabaseUser, AuthenticationException> createUs

/**
* Creates a user in a DB connection using <a href="https://auth0.com/docs/auth-api#!#post--dbconnections-signup">'/dbconnections/signup' endpoint</a>
* and then logs in using the /oauth/ro endpoint.
* and then logs in using the /oauth/ro endpoint. If {@link AuthenticationAPIClient#useOAuth2} is set to true, the /oauth/token endpoint will be used instead.
* Example usage:
* <pre><code>
* client.signUp("{email}", "{password}", "{username}", "{database connection name}")
Expand All @@ -519,13 +543,20 @@ public DatabaseConnectionRequest<DatabaseUser, AuthenticationException> createUs
@SuppressWarnings("WeakerAccess")
public SignUpRequest signUp(@NonNull String email, @NonNull String password, @NonNull String username, @NonNull String connection) {
final DatabaseConnectionRequest<DatabaseUser, AuthenticationException> createUserRequest = createUser(email, password, username, connection);
final AuthenticationRequest authenticationRequest = login(email, password, connection);
final AuthenticationRequest authenticationRequest;
if (useOAuth2) {
authenticationRequest = login(email, password);
authenticationRequest.setRealm(connection);
} else {
authenticationRequest = login(email, password, connection);
}

return new SignUpRequest(createUserRequest, authenticationRequest);
}

/**
* Creates a user in a DB connection using <a href="https://auth0.com/docs/auth-api#!#post--dbconnections-signup">'/dbconnections/signup' endpoint</a>
* and then logs in using the /oauth/ro endpoint.
* and then logs in using the /oauth/ro endpoint. If {@link AuthenticationAPIClient#useOAuth2} is set to true, the /oauth/token endpoint will be used instead.
* Example usage:
* <pre><code>
* client.signUp("{email}", "{password}", "{database connection name}")
Expand All @@ -545,8 +576,14 @@ public SignUpRequest signUp(@NonNull String email, @NonNull String password, @No
*/
@SuppressWarnings("WeakerAccess")
public SignUpRequest signUp(@NonNull String email, @NonNull String password, @NonNull String connection) {
DatabaseConnectionRequest<DatabaseUser, AuthenticationException> createUserRequest = createUser(email, password, connection);
final AuthenticationRequest authenticationRequest = login(email, password, connection);
final DatabaseConnectionRequest<DatabaseUser, AuthenticationException> createUserRequest = createUser(email, password, connection);
final AuthenticationRequest authenticationRequest;
if (useOAuth2) {
authenticationRequest = login(email, password);
authenticationRequest.setRealm(connection);
} else {
authenticationRequest = login(email, password, connection);
}
return new SignUpRequest(createUserRequest, authenticationRequest);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ public class AuthenticationAPIClientTest {
private static final String OPENID = "openid";

private AuthenticationAPIClient client;
private Auth0 auth0;
private Gson gson;

private AuthenticationAPI mockAPI;
Expand All @@ -104,7 +105,7 @@ public class AuthenticationAPIClientTest {
public void setUp() throws Exception {
mockAPI = new AuthenticationAPI();
final String domain = mockAPI.getDomain();
Auth0 auth0 = new Auth0(CLIENT_ID, domain, domain);
auth0 = new Auth0(CLIENT_ID, domain, domain);
client = new AuthenticationAPIClient(auth0);
gson = new GsonBuilder().serializeNulls().create();
}
Expand Down Expand Up @@ -256,6 +257,7 @@ public void shouldLoginWithUserAndPassword() throws Exception {
assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
Map<String, String> body = bodyFromRequest(request);
assertThat(body, hasEntry("connection", MY_CONNECTION));
assertThat(body, not(hasKey("realm")));
}

@Test
Expand All @@ -272,6 +274,33 @@ public void shouldLoginWithUserAndPasswordSync() throws Exception {
assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
Map<String, String> body = bodyFromRequest(request);
assertThat(body, hasEntry("connection", MY_CONNECTION));
assertThat(body, not(hasKey("realm")));
}

@Test
public void shouldLoginWithUserAndPasswordUsingOAuthTokenEndpointIfOAuth2IsEnabled() throws Exception {
mockAPI.willReturnSuccessfulLogin();
final MockAuthenticationCallback<Credentials> callback = new MockAuthenticationCallback<>();

AuthenticationAPIClient client = new AuthenticationAPIClient(auth0);
client.useOAuth2(true);
client.login(SUPPORT_AUTH0_COM, "some-password", MY_CONNECTION)
.start(callback);
assertThat(callback, hasPayloadOfType(Credentials.class));

final RecordedRequest request = mockAPI.takeRequest();
assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
Map<String, String> body = bodyFromRequest(request);

assertThat(request.getPath(), equalTo("/oauth/token"));
assertThat(body, hasEntry("client_id", CLIENT_ID));
assertThat(body, hasEntry("grant_type", "http://auth0.com/oauth/grant-type/password-realm"));
assertThat(body, hasEntry("username", SUPPORT_AUTH0_COM));
assertThat(body, hasEntry("password", "some-password"));
assertThat(body, hasEntry("realm", MY_CONNECTION));
assertThat(body, not(hasKey("connection")));
assertThat(body, not(hasKey("scope")));
assertThat(body, not(hasKey("audience")));
}

@Test
Expand All @@ -290,6 +319,7 @@ public void shouldLoginWithUserAndPasswordUsingOAuthTokenEndpoint() throws Excep
assertThat(body, hasEntry("grant_type", "http://auth0.com/oauth/grant-type/password-realm"));
assertThat(body, hasEntry("username", SUPPORT_AUTH0_COM));
assertThat(body, hasEntry("password", "some-password"));
assertThat(body, not(hasKey("realm")));
assertThat(body, not(hasKey("connection")));
assertThat(body, not(hasKey("scope")));
assertThat(body, not(hasKey("audience")));
Expand All @@ -311,6 +341,7 @@ public void shouldLoginWithUserAndPasswordSyncUsingOAuthTokenEndpoint() throws E
assertThat(body, hasEntry("grant_type", "http://auth0.com/oauth/grant-type/password-realm"));
assertThat(body, hasEntry("username", SUPPORT_AUTH0_COM));
assertThat(body, hasEntry("password", "some-password"));
assertThat(body, not(hasKey("realm")));
assertThat(body, not(hasKey("connection")));
assertThat(body, not(hasKey("scope")));
assertThat(body, not(hasKey("audience")));
Expand Down Expand Up @@ -352,6 +383,24 @@ public void shouldFetchTokenInfoSync() throws Exception {
assertThat(body, hasEntry("id_token", "ID_TOKEN"));
}

@Test
public void shouldFetchUserInfoIfOAuth2IsEnabled() throws Exception {
mockAPI.willReturnTokenInfo();
final MockAuthenticationCallback<UserProfile> callback = new MockAuthenticationCallback<>();

AuthenticationAPIClient client = new AuthenticationAPIClient(auth0);
client.useOAuth2(true);
client.tokenInfo("ACCESS_TOKEN")
.start(callback);

assertThat(callback, hasPayloadOfType(UserProfile.class));

final RecordedRequest request = mockAPI.takeRequest();
assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
assertThat(request.getHeader("Authorization"), is("Bearer ACCESS_TOKEN"));
assertThat(request.getPath(), equalTo("/userinfo"));
}

@Test
public void shouldFetchUserInfo() throws Exception {
mockAPI.willReturnTokenInfo();
Expand Down Expand Up @@ -709,6 +758,41 @@ public void shouldSignUpUser() throws Exception {
assertThat(loginBody, hasEntry("password", PASSWORD));
assertThat(loginBody, hasEntry("connection", MY_CONNECTION));
assertThat(loginBody, hasEntry("scope", OPENID));
assertThat(loginBody, not(hasKey("realm")));
}

@Test
public void shouldSignUpUserUsingOAuthTokenEndpointIfOAuth2IsEnabled() throws Exception {
mockAPI.willReturnSuccessfulSignUp()
.willReturnSuccessfulLogin();

final MockAuthenticationCallback<Credentials> callback = new MockAuthenticationCallback<>();
AuthenticationAPIClient client = new AuthenticationAPIClient(auth0);
client.useOAuth2(true);
client.signUp(SUPPORT_AUTH0_COM, PASSWORD, SUPPORT, MY_CONNECTION)
.start(callback);

final RecordedRequest request = mockAPI.takeRequest();
assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
assertThat(request.getPath(), equalTo("/dbconnections/signup"));

Map<String, String> body = bodyFromRequest(request);
assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM));
assertThat(body, hasEntry("username", SUPPORT));
assertThat(body, hasEntry("password", PASSWORD));
assertThat(body, hasEntry("connection", MY_CONNECTION));

assertThat(callback, hasPayloadOfType(Credentials.class));

final RecordedRequest loginRequest = mockAPI.takeRequest();
assertThat(loginRequest.getPath(), equalTo("/oauth/token"));

Map<String, String> loginBody = bodyFromRequest(loginRequest);
assertThat(loginBody, hasEntry("username", SUPPORT_AUTH0_COM));
assertThat(loginBody, hasEntry("password", PASSWORD));
assertThat(loginBody, hasEntry("realm", MY_CONNECTION));
assertThat(loginBody, not(hasKey("scope")));
assertThat(loginBody, not(hasKey("connection")));
}

@Test
Expand Down Expand Up @@ -789,13 +873,57 @@ public void shouldSignUpUserWithoutUsername() throws Exception {
assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
assertThat(request.getPath(), equalTo("/dbconnections/signup"));

Map<String, String> body = bodyFromRequest(request);
assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM));
assertThat(body, hasEntry("password", PASSWORD));
assertThat(body, hasEntry("connection", MY_CONNECTION));

assertThat(callback, hasPayloadOfType(Credentials.class));

final RecordedRequest loginRequest = mockAPI.takeRequest();
assertThat(loginRequest.getPath(), equalTo("/oauth/ro"));

Map<String, String> loginBody = bodyFromRequest(loginRequest);
assertThat(loginBody, hasEntry("username", SUPPORT_AUTH0_COM));
assertThat(loginBody, hasEntry("password", PASSWORD));
assertThat(loginBody, hasEntry("connection", MY_CONNECTION));
assertThat(loginBody, hasEntry("scope", OPENID));
assertThat(loginBody, not(hasKey("realm")));
}

@Test
public void shouldSignUpUserWithoutUsernameUsingOAuthTokenEndpointIfOAuth2IsEnabled() throws Exception {
mockAPI.willReturnSuccessfulSignUp()
.willReturnSuccessfulLogin()
.willReturnTokenInfo();

final MockAuthenticationCallback<Credentials> callback = new MockAuthenticationCallback<>();
AuthenticationAPIClient client = new AuthenticationAPIClient(auth0);
client.useOAuth2(true);
client.signUp(SUPPORT_AUTH0_COM, PASSWORD, MY_CONNECTION)
.start(callback);

final RecordedRequest request = mockAPI.takeRequest();
assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
assertThat(request.getPath(), equalTo("/dbconnections/signup"));

Map<String, String> body = bodyFromRequest(request);
assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM));
assertThat(body, not(hasKey("username")));
assertThat(body, hasEntry("password", PASSWORD));
assertThat(body, hasEntry("connection", MY_CONNECTION));

assertThat(callback, hasPayloadOfType(Credentials.class));

final RecordedRequest loginRequest = mockAPI.takeRequest();
assertThat(loginRequest.getPath(), equalTo("/oauth/token"));

Map<String, String> loginBody = bodyFromRequest(loginRequest);
assertThat(loginBody, hasEntry("username", SUPPORT_AUTH0_COM));
assertThat(loginBody, hasEntry("password", PASSWORD));
assertThat(loginBody, hasEntry("realm", MY_CONNECTION));
assertThat(loginBody, not(hasKey("scope")));
assertThat(loginBody, not(hasKey("connection")));
}

@Test
Expand All @@ -819,6 +947,16 @@ public void shouldSignUpUserWithoutUsernameSync() throws Exception {
assertThat(body, hasEntry("connection", MY_CONNECTION));

assertThat(credentials, is(notNullValue()));

final RecordedRequest loginRequest = mockAPI.takeRequest();
assertThat(loginRequest.getPath(), equalTo("/oauth/ro"));

Map<String, String> loginBody = bodyFromRequest(loginRequest);
assertThat(loginBody, hasEntry("username", SUPPORT_AUTH0_COM));
assertThat(loginBody, hasEntry("password", PASSWORD));
assertThat(loginBody, hasEntry("connection", MY_CONNECTION));
assertThat(loginBody, hasEntry("scope", OPENID));
assertThat(loginBody, not(hasKey("realm")));
}

@Test
Expand Down

0 comments on commit 09f9370

Please sign in to comment.