Search in sources :

Example 1 with USERNAME

use of io.gravitee.am.common.oauth2.Parameters.USERNAME in project gravitee-access-management by gravitee-io.

the class LoginFormHandler method handle.

@Override
public void handle(RoutingContext context) {
    HttpServerRequest req = context.request();
    if (req.method() != HttpMethod.POST) {
        // Must be a POST
        context.fail(405);
    } else {
        if (!req.isExpectMultipart()) {
            throw new IllegalStateException("Form body not parsed - do you forget to include a BodyHandler?");
        }
        MultiMap params = req.formAttributes();
        String username = params.get(USERNAME_PARAM_KEY);
        String password = params.get(PASSWORD_PARAM_KEY);
        String clientId = params.get(Parameters.CLIENT_ID);
        if (username == null || password == null) {
            logger.warn("No username or password provided in form - did you forget to include a BodyHandler?");
            context.fail(400);
        } else if (clientId == null) {
            logger.warn("No client id in form - did you forget to include client_id query parameter ?");
            context.fail(400);
        } else {
            // build authentication object with ip address and user agent
            JsonObject authInfo = new JsonObject().put(USERNAME_PARAM_KEY, username).put(PASSWORD_PARAM_KEY, password).put(Claims.ip_address, RequestUtils.remoteAddress(req)).put(Claims.user_agent, RequestUtils.userAgent(req)).put(Parameters.CLIENT_ID, clientId);
            authProvider.authenticate(context, authInfo, res -> {
                if (res.failed()) {
                    logger.debug("An error has occurred during the authentication process", res.cause());
                    context.fail(res.cause());
                    return;
                }
                // authentication success
                // set user into the context and continue
                final User result = res.result();
                context.getDelegate().setUser(result);
                context.put(ConstantKeys.USER_CONTEXT_KEY, result.getUser());
                context.next();
            });
        }
    }
}
Also used : RequestUtils(io.gravitee.am.gateway.handler.common.vertx.utils.RequestUtils) Logger(org.slf4j.Logger) HttpServerRequest(io.vertx.reactivex.core.http.HttpServerRequest) LoggerFactory(org.slf4j.LoggerFactory) ConstantKeys(io.gravitee.am.common.utils.ConstantKeys) RoutingContext(io.vertx.reactivex.ext.web.RoutingContext) MultiMap(io.vertx.reactivex.core.MultiMap) UserAuthProvider(io.gravitee.am.gateway.handler.common.vertx.web.auth.provider.UserAuthProvider) PASSWORD_PARAM_KEY(io.gravitee.am.common.utils.ConstantKeys.PASSWORD_PARAM_KEY) HttpMethod(io.vertx.core.http.HttpMethod) Claims(io.gravitee.am.common.jwt.Claims) User(io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User) JsonObject(io.vertx.core.json.JsonObject) Handler(io.vertx.core.Handler) Parameters(io.gravitee.am.common.oauth2.Parameters) USERNAME_PARAM_KEY(io.gravitee.am.common.utils.ConstantKeys.USERNAME_PARAM_KEY) MultiMap(io.vertx.reactivex.core.MultiMap) User(io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User) HttpServerRequest(io.vertx.reactivex.core.http.HttpServerRequest) JsonObject(io.vertx.core.json.JsonObject)

Example 2 with USERNAME

use of io.gravitee.am.common.oauth2.Parameters.USERNAME in project gravitee-access-management by gravitee-io.

the class ResourceOwnerPasswordCredentialsTokenGranter method resolveResourceOwner.

@Override
protected Maybe<User> resolveResourceOwner(TokenRequest tokenRequest, Client client) {
    String username = tokenRequest.getUsername();
    String password = tokenRequest.getPassword();
    return userAuthenticationManager.authenticate(client, new EndUserAuthentication(username, password, new SimpleAuthenticationContext(tokenRequest))).onErrorResumeNext(ex -> Single.error(new InvalidGrantException(ex.getMessage()))).toMaybe();
}
Also used : InvalidGrantException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException) GrantType(io.gravitee.am.common.oauth2.GrantType) UserAuthenticationManager(io.gravitee.am.gateway.handler.common.auth.user.UserAuthenticationManager) TokenRequest(io.gravitee.am.gateway.handler.oauth2.service.request.TokenRequest) Client(io.gravitee.am.model.oidc.Client) MultiValueMap(io.gravitee.common.util.MultiValueMap) Maybe(io.reactivex.Maybe) AbstractTokenGranter(io.gravitee.am.gateway.handler.oauth2.service.granter.AbstractTokenGranter) TokenService(io.gravitee.am.gateway.handler.oauth2.service.token.TokenService) Single(io.reactivex.Single) InvalidRequestException(io.gravitee.am.common.exception.oauth2.InvalidRequestException) USERNAME(io.gravitee.am.common.oauth2.Parameters.USERNAME) EndUserAuthentication(io.gravitee.am.gateway.handler.common.auth.user.EndUserAuthentication) TokenRequestResolver(io.gravitee.am.gateway.handler.oauth2.service.request.TokenRequestResolver) PASSWORD(io.gravitee.am.common.oauth2.Parameters.PASSWORD) User(io.gravitee.am.model.User) SimpleAuthenticationContext(io.gravitee.am.identityprovider.api.SimpleAuthenticationContext) SimpleAuthenticationContext(io.gravitee.am.identityprovider.api.SimpleAuthenticationContext) InvalidGrantException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException) EndUserAuthentication(io.gravitee.am.gateway.handler.common.auth.user.EndUserAuthentication)

