Search in sources :

Example 1 with BadCredentialsException

use of io.gravitee.am.common.exception.authentication.BadCredentialsException in project gravitee-access-management by gravitee-io.

the class SocialAuthenticationProviderTest method shouldNotAuthenticateUser_noUser.

@Test
public void shouldNotAuthenticateUser_noUser() throws Exception {
    JsonObject credentials = new JsonObject();
    credentials.put("username", "my-user-id");
    credentials.put("password", "my-user-password");
    credentials.put("provider", "idp");
    Client client = new Client();
    when(authenticationProvider.loadUserByUsername(any(EndUserAuthentication.class))).thenReturn(Maybe.empty());
    when(routingContext.get("client")).thenReturn(client);
    when(routingContext.get("provider")).thenReturn(authenticationProvider);
    when(routingContext.request()).thenReturn(httpServerRequest);
    final io.vertx.core.http.HttpServerRequest delegateRequest = mock(io.vertx.core.http.HttpServerRequest.class);
    when(httpServerRequest.getDelegate()).thenReturn(delegateRequest);
    when(delegateRequest.method()).thenReturn(HttpMethod.POST);
    CountDownLatch latch = new CountDownLatch(1);
    authProvider.authenticate(routingContext, credentials, userAsyncResult -> {
        latch.countDown();
        Assert.assertNotNull(userAsyncResult);
        Assert.assertTrue(userAsyncResult.failed());
        Assert.assertTrue(userAsyncResult.cause() instanceof BadCredentialsException);
    });
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    verify(userAuthenticationManager, never()).connect(any());
    verify(eventManager).publishEvent(argThat(evt -> evt == AuthenticationEvent.FAILURE), any());
}
Also used : Client(io.gravitee.am.model.oidc.Client) Mock(org.mockito.Mock) Maybe(io.reactivex.Maybe) RunWith(org.junit.runner.RunWith) Single(io.reactivex.Single) BadCredentialsException(io.gravitee.am.common.exception.authentication.BadCredentialsException) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) User(io.gravitee.am.model.User) InjectMocks(org.mockito.InjectMocks) EventManager(io.gravitee.am.common.event.EventManager) HttpServerRequest(io.vertx.reactivex.core.http.HttpServerRequest) UserAuthenticationManager(io.gravitee.am.gateway.handler.common.auth.user.UserAuthenticationManager) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) AuthenticationProvider(io.gravitee.am.identityprovider.api.AuthenticationProvider) RoutingContext(io.vertx.reactivex.ext.web.RoutingContext) TimeUnit(java.util.concurrent.TimeUnit) Matchers.any(org.mockito.Matchers.any) CountDownLatch(java.util.concurrent.CountDownLatch) Mockito(org.mockito.Mockito) AuthenticationEvent(io.gravitee.am.gateway.handler.common.auth.event.AuthenticationEvent) EndUserAuthentication(io.gravitee.am.gateway.handler.common.auth.user.EndUserAuthentication) HttpMethod(io.vertx.core.http.HttpMethod) Assert(org.junit.Assert) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) Collections(java.util.Collections) JsonObject(io.vertx.core.json.JsonObject) Client(io.gravitee.am.model.oidc.Client) CountDownLatch(java.util.concurrent.CountDownLatch) BadCredentialsException(io.gravitee.am.common.exception.authentication.BadCredentialsException) EndUserAuthentication(io.gravitee.am.gateway.handler.common.auth.user.EndUserAuthentication) Test(org.junit.Test)

Example 2 with BadCredentialsException

use of io.gravitee.am.common.exception.authentication.BadCredentialsException in project gravitee-access-management by gravitee-io.

the class AbstractOpenIDConnectAuthenticationProvider method authenticate.

