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();
});
}
}
}
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();
}
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));
});
}
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);
}
});
}
Aggregations