Example 3 with USERNAME

use of io.gravitee.am.common.oauth2.Parameters.USERNAME in project gravitee-access-management by gravitee-io.

the class SocialAuthenticationProvider method authenticate.

@Override
public void authenticate(RoutingContext context, JsonObject authInfo, Handler<AsyncResult<User>> resultHandler) {
    final Client client = context.get(CLIENT_CONTEXT_KEY);
    final AuthenticationProvider authenticationProvider = context.get(PROVIDER_CONTEXT_KEY);
    final String authProvider = context.get(PROVIDER_ID_PARAM_KEY);
    final String username = authInfo.getString(USERNAME_PARAM_KEY);
    final String password = authInfo.getString(PASSWORD_PARAM_KEY);
    logger.debug("Authentication attempt using social identity provider {}", authProvider);
    // create authentication context
    SimpleAuthenticationContext authenticationContext = new SimpleAuthenticationContext(new VertxHttpServerRequest(context.request().getDelegate()));
    authenticationContext.attributes().putAll(context.data());
    authenticationContext.set(Parameters.REDIRECT_URI, authInfo.getString(Parameters.REDIRECT_URI));
    // create user authentication
    EndUserAuthentication endUserAuthentication = new EndUserAuthentication(username, password, authenticationContext);
    endUserAuthentication.getContext().set(Claims.ip_address, RequestUtils.remoteAddress(context.request()));
    endUserAuthentication.getContext().set(Claims.user_agent, RequestUtils.userAgent(context.request()));
    // authenticate the user via the social provider
    authenticationProvider.loadUserByUsername(endUserAuthentication).switchIfEmpty(Maybe.error(new BadCredentialsException("Unable to authenticate social provider, authentication provider has returned empty value"))).flatMapSingle(user -> {
        // set source and client for the current authenticated end-user
        Map<String, Object> additionalInformation = user.getAdditionalInformation() == null ? new HashMap<>() : new HashMap<>(user.getAdditionalInformation());
        additionalInformation.put("source", authProvider);
        additionalInformation.put(Parameters.CLIENT_ID, client.getClientId());
        var accessToken = ofNullable(endUserAuthentication.getContext().get(ACCESS_TOKEN_KEY));
        var idToken = ofNullable(endUserAuthentication.getContext().get(ID_TOKEN_KEY));
        accessToken.ifPresentOrElse(at -> {
            // If isStoreOriginalToken, we add both the access_token and id_token in profile since they are present
            additionalInformation.put(OIDC_PROVIDER_ID_ACCESS_TOKEN_KEY, at);
            idToken.ifPresent(it -> additionalInformation.put(OIDC_PROVIDER_ID_TOKEN_KEY, it));
        }, () -> {
            // We remove both otherwise
            additionalInformation.remove(OIDC_PROVIDER_ID_ACCESS_TOKEN_KEY);
            additionalInformation.remove(OIDC_PROVIDER_ID_TOKEN_KEY);
        });
        // If id_token is present and SSO is enabled we add the id_token in profile
        if (client.isSingleSignOut() && idToken.isPresent()) {
            logger.debug("Single SignOut enable for client '{}' store the id_token coming from the provider {} as additional information", client.getId(), authProvider);
            additionalInformation.put(OIDC_PROVIDER_ID_TOKEN_KEY, idToken.get());
        } else if (accessToken.isEmpty()) {
            // unless isStoreOriginalToken is enabled (e.g access_token isPresent) we can remove id_token from the profile
            additionalInformation.remove(OIDC_PROVIDER_ID_TOKEN_KEY);
        }
        ((DefaultUser) user).setAdditionalInformation(additionalInformation);
        return userAuthenticationManager.connect(user);
    }).subscribe(user -> {
        eventManager.publishEvent(AuthenticationEvent.SUCCESS, new AuthenticationDetails(endUserAuthentication, domain, client, user));
        resultHandler.handle(Future.succeededFuture(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(user)));
    }, error -> {
        logger.error("Unable to authenticate social provider", error);
        eventManager.publishEvent(AuthenticationEvent.FAILURE, new AuthenticationDetails(endUserAuthentication, domain, client, error));
        resultHandler.handle(Future.failedFuture(error));
    });
}
Also used : Client(io.gravitee.am.model.oidc.Client) Maybe(io.reactivex.Maybe) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) ConstantKeys(io.gravitee.am.common.utils.ConstantKeys) DefaultUser(io.gravitee.am.identityprovider.api.DefaultUser) BadCredentialsException(io.gravitee.am.common.exception.authentication.BadCredentialsException) Map(java.util.Map) User(io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) SimpleAuthenticationContext(io.gravitee.am.identityprovider.api.SimpleAuthenticationContext) RequestUtils(io.gravitee.am.gateway.handler.common.vertx.utils.RequestUtils) Logger(org.slf4j.Logger) UserAuthenticationManager(io.gravitee.am.gateway.handler.common.auth.user.UserAuthenticationManager) Optional.ofNullable(java.util.Optional.ofNullable) Domain(io.gravitee.am.model.Domain) AuthenticationProvider(io.gravitee.am.identityprovider.api.AuthenticationProvider) VertxHttpServerRequest(io.gravitee.am.gateway.handler.common.vertx.core.http.VertxHttpServerRequest) Future(io.vertx.core.Future) RoutingContext(io.vertx.reactivex.ext.web.RoutingContext) AuthenticationDetails(io.gravitee.am.gateway.handler.common.auth.AuthenticationDetails) AuthenticationEvent(io.gravitee.am.gateway.handler.common.auth.event.AuthenticationEvent) UserAuthProvider(io.gravitee.am.gateway.handler.common.vertx.web.auth.provider.UserAuthProvider) EventManager(io.gravitee.common.event.EventManager) EndUserAuthentication(io.gravitee.am.gateway.handler.common.auth.user.EndUserAuthentication) Claims(io.gravitee.am.common.jwt.Claims) Handler(io.vertx.core.Handler) Parameters(io.gravitee.am.common.oauth2.Parameters) DefaultUser(io.gravitee.am.identityprovider.api.DefaultUser) User(io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User) HashMap(java.util.HashMap) AuthenticationProvider(io.gravitee.am.identityprovider.api.AuthenticationProvider) SimpleAuthenticationContext(io.gravitee.am.identityprovider.api.SimpleAuthenticationContext) VertxHttpServerRequest(io.gravitee.am.gateway.handler.common.vertx.core.http.VertxHttpServerRequest) BadCredentialsException(io.gravitee.am.common.exception.authentication.BadCredentialsException) Client(io.gravitee.am.model.oidc.Client) HashMap(java.util.HashMap) Map(java.util.Map) EndUserAuthentication(io.gravitee.am.gateway.handler.common.auth.user.EndUserAuthentication) AuthenticationDetails(io.gravitee.am.gateway.handler.common.auth.AuthenticationDetails)