protected Maybe<Token> authenticate(Authentication authentication) {
    // implicit flow, retrieve the hashValue of the URL (#access_token=....&token_type=...)
    if (AuthenticationFlow.IMPLICIT_FLOW.equals(authenticationFlow())) {
        final String hashValue = authentication.getContext().request().parameters().getFirst(HASH_VALUE_PARAMETER);
        Map<String, String> hashValues = getParams(hashValue.substring(1));
        // implicit flow was used with response_type=id_token token, access token is already fetched, continue
        if (ResponseType.ID_TOKEN_TOKEN.equals(getConfiguration().getResponseType())) {
            String accessToken = hashValues.get(ACCESS_TOKEN_PARAMETER);
            // We store the token is option is enabled
            if (getConfiguration().isStoreOriginalTokens()) {
                if (!Strings.isNullOrEmpty(accessToken)) {
                    authentication.getContext().set(ACCESS_TOKEN_PARAMETER, accessToken);
                }
            }
            // put the id_token in context for later use
            authentication.getContext().set(ID_TOKEN_PARAMETER, hashValues.get(ID_TOKEN_PARAMETER));
            return Maybe.just(new Token(accessToken, TokenTypeHint.ACCESS_TOKEN));
        }
        // implicit flow was used with response_type=id_token, id token is already fetched, continue
        if (ResponseType.ID_TOKEN.equals(getConfiguration().getResponseType())) {
            String idToken = hashValues.get(ID_TOKEN_PARAMETER);
            // put the id_token in context for later use
            authentication.getContext().set(ID_TOKEN_PARAMETER, idToken);
            return Maybe.just(new Token(idToken, TokenTypeHint.ID_TOKEN));
        }
    }
    // authorization code flow, exchange code for an access token
    // prepare body request parameters
    final String authorizationCode = authentication.getContext().request().parameters().getFirst(getConfiguration().getCodeParameter());
    if (authorizationCode == null || authorizationCode.isEmpty()) {
        LOGGER.debug("Authorization code is missing, skip authentication");
        return Maybe.error(new BadCredentialsException("Missing authorization code"));
    }
    final List<NameValuePair> urlParameters = new ArrayList<>();
    final HttpRequest<Buffer> tokenRequest = getClient().postAbs(getConfiguration().getAccessTokenUri());
    if (ClientAuthenticationMethod.CLIENT_SECRET_BASIC.equals(this.getConfiguration().getClientAuthenticationMethod())) {
        tokenRequest.basicAuthentication(getConfiguration().getClientId(), getConfiguration().getClientSecret());
    } else {
        urlParameters.add(new BasicNameValuePair(Parameters.CLIENT_SECRET, getConfiguration().getClientSecret()));
    }
    urlParameters.add(new BasicNameValuePair(Parameters.CLIENT_ID, getConfiguration().getClientId()));
    urlParameters.add(new BasicNameValuePair(Parameters.REDIRECT_URI, String.valueOf(authentication.getContext().get(Parameters.REDIRECT_URI))));
    urlParameters.add(new BasicNameValuePair(Parameters.CODE, authorizationCode));
    urlParameters.add(new BasicNameValuePair(Parameters.GRANT_TYPE, "authorization_code"));
    String bodyRequest = URLEncodedUtils.format(urlParameters);
    return tokenRequest.putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(bodyRequest.length())).putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).rxSendBuffer(Buffer.buffer(bodyRequest)).toMaybe().map(httpResponse -> {
        if (httpResponse.statusCode() != 200) {
            throw new BadCredentialsException(httpResponse.statusMessage());
        }
        JsonObject response = httpResponse.bodyAsJsonObject();
        String accessToken = response.getString(ACCESS_TOKEN_PARAMETER);
        // We store the token is option is enabled
        if (getConfiguration().isStoreOriginalTokens()) {
            if (!Strings.isNullOrEmpty(accessToken)) {
                authentication.getContext().set(ACCESS_TOKEN_PARAMETER, accessToken);
            }
        }
        // ID Token is always stored for SSO
        String idToken = response.getString(ID_TOKEN_PARAMETER);
        if (!Strings.isNullOrEmpty(idToken)) {
            authentication.getContext().set(ID_TOKEN_PARAMETER, idToken);
        }
        return new Token(accessToken, TokenTypeHint.ACCESS_TOKEN);
    });
}
Also used : Buffer(io.vertx.reactivex.core.buffer.Buffer) BasicNameValuePair(io.gravitee.am.model.http.BasicNameValuePair) NameValuePair(io.gravitee.am.model.http.NameValuePair) BasicNameValuePair(io.gravitee.am.model.http.BasicNameValuePair) JsonObject(io.vertx.core.json.JsonObject) SecureRandomString(io.gravitee.am.common.utils.SecureRandomString) BadCredentialsException(io.gravitee.am.common.exception.authentication.BadCredentialsException)

