use of javax.ws.rs.WebApplicationException in project oxAuth by GluuFederation.
the class TokenRestWebServiceImpl method requestAccessToken.
@Override
public Response requestAccessToken(String grantType, String code, String redirectUri, String username, String password, String scope, String assertion, String refreshToken, String oxAuthExchangeToken, String clientId, String clientSecret, String codeVerifier, HttpServletRequest request, SecurityContext sec) {
log.debug("Attempting to request access token: grantType = {}, code = {}, redirectUri = {}, username = {}, refreshToken = {}, " + "clientId = {}, ExtraParams = {}, isSecure = {}, codeVerifier = {}", grantType, code, redirectUri, username, refreshToken, clientId, request.getParameterMap(), sec.isSecure(), codeVerifier);
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.TOKEN_REQUEST);
oAuth2AuditLog.setClientId(clientId);
oAuth2AuditLog.setUsername(username);
oAuth2AuditLog.setScope(scope);
// it may be encoded in uma case
scope = ServerUtil.urlDecode(scope);
ResponseBuilder builder = Response.ok();
try {
log.debug("Starting to validate request parameters");
if (!TokenParamsValidator.validateParams(grantType, code, redirectUri, username, password, scope, assertion, refreshToken, oxAuthExchangeToken)) {
log.trace("Failed to validate request parameters");
builder = error(400, TokenErrorResponseType.INVALID_REQUEST);
} else {
log.trace("Request parameters are right");
GrantType gt = GrantType.fromString(grantType);
log.debug("Grant type: '{}'", gt);
SessionClient sessionClient = identity.getSetSessionClient();
Client client = null;
if (sessionClient != null) {
client = sessionClient.getClient();
log.debug("Get sessionClient: '{}'", sessionClient);
}
if (client != null) {
log.debug("Get client from session: '{}'", client.getClientId());
}
if (gt == GrantType.AUTHORIZATION_CODE) {
if (client == null) {
return response(error(400, TokenErrorResponseType.INVALID_GRANT));
}
log.debug("Attempting to find authorizationCodeGrant by clinetId: '{}', code: '{}'", client.getClientId(), code);
AuthorizationCodeGrant authorizationCodeGrant = authorizationGrantList.getAuthorizationCodeGrant(client.getClientId(), code);
log.trace("AuthorizationCodeGrant : '{}'", authorizationCodeGrant);
if (authorizationCodeGrant != null) {
validatePKCE(authorizationCodeGrant, codeVerifier);
authorizationCodeGrant.setIsCachedWithNoPersistence(false);
authorizationCodeGrant.save();
AccessToken accToken = authorizationCodeGrant.createAccessToken();
log.debug("Issuing access token: {}", accToken.getCode());
RefreshToken reToken = authorizationCodeGrant.createRefreshToken();
if (scope != null && !scope.isEmpty()) {
scope = authorizationCodeGrant.checkScopesPolicy(scope);
}
IdToken idToken = null;
if (authorizationCodeGrant.getScopes().contains("openid")) {
String nonce = authorizationCodeGrant.getNonce();
boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
idToken = authorizationCodeGrant.createIdToken(nonce, null, accToken, authorizationCodeGrant, includeIdTokenClaims);
}
builder.entity(getJSonResponse(accToken, accToken.getTokenType(), accToken.getExpiresIn(), reToken, scope, idToken));
oAuth2AuditLog.updateOAuth2AuditLog(authorizationCodeGrant, true);
grantService.removeByCode(authorizationCodeGrant.getAuthorizationCode().getCode(), authorizationCodeGrant.getClientId());
} else {
log.debug("AuthorizationCodeGrant is empty by clinetId: '{}', code: '{}'", client.getClientId(), code);
// if authorization code is not found then code was already used = remove all grants with this auth code
grantService.removeAllByAuthorizationCode(code);
builder = error(400, TokenErrorResponseType.INVALID_GRANT);
}
} else if (gt == GrantType.REFRESH_TOKEN) {
if (client == null) {
return response(error(401, TokenErrorResponseType.INVALID_GRANT));
}
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByRefreshToken(client.getClientId(), refreshToken);
if (authorizationGrant != null) {
AccessToken accToken = authorizationGrant.createAccessToken();
/*
The authorization server MAY issue a new refresh token, in which case
the client MUST discard the old refresh token and replace it with the
new refresh token.
*/
RefreshToken reToken = authorizationGrant.createRefreshToken();
grantService.removeByCode(refreshToken, client.getClientId());
if (scope != null && !scope.isEmpty()) {
scope = authorizationGrant.checkScopesPolicy(scope);
}
builder.entity(getJSonResponse(accToken, accToken.getTokenType(), accToken.getExpiresIn(), reToken, scope, null));
oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
} else {
builder = error(401, TokenErrorResponseType.INVALID_GRANT);
}
} else if (gt == GrantType.CLIENT_CREDENTIALS) {
if (client == null) {
return response(error(401, TokenErrorResponseType.INVALID_GRANT));
}
// TODO: fix the user arg
ClientCredentialsGrant clientCredentialsGrant = authorizationGrantList.createClientCredentialsGrant(new User(), client);
AccessToken accessToken = clientCredentialsGrant.createAccessToken();
if (scope != null && !scope.isEmpty()) {
scope = clientCredentialsGrant.checkScopesPolicy(scope);
}
IdToken idToken = null;
if (clientCredentialsGrant.getScopes().contains("openid")) {
boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
idToken = clientCredentialsGrant.createIdToken(null, null, null, clientCredentialsGrant, includeIdTokenClaims);
}
oAuth2AuditLog.updateOAuth2AuditLog(clientCredentialsGrant, true);
builder.entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), null, scope, idToken));
} else if (gt == GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS) {
if (client == null) {
log.error("Invalid client", new RuntimeException("Client is empty"));
return response(error(401, TokenErrorResponseType.INVALID_CLIENT));
}
User user = null;
if (authenticationFilterService.isEnabled()) {
String userDn = authenticationFilterService.processAuthenticationFilters(request.getParameterMap());
if (StringHelper.isNotEmpty(userDn)) {
user = userService.getUserByDn(userDn);
}
}
if (user == null) {
boolean authenticated = authenticationService.authenticate(username, password);
if (authenticated) {
user = authenticationService.getAuthenticatedUser();
}
}
if (user != null) {
ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant = authorizationGrantList.createResourceOwnerPasswordCredentialsGrant(user, client);
AccessToken accessToken = resourceOwnerPasswordCredentialsGrant.createAccessToken();
RefreshToken reToken = resourceOwnerPasswordCredentialsGrant.createRefreshToken();
if (scope != null && !scope.isEmpty()) {
scope = resourceOwnerPasswordCredentialsGrant.checkScopesPolicy(scope);
}
IdToken idToken = null;
if (resourceOwnerPasswordCredentialsGrant.getScopes().contains("openid")) {
boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
idToken = resourceOwnerPasswordCredentialsGrant.createIdToken(null, null, null, resourceOwnerPasswordCredentialsGrant, includeIdTokenClaims);
}
oAuth2AuditLog.updateOAuth2AuditLog(resourceOwnerPasswordCredentialsGrant, true);
builder.entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), reToken, scope, idToken));
} else {
log.error("Invalid user", new RuntimeException("User is empty"));
builder = error(401, TokenErrorResponseType.INVALID_CLIENT);
}
} else if (gt == GrantType.EXTENSION) {
builder = error(501, TokenErrorResponseType.INVALID_GRANT);
} else if (gt == GrantType.OXAUTH_EXCHANGE_TOKEN) {
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(oxAuthExchangeToken);
if (authorizationGrant != null) {
final AccessToken accessToken = authorizationGrant.createLongLivedAccessToken();
oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
builder.entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), null, null, null));
} else {
builder = error(401, TokenErrorResponseType.INVALID_GRANT);
}
}
}
} catch (WebApplicationException e) {
throw e;
} catch (SignatureException e) {
builder = Response.status(500);
log.error(e.getMessage(), e);
} catch (StringEncrypter.EncryptionException e) {
builder = Response.status(500);
log.error(e.getMessage(), e);
} catch (InvalidJwtException e) {
builder = Response.status(500);
log.error(e.getMessage(), e);
} catch (InvalidJweException e) {
builder = Response.status(500);
log.error(e.getMessage(), e);
} catch (Exception e) {
builder = Response.status(500);
log.error(e.getMessage(), e);
}
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return response(builder);
}
use of javax.ws.rs.WebApplicationException in project oxAuth by GluuFederation.
the class U2fRegistrationWS method finishRegistration.
@POST
@Produces({ "application/json" })
public Response finishRegistration(@FormParam("username") String userName, @FormParam("tokenResponse") String registerResponseString) {
String sessionState = null;
try {
log.debug("Finishing registration for username '{}' with response '{}'", userName, registerResponseString);
RegisterResponse registerResponse = ServerUtil.jsonMapperWithWrapRoot().readValue(registerResponseString, RegisterResponse.class);
String requestId = registerResponse.getRequestId();
RegisterRequestMessageLdap registerRequestMessageLdap = u2fRegistrationService.getRegisterRequestMessageByRequestId(requestId);
if (registerRequestMessageLdap == null) {
throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN).entity(errorResponseFactory.getJsonErrorResponse(U2fErrorResponseType.SESSION_EXPIRED)).build());
}
u2fRegistrationService.removeRegisterRequestMessage(registerRequestMessageLdap);
String foundUserInum = registerRequestMessageLdap.getUserInum();
RegisterRequestMessage registerRequestMessage = registerRequestMessageLdap.getRegisterRequestMessage();
DeviceRegistrationResult deviceRegistrationResult = u2fRegistrationService.finishRegistration(registerRequestMessage, registerResponse, foundUserInum);
// If sessionState is not empty update session
sessionState = registerRequestMessageLdap.getSessionState();
if (StringHelper.isNotEmpty(sessionState)) {
log.debug("There is session state. Setting session state attributes");
boolean oneStep = StringHelper.isEmpty(foundUserInum);
userSessionStateService.updateUserSessionStateOnFinishRequest(sessionState, foundUserInum, deviceRegistrationResult, true, oneStep);
}
RegisterStatus registerStatus = new RegisterStatus(Constants.RESULT_SUCCESS, requestId);
// Convert manually to avoid possible conflict between resteasy providers, e.g. jettison, jackson
final String entity = ServerUtil.asJson(registerStatus);
return Response.status(Response.Status.OK).entity(entity).cacheControl(ServerUtil.cacheControl(true)).build();
} catch (Exception ex) {
log.error("Exception happened", ex);
try {
// If sessionState is not empty update session
if (StringHelper.isNotEmpty(sessionState)) {
log.debug("There is session state. Setting session state status to 'declined'");
userSessionStateService.updateUserSessionStateOnError(sessionState);
}
} catch (Exception ex2) {
log.error("Failed to update session state status", ex2);
}
if (ex instanceof WebApplicationException) {
throw (WebApplicationException) ex;
}
if (ex instanceof BadInputException) {
throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN).entity(errorResponseFactory.getErrorResponse(U2fErrorResponseType.INVALID_REQUEST)).build());
}
throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorResponseFactory.getJsonErrorResponse(U2fErrorResponseType.SERVER_ERROR)).build());
}
}
use of javax.ws.rs.WebApplicationException in project oxAuth by GluuFederation.
the class U2fAuthenticationWS method finishAuthentication.
@POST
@Produces({ "application/json" })
public Response finishAuthentication(@FormParam("username") String userName, @FormParam("tokenResponse") String authenticateResponseString) {
String sessionState = null;
try {
log.debug("Finishing authentication for username '{}' with response '{}'", userName, authenticateResponseString);
AuthenticateResponse authenticateResponse = ServerUtil.jsonMapperWithWrapRoot().readValue(authenticateResponseString, AuthenticateResponse.class);
String requestId = authenticateResponse.getRequestId();
AuthenticateRequestMessageLdap authenticateRequestMessageLdap = u2fAuthenticationService.getAuthenticationRequestMessageByRequestId(requestId);
if (authenticateRequestMessageLdap == null) {
throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN).entity(errorResponseFactory.getJsonErrorResponse(U2fErrorResponseType.SESSION_EXPIRED)).build());
}
sessionState = authenticateRequestMessageLdap.getSessionState();
u2fAuthenticationService.removeAuthenticationRequestMessage(authenticateRequestMessageLdap);
AuthenticateRequestMessage authenticateRequestMessage = authenticateRequestMessageLdap.getAuthenticateRequestMessage();
String foundUserInum = authenticateRequestMessageLdap.getUserInum();
DeviceRegistrationResult deviceRegistrationResult = u2fAuthenticationService.finishAuthentication(authenticateRequestMessage, authenticateResponse, foundUserInum);
// If sessionState is not empty update session
if (StringHelper.isNotEmpty(sessionState)) {
log.debug("There is session state. Setting session state attributes");
boolean oneStep = StringHelper.isEmpty(userName);
userSessionStateService.updateUserSessionStateOnFinishRequest(sessionState, foundUserInum, deviceRegistrationResult, false, oneStep);
}
AuthenticateStatus authenticationStatus = new AuthenticateStatus(Constants.RESULT_SUCCESS, requestId);
// convert manually to avoid possible conflict between resteasy
// providers, e.g. jettison, jackson
final String entity = ServerUtil.asJson(authenticationStatus);
return Response.status(Response.Status.OK).entity(entity).cacheControl(ServerUtil.cacheControl(true)).build();
} catch (Exception ex) {
log.error("Exception happened", ex);
if (ex instanceof WebApplicationException) {
throw (WebApplicationException) ex;
}
try {
// If sessionState is not empty update session
if (StringHelper.isNotEmpty(sessionState)) {
log.debug("There is session state. Setting session state status to 'declined'");
userSessionStateService.updateUserSessionStateOnError(sessionState);
}
} catch (Exception ex2) {
log.error("Failed to update session state status", ex2);
}
if (ex instanceof BadInputException) {
throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN).entity(errorResponseFactory.getErrorResponse(U2fErrorResponseType.INVALID_REQUEST)).build());
}
if (ex instanceof DeviceCompromisedException) {
DeviceRegistration deviceRegistration = ((DeviceCompromisedException) ex).getDeviceRegistration();
try {
deviceRegistrationService.disableUserDeviceRegistration(deviceRegistration);
} catch (Exception ex2) {
log.error("Failed to mark device '{}' as compomised", ex2, deviceRegistration.getId());
}
throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN).entity(errorResponseFactory.getErrorResponse(U2fErrorResponseType.DEVICE_COMPROMISED)).build());
}
throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorResponseFactory.getJsonErrorResponse(U2fErrorResponseType.SERVER_ERROR)).build());
}
}
use of javax.ws.rs.WebApplicationException in project oxAuth by GluuFederation.
the class U2fRegistrationWS method startRegistration.
@GET
@Produces({ "application/json" })
public Response startRegistration(@QueryParam("username") String userName, @QueryParam("application") String appId, @QueryParam("session_state") String sessionState, @QueryParam("enrollment_code") String enrollmentCode) {
// Parameter username is deprecated. We uses it only to determine is it's one or two step workflow
try {
log.debug("Startig registration with username '{}' for appId '{}'. session_state '{}', enrollment_code '{}'", userName, appId, sessionState, enrollmentCode);
String userInum = null;
boolean sessionBasedEnrollment = false;
boolean twoStep = StringHelper.isNotEmpty(userName);
if (twoStep) {
boolean removeEnrollment = false;
if (StringHelper.isNotEmpty(sessionState)) {
boolean valid = u2fValidationService.isValidSessionState(userName, sessionState);
if (!valid) {
throw new BadInputException(String.format("session_state '%s' is invalid", sessionState));
}
sessionBasedEnrollment = true;
} else if (StringHelper.isNotEmpty(enrollmentCode)) {
boolean valid = u2fValidationService.isValidEnrollmentCode(userName, enrollmentCode);
if (!valid) {
throw new BadInputException(String.format("enrollment_code '%s' is invalid", enrollmentCode));
}
removeEnrollment = true;
} else {
throw new BadInputException(String.format("session_state or enrollment_code is mandatory"));
}
User user = userService.getUser(userName);
userInum = userService.getUserInum(user);
if (StringHelper.isEmpty(userInum)) {
throw new BadInputException(String.format("Failed to find user '%s' in LDAP", userName));
}
if (removeEnrollment) {
// We allow to use enrollment code only one time
user.setAttribute(U2fConstants.U2F_ENROLLMENT_CODE_ATTRIBUTE, (String) null);
userService.updateUser(user);
}
}
if (sessionBasedEnrollment) {
List<DeviceRegistration> deviceRegistrations = deviceRegistrationService.findUserDeviceRegistrations(userInum, appId);
if (deviceRegistrations.size() > 0 && !isCurrentAuthenticationLevelCorrespondsToU2fLevel(sessionState)) {
throw new RegistrationNotAllowed(String.format("It's not possible to start registration with user_name and session_state becuase user '%s' has already enrolled device", userName));
}
}
RegisterRequestMessage registerRequestMessage = u2fRegistrationService.builRegisterRequestMessage(appId, userInum);
u2fRegistrationService.storeRegisterRequestMessage(registerRequestMessage, userInum, sessionState);
// Convert manually to avoid possible conflict between resteasy providers, e.g. jettison, jackson
final String entity = ServerUtil.asJson(registerRequestMessage);
return Response.status(Response.Status.OK).entity(entity).cacheControl(ServerUtil.cacheControl(true)).build();
} catch (Exception ex) {
log.error("Exception happened", ex);
if (ex instanceof WebApplicationException) {
throw (WebApplicationException) ex;
}
if (ex instanceof RegistrationNotAllowed) {
throw new WebApplicationException(Response.status(Response.Status.NOT_ACCEPTABLE).entity(errorResponseFactory.getErrorResponse(U2fErrorResponseType.REGISTRATION_NOT_ALLOWED)).build());
}
throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorResponseFactory.getJsonErrorResponse(U2fErrorResponseType.SERVER_ERROR)).build());
}
}
use of javax.ws.rs.WebApplicationException in project oxAuth by GluuFederation.
the class UmaValidationService method validateAuthorization.
private AuthorizationGrant validateAuthorization(String authorization, UmaScopeType umaScopeType) {
log.trace("Validate authorization: {}", authorization);
if (StringHelper.isEmpty(authorization)) {
throw new WebApplicationException(Response.status(UNAUTHORIZED).entity(errorResponseFactory.getUmaJsonErrorResponse(UNAUTHORIZED_CLIENT)).build());
}
String token = tokenService.getTokenFromAuthorizationParameter(authorization);
if (StringHelper.isEmpty(token)) {
log.debug("Token is invalid");
throw new WebApplicationException(Response.status(UNAUTHORIZED).entity(errorResponseFactory.getUmaJsonErrorResponse(UNAUTHORIZED_CLIENT)).build());
}
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(token);
if (authorizationGrant == null) {
throw new WebApplicationException(Response.status(UNAUTHORIZED).entity(errorResponseFactory.getUmaJsonErrorResponse(ACCESS_DENIED)).build());
}
if (!authorizationGrant.isValid()) {
throw new WebApplicationException(Response.status(UNAUTHORIZED).entity(errorResponseFactory.getUmaJsonErrorResponse(INVALID_TOKEN)).build());
}
Set<String> scopes = authorizationGrant.getScopes();
if (!scopes.contains(umaScopeType.getValue())) {
throw new WebApplicationException(Response.status(Response.Status.NOT_ACCEPTABLE).entity(errorResponseFactory.getUmaJsonErrorResponse(UmaErrorResponseType.INVALID_CLIENT_SCOPE)).build());
}
return authorizationGrant;
}
Aggregations