Example 4 with USERNAME

use of io.gravitee.am.common.oauth2.Parameters.USERNAME in project gravitee-access-management by gravitee-io.

the class UserAuthenticationManagerImpl method loadUserByUsername.

@Override
public Maybe<User> loadUserByUsername(Client client, String username, Request request) {
    logger.debug("Trying to load user [{}]", username);
    // Get identity providers associated to a client
    // For each idp, try to find the user while it can not be found
    // If user can't be found, send an exception
    // Skip external identity provider for authentication with credentials.
    List<String> identities = client.getIdentityProviders() != null ? client.getIdentityProviders().stream().map(idp -> identityProviderManager.getIdentityProvider(idp.getIdentity())).filter(idp -> idp != null && !idp.isExternal()).map(IdentityProvider::getId).collect(Collectors.toList()) : null;
    if (identities == null || identities.isEmpty()) {
        logger.error("No identity provider found for client : " + client.getClientId());
        return Maybe.error(new InternalAuthenticationServiceException("No identity provider found for client : " + client.getClientId()));
    }
    final Authentication authentication = new EndUserAuthentication(username, null, new SimpleAuthenticationContext(request));
    return Observable.fromIterable(identities).flatMapMaybe(authProvider -> loadUserByUsername0(client, authentication, authProvider, true)).takeUntil(userAuthentication -> userAuthentication.getUser() != null).lastOrError().flatMapMaybe(userAuthentication -> {
        io.gravitee.am.identityprovider.api.User user = userAuthentication.getUser();
        if (user == null) {
            Throwable lastException = userAuthentication.getLastException();
            if (lastException != null) {
                if (lastException instanceof UsernameNotFoundException) {
                    return Maybe.error(new UsernameNotFoundException("Invalid or unknown user"));
                } else {
                    logger.error("An error occurs during user authentication", lastException);
                    return Maybe.error(new InternalAuthenticationServiceException("Unable to validate credentials. The user account you are trying to access may be experiencing a problem.", lastException));
                }
            } else {
                return Maybe.error(new UsernameNotFoundException("No user found for registered providers"));
            }
        } else {
            // complete user connection
            return userAuthenticationService.loadPreAuthenticatedUser(user);
        }
    });
}
Also used : Client(io.gravitee.am.model.oidc.Client) Completable(io.reactivex.Completable) Authentication(io.gravitee.am.identityprovider.api.Authentication) Maybe(io.reactivex.Maybe) LoggerFactory(org.slf4j.LoggerFactory) IdentityProviderManager(io.gravitee.am.gateway.handler.common.auth.idp.IdentityProviderManager) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) IdentityProvider(io.gravitee.am.model.IdentityProvider) Single(io.reactivex.Single) DefaultUser(io.gravitee.am.identityprovider.api.DefaultUser) ApplicationIdentityProvider(io.gravitee.am.model.idp.ApplicationIdentityProvider) UserAuthenticationService(io.gravitee.am.gateway.handler.common.auth.user.UserAuthenticationService) Request(io.gravitee.gateway.api.Request) io.gravitee.am.common.exception.authentication(io.gravitee.am.common.exception.authentication) Map(java.util.Map) Observable(io.reactivex.Observable) User(io.gravitee.am.model.User) SimpleAuthenticationContext(io.gravitee.am.identityprovider.api.SimpleAuthenticationContext) LoginAttemptService(io.gravitee.am.service.LoginAttemptService) Logger(org.slf4j.Logger) UserAuthenticationManager(io.gravitee.am.gateway.handler.common.auth.user.UserAuthenticationManager) Domain(io.gravitee.am.model.Domain) Collectors(java.util.stream.Collectors) AuthenticationDetails(io.gravitee.am.gateway.handler.common.auth.AuthenticationDetails) AuthenticationEvent(io.gravitee.am.gateway.handler.common.auth.event.AuthenticationEvent) LoginAttemptCriteria(io.gravitee.am.repository.management.api.search.LoginAttemptCriteria) List(java.util.List) PasswordService(io.gravitee.am.service.PasswordService) EventManager(io.gravitee.common.event.EventManager) EndUserAuthentication(io.gravitee.am.gateway.handler.common.auth.user.EndUserAuthentication) UserService(io.gravitee.am.gateway.handler.common.user.UserService) Optional(java.util.Optional) Parameters(io.gravitee.am.common.oauth2.Parameters) AccountSettings(io.gravitee.am.model.account.AccountSettings) IdentityProvider(io.gravitee.am.model.IdentityProvider) ApplicationIdentityProvider(io.gravitee.am.model.idp.ApplicationIdentityProvider) SimpleAuthenticationContext(io.gravitee.am.identityprovider.api.SimpleAuthenticationContext) Authentication(io.gravitee.am.identityprovider.api.Authentication) EndUserAuthentication(io.gravitee.am.gateway.handler.common.auth.user.EndUserAuthentication) EndUserAuthentication(io.gravitee.am.gateway.handler.common.auth.user.EndUserAuthentication)