Example 3 with BadCredentialsException

use of io.gravitee.am.common.exception.authentication.BadCredentialsException in project gravitee-access-management by gravitee-io.

the class FacebookAuthenticationProvider method authenticate.

protected Maybe<Token> authenticate(Authentication authentication) {
    // Prepare body request parameters.
    final String authorizationCode = authentication.getContext().request().parameters().getFirst(configuration.getCodeParameter());
    if (authorizationCode == null || authorizationCode.isEmpty()) {
        LOGGER.debug("Authorization code is missing, skip authentication");
        return Maybe.error(new BadCredentialsException("Missing authorization code"));
    }
    MultiMap form = MultiMap.caseInsensitiveMultiMap().set(CLIENT_ID, configuration.getClientId()).set(CLIENT_SECRET, configuration.getClientSecret()).set(REDIRECT_URI, (String) authentication.getContext().get(REDIRECT_URI)).set(CODE, authorizationCode);
    return client.postAbs(configuration.getAccessTokenUri()).rxSendForm(form).toMaybe().flatMap(httpResponse -> {
        if (httpResponse.statusCode() != 200) {
            return Maybe.error(new BadCredentialsException(httpResponse.bodyAsString()));
        }
        return Maybe.just(new Token(httpResponse.bodyAsJsonObject().getString(ACCESS_TOKEN), TokenTypeHint.ACCESS_TOKEN));
    });
}
Also used : MultiMap(io.vertx.reactivex.core.MultiMap) BadCredentialsException(io.gravitee.am.common.exception.authentication.BadCredentialsException)

Example 4 with BadCredentialsException

use of io.gravitee.am.common.exception.authentication.BadCredentialsException in project gravitee-access-management by gravitee-io.

the class ManagementAuthenticationProviderTest method shouldAuthenticate_secondAuthProvider.

@Test
public void shouldAuthenticate_secondAuthProvider() {
    AuthenticationProvider authenticationProvider = mock(AuthenticationProvider.class);
    when(authenticationProvider.loadUserByUsername(any(io.gravitee.am.identityprovider.api.Authentication.class))).thenReturn(Maybe.error(new BadCredentialsException()));
    AuthenticationProvider authenticationProvider2 = mock(AuthenticationProvider.class);
    when(authenticationProvider2.loadUserByUsername(any(io.gravitee.am.identityprovider.api.Authentication.class))).thenReturn(Maybe.just(new DefaultUser("username")));
    when(identityProviderManager.getIdentityProvider("idp1")).thenReturn(new IdentityProvider());
    when(identityProviderManager.getIdentityProvider("idp2")).thenReturn(new IdentityProvider());
    when(identityProviderManager.get("idp1")).thenReturn(authenticationProvider);
    when(identityProviderManager.get("idp2")).thenReturn(authenticationProvider2);
    Authentication authentication = managementAuthenticationProvider.authenticate(new UsernamePasswordAuthenticationToken("username", "password"));
    Assert.assertNotNull(authentication);
    verify(identityProviderManager, times(1)).get("idp1");
    verify(identityProviderManager, times(1)).get("idp2");
}
Also used : DefaultUser(io.gravitee.am.identityprovider.api.DefaultUser) Authentication(org.springframework.security.core.Authentication) AuthenticationProvider(io.gravitee.am.identityprovider.api.AuthenticationProvider) IdentityProvider(io.gravitee.am.model.IdentityProvider) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(io.gravitee.am.common.exception.authentication.BadCredentialsException) Test(org.junit.Test)