Aggregations

Parameters (io.gravitee.am.common.oauth2.Parameters)3 EndUserAuthentication (io.gravitee.am.gateway.handler.common.auth.user.EndUserAuthentication)3 UserAuthenticationManager (io.gravitee.am.gateway.handler.common.auth.user.UserAuthenticationManager)3 SimpleAuthenticationContext (io.gravitee.am.identityprovider.api.SimpleAuthenticationContext)3 Client (io.gravitee.am.model.oidc.Client)3 Maybe (io.reactivex.Maybe)3 Logger (org.slf4j.Logger)3 LoggerFactory (org.slf4j.LoggerFactory)3 Claims (io.gravitee.am.common.jwt.Claims)2 ConstantKeys (io.gravitee.am.common.utils.ConstantKeys)2 AuthenticationDetails (io.gravitee.am.gateway.handler.common.auth.AuthenticationDetails)2 AuthenticationEvent (io.gravitee.am.gateway.handler.common.auth.event.AuthenticationEvent)2 RequestUtils (io.gravitee.am.gateway.handler.common.vertx.utils.RequestUtils)2 UserAuthProvider (io.gravitee.am.gateway.handler.common.vertx.web.auth.provider.UserAuthProvider)2 User (io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User)2 DefaultUser (io.gravitee.am.identityprovider.api.DefaultUser)2 Domain (io.gravitee.am.model.Domain)2 User (io.gravitee.am.model.User)2 EventManager (io.gravitee.common.event.EventManager)2 Single (io.reactivex.Single)2