Example 5 with BadCredentialsException

use of io.gravitee.am.common.exception.authentication.BadCredentialsException in project gravitee-access-management by gravitee-io.

the class ManagementAuthenticationProviderTest method shouldNotAuthenticate_wrongCredentials.

@Test(expected = org.springframework.security.authentication.BadCredentialsException.class)
public void shouldNotAuthenticate_wrongCredentials() {
    AuthenticationProvider authenticationProvider = mock(AuthenticationProvider.class);
    when(authenticationProvider.loadUserByUsername(any(io.gravitee.am.identityprovider.api.Authentication.class))).thenReturn(Maybe.error(new BadCredentialsException()));
    AuthenticationProvider authenticationProvider2 = mock(AuthenticationProvider.class);
    when(authenticationProvider2.loadUserByUsername(any(io.gravitee.am.identityprovider.api.Authentication.class))).thenReturn(Maybe.error(new BadCredentialsException()));
    when(identityProviderManager.getIdentityProvider("idp1")).thenReturn(new IdentityProvider());
    when(identityProviderManager.getIdentityProvider("idp2")).thenReturn(new IdentityProvider());
    when(identityProviderManager.get("idp1")).thenReturn(authenticationProvider);
    when(identityProviderManager.get("idp2")).thenReturn(authenticationProvider2);
    Authentication authentication = managementAuthenticationProvider.authenticate(new UsernamePasswordAuthenticationToken("username", "password"));
    Assert.assertNull(authentication);
    verify(identityProviderManager, times(1)).get("idp1");
    verify(identityProviderManager, times(1)).get("idp2");
}
Also used : Authentication(org.springframework.security.core.Authentication) AuthenticationProvider(io.gravitee.am.identityprovider.api.AuthenticationProvider) IdentityProvider(io.gravitee.am.model.IdentityProvider) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(io.gravitee.am.common.exception.authentication.BadCredentialsException) Test(org.junit.Test)

Aggregations

BadCredentialsException (io.gravitee.am.common.exception.authentication.BadCredentialsException)16 JsonObject (io.vertx.core.json.JsonObject)7 Map (java.util.Map)6 AuthenticationProvider (io.gravitee.am.identityprovider.api.AuthenticationProvider)5 Maybe (io.reactivex.Maybe)5 BasicNameValuePair (io.gravitee.am.model.http.BasicNameValuePair)4 NameValuePair (io.gravitee.am.model.http.NameValuePair)4 HashMap (java.util.HashMap)4 AuthenticationEvent (io.gravitee.am.gateway.handler.common.auth.event.AuthenticationEvent)3 EndUserAuthentication (io.gravitee.am.gateway.handler.common.auth.user.EndUserAuthentication)3 UserAuthenticationManager (io.gravitee.am.gateway.handler.common.auth.user.UserAuthenticationManager)3 OAuthCredentials (io.gravitee.am.identityprovider.twitter.authentication.utils.OAuthCredentials)3 Client (io.gravitee.am.model.oidc.Client)3 RoutingContext (io.vertx.reactivex.ext.web.RoutingContext)3 ArrayList (java.util.ArrayList)3 Test (org.junit.Test)3 EventManager (io.gravitee.am.common.event.EventManager)2 UsernameNotFoundException (io.gravitee.am.common.exception.authentication.UsernameNotFoundException)2 StandardClaims (io.gravitee.am.common.oidc.StandardClaims)2 SecureRandomString (io.gravitee.am.common.utils.SecureRandomString)2