KEYCLOAK-5567 Set correct status code on login error pages

This commit is contained in:
Stian Thorgersen 2017-11-14 09:56:26 +01:00 committed by Stian Thorgersen
parent 1412fed265
commit 89f4b87038
28 changed files with 181 additions and 200 deletions

View file

@ -41,9 +41,9 @@ public interface AccountProvider extends Provider {
Response createResponse(AccountPages page);
AccountProvider setError(String message, Object ... parameters);
AccountProvider setError(Response.Status status, String message, Object ... parameters);
AccountProvider setErrors(List<FormMessage> messages);
AccountProvider setErrors(Response.Status status, List<FormMessage> messages);
AccountProvider setSuccess(String message, Object ... parameters);
@ -53,8 +53,6 @@ public interface AccountProvider extends Provider {
AccountProvider setProfileFormData(MultivaluedMap<String, String> formData);
AccountProvider setStatus(Response.Status status);
AccountProvider setRealm(RealmModel realm);
AccountProvider setReferrer(String[] referrer);

View file

@ -48,40 +48,40 @@ public interface LoginFormsProvider extends Provider {
*/
void addScript(String scriptUrl);
public Response createResponse(UserModel.RequiredAction action);
Response createResponse(UserModel.RequiredAction action);
Response createForm(String form);
public Response createLogin();
Response createLogin();
public Response createPasswordReset();
Response createPasswordReset();
public Response createLoginTotp();
Response createLoginTotp();
public Response createRegistration();
Response createRegistration();
public Response createInfoPage();
Response createInfoPage();
public Response createUpdateProfilePage();
Response createUpdateProfilePage();
public Response createIdpLinkConfirmLinkPage();
Response createIdpLinkConfirmLinkPage();
public Response createIdpLinkEmailPage();
Response createIdpLinkEmailPage();
public Response createLoginExpiredPage();
Response createLoginExpiredPage();
public Response createErrorPage();
Response createErrorPage(Response.Status status);
public Response createOAuthGrant();
Response createOAuthGrant();
public Response createCode();
Response createCode();
public LoginFormsProvider setAuthenticationSession(AuthenticationSessionModel authenticationSession);
LoginFormsProvider setAuthenticationSession(AuthenticationSessionModel authenticationSession);
public LoginFormsProvider setClientSessionCode(String accessCode);
LoginFormsProvider setClientSessionCode(String accessCode);
public LoginFormsProvider setAccessRequest(List<RoleModel> realmRolesRequested, MultivaluedMap<String,RoleModel> resourceRolesRequested, List<ProtocolMapperModel> protocolMappers);
public LoginFormsProvider setAccessRequest(String message);
LoginFormsProvider setAccessRequest(List<RoleModel> realmRolesRequested, MultivaluedMap<String,RoleModel> resourceRolesRequested, List<ProtocolMapperModel> protocolMappers);
LoginFormsProvider setAccessRequest(String message);
/**
* Set one global error message.
@ -89,14 +89,14 @@ public interface LoginFormsProvider extends Provider {
* @param message key of message
* @param parameters to be formatted into message
*/
public LoginFormsProvider setError(String message, Object ... parameters);
LoginFormsProvider setError(String message, Object ... parameters);
/**
* Set multiple error messages.
*
* @param messages to be set
*/
public LoginFormsProvider setErrors(List<FormMessage> messages);
LoginFormsProvider setErrors(List<FormMessage> messages);
LoginFormsProvider addError(FormMessage errorMessage);
@ -108,19 +108,19 @@ public interface LoginFormsProvider extends Provider {
*/
LoginFormsProvider addSuccess(FormMessage errorMessage);
public LoginFormsProvider setSuccess(String message, Object ... parameters);
LoginFormsProvider setSuccess(String message, Object ... parameters);
public LoginFormsProvider setInfo(String message, Object ... parameters);
LoginFormsProvider setInfo(String message, Object ... parameters);
public LoginFormsProvider setUser(UserModel user);
LoginFormsProvider setUser(UserModel user);
public LoginFormsProvider setResponseHeader(String headerName, String headerValue);
LoginFormsProvider setResponseHeader(String headerName, String headerValue);
public LoginFormsProvider setFormData(MultivaluedMap<String, String> formData);
LoginFormsProvider setFormData(MultivaluedMap<String, String> formData);
LoginFormsProvider setAttribute(String name, Object value);
public LoginFormsProvider setStatus(Response.Status status);
LoginFormsProvider setStatus(Response.Status status);
LoginFormsProvider setActionUri(URI requestUri);

View file

@ -610,25 +610,25 @@ public class AuthenticationProcessor {
if (e.getError() == AuthenticationFlowError.INVALID_USER) {
ServicesLogger.LOGGER.failedAuthentication(e);
event.error(Errors.USER_NOT_FOUND);
return ErrorPage.error(session, authenticationSession, Messages.INVALID_USER);
return ErrorPage.error(session, authenticationSession, Response.Status.BAD_REQUEST, Messages.INVALID_USER);
} else if (e.getError() == AuthenticationFlowError.USER_DISABLED) {
ServicesLogger.LOGGER.failedAuthentication(e);
event.error(Errors.USER_DISABLED);
return ErrorPage.error(session,authenticationSession, Messages.ACCOUNT_DISABLED);
return ErrorPage.error(session,authenticationSession, Response.Status.BAD_REQUEST, Messages.ACCOUNT_DISABLED);
} else if (e.getError() == AuthenticationFlowError.USER_TEMPORARILY_DISABLED) {
ServicesLogger.LOGGER.failedAuthentication(e);
event.error(Errors.USER_TEMPORARILY_DISABLED);
return ErrorPage.error(session,authenticationSession, Messages.INVALID_USER);
return ErrorPage.error(session,authenticationSession, Response.Status.BAD_REQUEST, Messages.INVALID_USER);
} else if (e.getError() == AuthenticationFlowError.INVALID_CLIENT_SESSION) {
ServicesLogger.LOGGER.failedAuthentication(e);
event.error(Errors.INVALID_CODE);
return ErrorPage.error(session, authenticationSession, Messages.INVALID_CODE);
return ErrorPage.error(session, authenticationSession, Response.Status.BAD_REQUEST, Messages.INVALID_CODE);
} else if (e.getError() == AuthenticationFlowError.EXPIRED_CODE) {
ServicesLogger.LOGGER.failedAuthentication(e);
event.error(Errors.EXPIRED_CODE);
return ErrorPage.error(session, authenticationSession, Messages.EXPIRED_CODE);
return ErrorPage.error(session, authenticationSession, Response.Status.BAD_REQUEST, Messages.EXPIRED_CODE);
} else if (e.getError() == AuthenticationFlowError.FORK_FLOW) {
ForkFlowException reset = (ForkFlowException)e;
@ -655,13 +655,13 @@ public class AuthenticationProcessor {
} else {
ServicesLogger.LOGGER.failedAuthentication(e);
event.error(Errors.INVALID_USER_CREDENTIALS);
return ErrorPage.error(session, authenticationSession, Messages.INVALID_USER);
return ErrorPage.error(session, authenticationSession, Response.Status.BAD_REQUEST, Messages.INVALID_USER);
}
} else {
ServicesLogger.LOGGER.failedAuthentication(failure);
event.error(Errors.INVALID_USER_CREDENTIALS);
return ErrorPage.error(session, authenticationSession, Messages.UNEXPECTED_ERROR_HANDLING_REQUEST);
return ErrorPage.error(session, authenticationSession, Response.Status.BAD_REQUEST, Messages.UNEXPECTED_ERROR_HANDLING_REQUEST);
}
}
@ -886,7 +886,7 @@ public class AuthenticationProcessor {
if (!authSession.getAuthenticatedUser().equals(userSession.getUser())) {
event.detail(Details.EXISTING_USER, userSession.getUser().getId());
event.error(Errors.DIFFERENT_USER_AUTHENTICATED);
throw new ErrorPageException(session, authSession, Messages.DIFFERENT_USER_AUTHENTICATED, userSession.getUser().getUsername());
throw new ErrorPageException(session, authSession, Response.Status.INTERNAL_SERVER_ERROR, Messages.DIFFERENT_USER_AUTHENTICATED, userSession.getUser().getUsername());
}
}
userSession.setState(UserSessionModel.State.LOGGED_IN);

View file

@ -85,7 +85,7 @@ public class ResetCredentialsActionTokenHandler extends AbstractActionTokenHande
UserModel linkingUser = AbstractIdpAuthenticator.getExistingUser(session, realm, authenticationSession);
if (!linkingUser.getId().equals(authenticationSession.getAuthenticatedUser().getId())) {
return ErrorPage.error(session, authenticationSession,
return ErrorPage.error(session, authenticationSession, Response.Status.INTERNAL_SERVER_ERROR,
Messages.IDENTITY_PROVIDER_DIFFERENT_USER_MESSAGE,
authenticationSession.getAuthenticatedUser().getUsername(),
linkingUser.getUsername()

View file

@ -68,7 +68,7 @@ public abstract class AbstractIdpAuthenticator implements Authenticator {
BrokeredIdentityContext brokerContext = serializedCtx.deserialize(context.getSession(), authSession);
if (!brokerContext.getIdpConfig().isEnabled()) {
sendFailureChallenge(context, Errors.IDENTITY_PROVIDER_ERROR, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR, AuthenticationFlowError.IDENTITY_PROVIDER_ERROR);
sendFailureChallenge(context, Response.Status.BAD_REQUEST, Errors.IDENTITY_PROVIDER_ERROR, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR, AuthenticationFlowError.IDENTITY_PROVIDER_ERROR);
}
authenticateImpl(context, serializedCtx, brokerContext);
@ -85,7 +85,7 @@ public abstract class AbstractIdpAuthenticator implements Authenticator {
BrokeredIdentityContext brokerContext = serializedCtx.deserialize(context.getSession(), clientSession);
if (!brokerContext.getIdpConfig().isEnabled()) {
sendFailureChallenge(context, Errors.IDENTITY_PROVIDER_ERROR, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR, AuthenticationFlowError.IDENTITY_PROVIDER_ERROR);
sendFailureChallenge(context, Response.Status.BAD_REQUEST, Errors.IDENTITY_PROVIDER_ERROR, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR, AuthenticationFlowError.IDENTITY_PROVIDER_ERROR);
}
actionImpl(context, serializedCtx, brokerContext);
@ -94,12 +94,12 @@ public abstract class AbstractIdpAuthenticator implements Authenticator {
protected abstract void authenticateImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext serializedCtx, BrokeredIdentityContext brokerContext);
protected abstract void actionImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext serializedCtx, BrokeredIdentityContext brokerContext);
protected void sendFailureChallenge(AuthenticationFlowContext context, String eventError, String errorMessage, AuthenticationFlowError flowError) {
protected void sendFailureChallenge(AuthenticationFlowContext context, Response.Status status, String eventError, String errorMessage, AuthenticationFlowError flowError) {
context.getEvent().user(context.getUser())
.error(eventError);
Response challengeResponse = context.form()
.setError(errorMessage)
.createErrorPage();
.createErrorPage(status);
context.failureChallenge(flowError, challengeResponse);
}

View file

@ -102,7 +102,7 @@ public class IdpCreateUserIfUniqueAuthenticator extends AbstractIdpAuthenticator
Response challengeResponse = context.form()
.setError(Messages.FEDERATED_IDENTITY_EXISTS, duplication.getDuplicateAttributeName(), duplication.getDuplicateAttributeValue())
.createErrorPage();
.createErrorPage(Response.Status.CONFLICT);
context.challenge(challengeResponse);
if (context.getExecution().isRequired()) {

View file

@ -152,7 +152,7 @@ public class IdpEmailVerificationAuthenticator extends AbstractIdpAuthenticator
ServicesLogger.LOGGER.confirmBrokerEmailFailed(e);
Response challenge = context.form()
.setError(Messages.EMAIL_SENT_ERROR)
.createErrorPage();
.createErrorPage(Response.Status.INTERNAL_SERVER_ERROR);
context.failure(AuthenticationFlowError.INTERNAL_ERROR, challenge);
return;
}

View file

@ -122,7 +122,7 @@ public class SpnegoAuthenticator extends AbstractUsernameFormAuthenticator imple
.setAuthenticationSession(context.getAuthenticationSession())
.setStatus(Response.Status.UNAUTHORIZED)
.setResponseHeader(HttpHeaders.WWW_AUTHENTICATE, negotiateHeader)
.setError(Messages.KERBEROS_NOT_ENABLED).createErrorPage();
.setError(Messages.KERBEROS_NOT_ENABLED).createErrorPage(Response.Status.BAD_REQUEST);
} else {
return optionalChallengeRedirect(context, negotiateHeader);
}

View file

@ -111,7 +111,7 @@ public class ResetCredentialEmail implements Authenticator, AuthenticatorFactory
ServicesLogger.LOGGER.failedToSendPwdResetEmail(e);
Response challenge = context.form()
.setError(Messages.EMAIL_SENT_ERROR)
.createErrorPage();
.createErrorPage(Response.Status.INTERNAL_SERVER_ERROR);
context.failure(AuthenticationFlowError.INTERNAL_ERROR, challenge);
}
}

View file

@ -417,7 +417,7 @@ public abstract class AbstractOAuth2IdentityProvider<C extends OAuth2IdentityPro
}
event.event(EventType.LOGIN);
event.error(Errors.IDENTITY_PROVIDER_LOGIN_FAILURE);
return ErrorPage.error(session, null, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR);
return ErrorPage.error(session, null, Response.Status.BAD_GATEWAY, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR);
}
public SimpleHttp generateTokenRequest(String authorizationCode) {

View file

@ -110,14 +110,14 @@ public class OIDCIdentityProvider extends AbstractOAuth2IdentityProvider<OIDCIde
EventBuilder event = new EventBuilder(realm, session, clientConnection);
event.event(EventType.LOGOUT);
event.error(Errors.USER_SESSION_NOT_FOUND);
return ErrorPage.error(session, null, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR);
}
if (userSession.getState() != UserSessionModel.State.LOGGING_OUT) {
logger.error("usersession in different state");
EventBuilder event = new EventBuilder(realm, session, clientConnection);
event.event(EventType.LOGOUT);
event.error(Errors.USER_SESSION_NOT_FOUND);
return ErrorPage.error(session, null, Messages.SESSION_NOT_ACTIVE);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.SESSION_NOT_ACTIVE);
}
return AuthenticationManager.finishBrowserLogout(session, realm, userSession, uriInfo, clientConnection, headers);
}

View file

@ -192,18 +192,18 @@ public class SAMLEndpoint {
if (!checkSsl()) {
event.event(EventType.LOGIN);
event.error(Errors.SSL_REQUIRED);
return ErrorPage.error(session, null, Messages.HTTPS_REQUIRED);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.HTTPS_REQUIRED);
}
if (!realm.isEnabled()) {
event.event(EventType.LOGIN_ERROR);
event.error(Errors.REALM_DISABLED);
return ErrorPage.error(session, null, Messages.REALM_NOT_ENABLED);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.REALM_NOT_ENABLED);
}
if (samlRequest == null && samlResponse == null) {
event.event(EventType.LOGIN);
event.error(Errors.INVALID_REQUEST);
return ErrorPage.error(session, null, Messages.INVALID_REQUEST);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
return null;
@ -245,7 +245,7 @@ public class SAMLEndpoint {
event.event(EventType.IDENTITY_PROVIDER_RESPONSE);
event.detail(Details.REASON, "invalid_destination");
event.error(Errors.INVALID_SAML_RESPONSE);
return ErrorPage.error(session, null, Messages.INVALID_REQUEST);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
if (config.isValidateSignature()) {
try {
@ -254,7 +254,7 @@ public class SAMLEndpoint {
logger.error("validation failed", e);
event.event(EventType.IDENTITY_PROVIDER_RESPONSE);
event.error(Errors.INVALID_SIGNATURE);
return ErrorPage.error(session, null, Messages.INVALID_REQUESTER);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUESTER);
}
}
@ -267,7 +267,7 @@ public class SAMLEndpoint {
} else {
event.event(EventType.LOGIN);
event.error(Errors.INVALID_TOKEN);
return ErrorPage.error(session, null, Messages.INVALID_REQUEST);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
}
@ -359,7 +359,7 @@ public class SAMLEndpoint {
logger.error("The assertion is not encrypted, which is required.");
event.event(EventType.IDENTITY_PROVIDER_RESPONSE);
event.error(Errors.INVALID_SAML_RESPONSE);
return ErrorPage.error(session, null, Messages.INVALID_REQUESTER);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUESTER);
}
Element assertionElement;
@ -379,7 +379,7 @@ public class SAMLEndpoint {
logger.error("validation failed");
event.event(EventType.IDENTITY_PROVIDER_RESPONSE);
event.error(Errors.INVALID_SIGNATURE);
return ErrorPage.error(session, null, Messages.INVALID_REQUESTER);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUESTER);
}
AssertionType assertion = responseType.getAssertions().get(0).getAssertion();
@ -463,7 +463,7 @@ public class SAMLEndpoint {
event.event(EventType.IDENTITY_PROVIDER_RESPONSE);
event.detail(Details.REASON, "invalid_destination");
event.error(Errors.INVALID_SAML_RESPONSE);
return ErrorPage.error(session, null, Messages.INVALID_FEDERATED_IDENTITY_ACTION);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_FEDERATED_IDENTITY_ACTION);
}
if (config.isValidateSignature()) {
try {
@ -472,7 +472,7 @@ public class SAMLEndpoint {
logger.error("validation failed", e);
event.event(EventType.IDENTITY_PROVIDER_RESPONSE);
event.error(Errors.INVALID_SIGNATURE);
return ErrorPage.error(session, null, Messages.INVALID_FEDERATED_IDENTITY_ACTION);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_FEDERATED_IDENTITY_ACTION);
}
}
if (statusResponse instanceof ResponseType) {
@ -491,20 +491,20 @@ public class SAMLEndpoint {
logger.error("no valid user session");
event.event(EventType.LOGOUT);
event.error(Errors.USER_SESSION_NOT_FOUND);
return ErrorPage.error(session, null, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR);
}
UserSessionModel userSession = session.sessions().getUserSession(realm, relayState);
if (userSession == null) {
logger.error("no valid user session");
event.event(EventType.LOGOUT);
event.error(Errors.USER_SESSION_NOT_FOUND);
return ErrorPage.error(session, null, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR);
}
if (userSession.getState() != UserSessionModel.State.LOGGING_OUT) {
logger.error("usersession in different state");
event.event(EventType.LOGOUT);
event.error(Errors.USER_SESSION_NOT_FOUND);
return ErrorPage.error(session, null, Messages.SESSION_NOT_ACTIVE);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.SESSION_NOT_ACTIVE);
}
return AuthenticationManager.finishBrowserLogout(session, realm, userSession, uriInfo, clientConnection, headers);
}

View file

@ -284,7 +284,8 @@ public class FreeMarkerAccountProvider implements AccountProvider {
}
@Override
public AccountProvider setErrors(List<FormMessage> messages) {
public AccountProvider setErrors(Response.Status status, List<FormMessage> messages) {
this.status = status;
this.messageType = MessageType.ERROR;
this.messages = new ArrayList<>(messages);
return this;
@ -292,7 +293,8 @@ public class FreeMarkerAccountProvider implements AccountProvider {
@Override
public AccountProvider setError(String message, Object ... parameters) {
public AccountProvider setError(Response.Status status, String message, Object ... parameters) {
this.status = status;
setMessage(MessageType.ERROR, message, parameters);
return this;
}
@ -327,12 +329,6 @@ public class FreeMarkerAccountProvider implements AccountProvider {
return this;
}
@Override
public AccountProvider setStatus(Response.Status status) {
this.status = status;
return this;
}
@Override
public AccountProvider setReferrer(String[] referrer) {
this.referrer = referrer;

View file

@ -152,11 +152,6 @@ public class FreeMarkerLoginFormsProvider implements LoginFormsProvider {
@SuppressWarnings("incomplete-switch")
protected Response createResponse(LoginFormsPages page) {
if (status == null) {
status = Response.Status.OK;
}
Theme theme;
try {
theme = getTheme();
@ -206,20 +201,11 @@ public class FreeMarkerLoginFormsProvider implements LoginFormsProvider {
break;
}
if (status == null) {
status = Response.Status.OK;
}
return processTemplate(theme, Templates.getTemplate(page), locale);
}
@Override
public Response createForm(String form) {
if (status == null) {
status = Response.Status.OK;
}
Theme theme;
try {
theme = getTheme();
@ -394,7 +380,7 @@ public class FreeMarkerLoginFormsProvider implements LoginFormsProvider {
protected Response processTemplate(Theme theme, String templateName, Locale locale) {
try {
String result = freeMarker.processTemplate(attributes, templateName, theme);
Response.ResponseBuilder builder = Response.status(status).type(MediaType.TEXT_HTML_UTF_8_TYPE).language(locale).entity(result);
Response.ResponseBuilder builder = Response.status(status == null ? Response.Status.OK : status).type(MediaType.TEXT_HTML_UTF_8_TYPE).language(locale).entity(result);
BrowserSecurityHeaderSetup.headers(builder, realm);
for (Map.Entry<String, String> entry : httpResponseHeaders.entrySet()) {
builder.header(entry.getKey(), entry.getValue());
@ -462,10 +448,8 @@ public class FreeMarkerLoginFormsProvider implements LoginFormsProvider {
}
@Override
public Response createErrorPage() {
if (status == null) {
status = Response.Status.INTERNAL_SERVER_ERROR;
}
public Response createErrorPage(Response.Status status) {
this.status = status;
return createResponse(LoginFormsPages.ERROR);
}

View file

@ -154,14 +154,14 @@ public abstract class AuthorizationEndpointBase {
protected void checkSsl() {
if (!uriInfo.getBaseUri().getScheme().equals("https") && realm.getSslRequired().isRequired(clientConnection)) {
event.error(Errors.SSL_REQUIRED);
throw new ErrorPageException(session, Messages.HTTPS_REQUIRED);
throw new ErrorPageException(session, Response.Status.BAD_REQUEST, Messages.HTTPS_REQUIRED);
}
}
protected void checkRealm() {
if (!realm.isEnabled()) {
event.error(Errors.REALM_DISABLED);
throw new ErrorPageException(session, Messages.REALM_NOT_ENABLED);
throw new ErrorPageException(session, Response.Status.BAD_REQUEST, Messages.REALM_NOT_ENABLED);
}
}

View file

@ -153,7 +153,7 @@ public class AuthorizationEndpoint extends AuthorizationEndpointBase {
action = Action.REGISTER;
if (!realm.isRegistrationAllowed()) {
throw new ErrorPageException(session, authenticationSession, Messages.REGISTRATION_NOT_ALLOWED);
throw new ErrorPageException(session, authenticationSession, Response.Status.BAD_REQUEST, Messages.REGISTRATION_NOT_ALLOWED);
}
return this;
@ -164,7 +164,7 @@ public class AuthorizationEndpoint extends AuthorizationEndpointBase {
action = Action.FORGOT_CREDENTIALS;
if (!realm.isResetPasswordAllowed()) {
throw new ErrorPageException(session, authenticationSession, Messages.RESET_CREDENTIAL_NOT_ALLOWED);
throw new ErrorPageException(session, authenticationSession, Response.Status.BAD_REQUEST, Messages.RESET_CREDENTIAL_NOT_ALLOWED);
}
return this;
@ -173,7 +173,7 @@ public class AuthorizationEndpoint extends AuthorizationEndpointBase {
private void checkClient(String clientId) {
if (clientId == null) {
event.error(Errors.INVALID_REQUEST);
throw new ErrorPageException(session, authenticationSession, Messages.MISSING_PARAMETER, OIDCLoginProtocol.CLIENT_ID_PARAM);
throw new ErrorPageException(session, authenticationSession, Response.Status.BAD_REQUEST, Messages.MISSING_PARAMETER, OIDCLoginProtocol.CLIENT_ID_PARAM);
}
event.client(clientId);
@ -181,17 +181,17 @@ public class AuthorizationEndpoint extends AuthorizationEndpointBase {
client = realm.getClientByClientId(clientId);
if (client == null) {
event.error(Errors.CLIENT_NOT_FOUND);
throw new ErrorPageException(session, authenticationSession, Messages.CLIENT_NOT_FOUND);
throw new ErrorPageException(session, authenticationSession, Response.Status.BAD_REQUEST, Messages.CLIENT_NOT_FOUND);
}
if (!client.isEnabled()) {
event.error(Errors.CLIENT_DISABLED);
throw new ErrorPageException(session, authenticationSession, Messages.CLIENT_DISABLED);
throw new ErrorPageException(session, authenticationSession, Response.Status.BAD_REQUEST, Messages.CLIENT_DISABLED);
}
if (client.isBearerOnly()) {
event.error(Errors.NOT_ALLOWED);
throw new ErrorPageException(session, authenticationSession, Messages.BEARER_ONLY);
throw new ErrorPageException(session, authenticationSession, Response.Status.FORBIDDEN, Messages.BEARER_ONLY);
}
session.getContext().setClient(client);
@ -354,7 +354,7 @@ public class AuthorizationEndpoint extends AuthorizationEndpointBase {
redirectUri = RedirectUtils.verifyRedirectUri(uriInfo, redirectUriParam, realm, client, isOIDCRequest);
if (redirectUri == null) {
event.error(Errors.INVALID_REDIRECT_URI);
throw new ErrorPageException(session, authenticationSession, Messages.INVALID_PARAMETER, OIDCLoginProtocol.REDIRECT_URI_PARAM);
throw new ErrorPageException(session, authenticationSession, Response.Status.BAD_REQUEST, Messages.INVALID_PARAMETER, OIDCLoginProtocol.REDIRECT_URI_PARAM);
}
}

View file

@ -109,7 +109,7 @@ public class LogoutEndpoint {
event.event(EventType.LOGOUT);
event.detail(Details.REDIRECT_URI, redirect);
event.error(Errors.INVALID_REDIRECT_URI);
return ErrorPage.error(session, null, Messages.INVALID_REDIRECT_URI);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REDIRECT_URI);
}
redirect = validatedUri;
}
@ -122,7 +122,7 @@ public class LogoutEndpoint {
} catch (OAuthErrorException e) {
event.event(EventType.LOGOUT);
event.error(Errors.INVALID_TOKEN);
return ErrorPage.error(session, null, Messages.SESSION_NOT_ACTIVE);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.SESSION_NOT_ACTIVE);
}
}

View file

@ -29,6 +29,7 @@ import org.keycloak.services.ServicesLogger;
import org.keycloak.services.messages.Messages;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import java.io.InputStream;
/**
@ -63,7 +64,7 @@ public class AuthorizationEndpointRequestParserProcessor {
} catch (Exception e) {
ServicesLogger.LOGGER.invalidRequest(e);
event.error(Errors.INVALID_REQUEST);
throw new ErrorPageException(session, Messages.INVALID_REQUEST);
throw new ErrorPageException(session, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
}
}

View file

@ -173,7 +173,7 @@ public class SamlProtocol implements LoginProtocol {
URI redirect = builder.buildFromMap(params);
return Response.status(302).location(redirect).build();
} else {
return ErrorPage.error(session, authSession, translateErrorToIdpInitiatedErrorMessage(error));
return ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, translateErrorToIdpInitiatedErrorMessage(error));
}
} else {
SAML2ErrorResponseBuilder builder = new SAML2ErrorResponseBuilder().destination(authSession.getRedirectUri()).issuer(getResponseIssuer(realm)).status(translateErrorToSAMLStatus(error).get());
@ -196,7 +196,7 @@ public class SamlProtocol implements LoginProtocol {
Document document = builder.buildDocument();
return buildErrorResponse(authSession, binding, document);
} catch (Exception e) {
return ErrorPage.error(session, authSession, Messages.FAILED_TO_PROCESS_RESPONSE);
return ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, Messages.FAILED_TO_PROCESS_RESPONSE);
}
}
} finally {
@ -427,7 +427,7 @@ public class SamlProtocol implements LoginProtocol {
samlDocument = builder.buildDocument(samlModel);
} catch (Exception e) {
logger.error("failed", e);
return ErrorPage.error(session, null, Messages.FAILED_TO_PROCESS_RESPONSE);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.FAILED_TO_PROCESS_RESPONSE);
}
JaxrsSAML2BindingBuilder bindingBuilder = new JaxrsSAML2BindingBuilder();
@ -453,7 +453,7 @@ public class SamlProtocol implements LoginProtocol {
publicKey = SamlProtocolUtils.getEncryptionKey(client);
} catch (Exception e) {
logger.error("failed", e);
return ErrorPage.error(session, null, Messages.FAILED_TO_PROCESS_RESPONSE);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.FAILED_TO_PROCESS_RESPONSE);
}
bindingBuilder.encrypt(publicKey);
}
@ -461,7 +461,7 @@ public class SamlProtocol implements LoginProtocol {
return buildAuthenticatedResponse(clientSession, redirectUri, samlDocument, bindingBuilder);
} catch (Exception e) {
logger.error("failed", e);
return ErrorPage.error(session, null, Messages.FAILED_TO_PROCESS_RESPONSE);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.FAILED_TO_PROCESS_RESPONSE);
}
}
@ -568,7 +568,7 @@ public class SamlProtocol implements LoginProtocol {
String logoutBindingUri = userSession.getNote(SAML_LOGOUT_BINDING_URI);
if (logoutBindingUri == null) {
logger.error("Can't finish SAML logout as there is no logout binding set. Please configure the logout service url in the admin console for your client applications.");
return ErrorPage.error(session, null, Messages.FAILED_LOGOUT);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.FAILED_LOGOUT);
}
String logoutRelayState = userSession.getNote(SAML_LOGOUT_RELAY_STATE);

View file

@ -118,18 +118,18 @@ public class SamlService extends AuthorizationEndpointBase {
if (!checkSsl()) {
event.event(EventType.LOGIN);
event.error(Errors.SSL_REQUIRED);
return ErrorPage.error(session, null, Messages.HTTPS_REQUIRED);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.HTTPS_REQUIRED);
}
if (!realm.isEnabled()) {
event.event(EventType.LOGIN_ERROR);
event.error(Errors.REALM_DISABLED);
return ErrorPage.error(session, null, Messages.REALM_NOT_ENABLED);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.REALM_NOT_ENABLED);
}
if (samlRequest == null && samlResponse == null) {
event.event(EventType.LOGIN);
event.error(Errors.INVALID_TOKEN);
return ErrorPage.error(session, null, Messages.INVALID_REQUEST);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
return null;
@ -142,7 +142,7 @@ public class SamlService extends AuthorizationEndpointBase {
if (! (holder.getSamlObject() instanceof StatusResponseType)) {
event.detail(Details.REASON, "invalid_saml_response");
event.error(Errors.INVALID_SAML_RESPONSE);
return ErrorPage.error(session, null, Messages.INVALID_REQUEST);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
StatusResponseType statusResponse = (StatusResponseType) holder.getSamlObject();
@ -150,7 +150,7 @@ public class SamlService extends AuthorizationEndpointBase {
if (statusResponse.getDestination() != null && !uriInfo.getAbsolutePath().toString().equals(statusResponse.getDestination())) {
event.detail(Details.REASON, "invalid_destination");
event.error(Errors.INVALID_SAML_LOGOUT_RESPONSE);
return ErrorPage.error(session, null, Messages.INVALID_REQUEST);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
AuthenticationManager.AuthResult authResult = authManager.authenticateIdentityCookie(session, realm, false);
@ -158,7 +158,7 @@ public class SamlService extends AuthorizationEndpointBase {
logger.warn("Unknown saml response.");
event.event(EventType.LOGOUT);
event.error(Errors.INVALID_TOKEN);
return ErrorPage.error(session, null, Messages.INVALID_REQUEST);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
// assume this is a logout response
UserSessionModel userSession = authResult.getSession();
@ -167,7 +167,7 @@ public class SamlService extends AuthorizationEndpointBase {
logger.warn("UserSession is not tagged as logging out.");
event.event(EventType.LOGOUT);
event.error(Errors.INVALID_SAML_LOGOUT_RESPONSE);
return ErrorPage.error(session, null, Messages.INVALID_REQUEST);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
logger.debug("logout response");
Response response = authManager.browserLogout(session, realm, userSession, uriInfo, clientConnection, headers);
@ -180,7 +180,7 @@ public class SamlService extends AuthorizationEndpointBase {
if (documentHolder == null) {
event.event(EventType.LOGIN);
event.error(Errors.INVALID_TOKEN);
return ErrorPage.error(session, null, Messages.INVALID_REQUEST);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
SAML2Object samlObject = documentHolder.getSamlObject();
@ -188,7 +188,7 @@ public class SamlService extends AuthorizationEndpointBase {
if (! (samlObject instanceof RequestAbstractType)) {
event.event(EventType.LOGIN);
event.error(Errors.INVALID_SAML_AUTHN_REQUEST);
return ErrorPage.error(session, null, Messages.INVALID_REQUEST);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
RequestAbstractType requestAbstractType = (RequestAbstractType) samlObject;
@ -199,23 +199,23 @@ public class SamlService extends AuthorizationEndpointBase {
event.event(EventType.LOGIN);
event.client(issuer);
event.error(Errors.CLIENT_NOT_FOUND);
return ErrorPage.error(session, null, Messages.UNKNOWN_LOGIN_REQUESTER);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.UNKNOWN_LOGIN_REQUESTER);
}
if (!client.isEnabled()) {
event.event(EventType.LOGIN);
event.error(Errors.CLIENT_DISABLED);
return ErrorPage.error(session, null, Messages.LOGIN_REQUESTER_NOT_ENABLED);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.LOGIN_REQUESTER_NOT_ENABLED);
}
if (client.isBearerOnly()) {
event.event(EventType.LOGIN);
event.error(Errors.NOT_ALLOWED);
return ErrorPage.error(session, null, Messages.BEARER_ONLY);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.BEARER_ONLY);
}
if (!client.isStandardFlowEnabled()) {
event.event(EventType.LOGIN);
event.error(Errors.NOT_ALLOWED);
return ErrorPage.error(session, null, Messages.STANDARD_FLOW_DISABLED);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.STANDARD_FLOW_DISABLED);
}
session.getContext().setClient(client);
@ -226,7 +226,7 @@ public class SamlService extends AuthorizationEndpointBase {
SamlService.logger.error("request validation failed", e);
event.event(EventType.LOGIN);
event.error(Errors.INVALID_SIGNATURE);
return ErrorPage.error(session, null, Messages.INVALID_REQUESTER);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUESTER);
}
logger.debug("verified request");
if (samlObject instanceof AuthnRequestType) {
@ -244,7 +244,7 @@ public class SamlService extends AuthorizationEndpointBase {
} else {
event.event(EventType.LOGIN);
event.error(Errors.INVALID_TOKEN);
return ErrorPage.error(session, null, Messages.INVALID_REQUEST);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
}
@ -260,12 +260,12 @@ public class SamlService extends AuthorizationEndpointBase {
if (requestAbstractType.getDestination() == null && samlClient.requiresClientSignature()) {
event.detail(Details.REASON, "invalid_destination");
event.error(Errors.INVALID_SAML_AUTHN_REQUEST);
return ErrorPage.error(session, null, Messages.INVALID_REQUEST);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
if (! isValidDestination(requestAbstractType.getDestination())) {
event.detail(Details.REASON, "invalid_destination");
event.error(Errors.INVALID_SAML_AUTHN_REQUEST);
return ErrorPage.error(session, null, Messages.INVALID_REQUEST);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
String bindingType = getBindingType(requestAbstractType);
if (samlClient.forcePostBinding())
@ -288,7 +288,7 @@ public class SamlService extends AuthorizationEndpointBase {
if (redirect == null) {
event.error(Errors.INVALID_REDIRECT_URI);
return ErrorPage.error(session, null, Messages.INVALID_REDIRECT_URI);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REDIRECT_URI);
}
AuthorizationEndpointChecks checks = getOrCreateAuthenticationSession(client, relayState);
@ -316,7 +316,7 @@ public class SamlService extends AuthorizationEndpointBase {
} else {
event.detail(Details.REASON, "unsupported_nameid_format");
event.error(Errors.INVALID_SAML_AUTHN_REQUEST);
return ErrorPage.error(session, null, Messages.UNSUPPORTED_NAME_ID_FORMAT);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.UNSUPPORTED_NAME_ID_FORMAT);
}
}
@ -367,12 +367,12 @@ public class SamlService extends AuthorizationEndpointBase {
if (logoutRequest.getDestination() == null && samlClient.requiresClientSignature()) {
event.detail(Details.REASON, "invalid_destination");
event.error(Errors.INVALID_SAML_LOGOUT_REQUEST);
return ErrorPage.error(session, null, Messages.INVALID_REQUEST);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
if (! isValidDestination(logoutRequest.getDestination())) {
event.detail(Details.REASON, "invalid_destination");
event.error(Errors.INVALID_SAML_LOGOUT_REQUEST);
return ErrorPage.error(session, null, Messages.INVALID_REQUEST);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
// authenticate identity cookie, but ignore an access token timeout as we're logging out anyways.
@ -620,16 +620,16 @@ public class SamlService extends AuthorizationEndpointBase {
}
if (client == null) {
event.error(Errors.CLIENT_NOT_FOUND);
return ErrorPage.error(session, null, Messages.CLIENT_NOT_FOUND);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.CLIENT_NOT_FOUND);
}
if (!client.isEnabled()) {
event.error(Errors.CLIENT_DISABLED);
return ErrorPage.error(session, null, Messages.CLIENT_DISABLED);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.CLIENT_DISABLED);
}
if (client.getManagementUrl() == null && client.getAttribute(SamlProtocol.SAML_ASSERTION_CONSUMER_URL_POST_ATTRIBUTE) == null && client.getAttribute(SamlProtocol.SAML_ASSERTION_CONSUMER_URL_REDIRECT_ATTRIBUTE) == null) {
logger.error("SAML assertion consumer url not set up");
event.error(Errors.INVALID_REDIRECT_URI);
return ErrorPage.error(session, null, Messages.INVALID_REDIRECT_URI);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REDIRECT_URI);
}
AuthenticationSessionModel authSession = getOrCreateLoginSessionForIdpInitiatedSso(this.session, this.realm, client, relayState);

View file

@ -27,8 +27,8 @@ import javax.ws.rs.core.Response;
*/
public class ErrorPage {
public static Response error(KeycloakSession session, AuthenticationSessionModel authenticationSession, String message, Object... parameters) {
return session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authenticationSession).setError(message, parameters).createErrorPage();
public static Response error(KeycloakSession session, AuthenticationSessionModel authenticationSession, Response.Status status, String message, Object... parameters) {
return session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authenticationSession).setError(message, parameters).createErrorPage(status);
}

View file

@ -29,20 +29,23 @@ import javax.ws.rs.core.Response;
public class ErrorPageException extends WebApplicationException {
private final KeycloakSession session;
private Response.Status status;
private final String errorMessage;
private final Object[] parameters;
private final AuthenticationSessionModel authSession;
public ErrorPageException(KeycloakSession session, String errorMessage, Object... parameters) {
public ErrorPageException(KeycloakSession session, Response.Status status, String errorMessage, Object... parameters) {
this.session = session;
this.status = status;
this.errorMessage = errorMessage;
this.parameters = parameters;
this.authSession = null;
}
public ErrorPageException(KeycloakSession session, AuthenticationSessionModel authSession, String errorMessage, Object... parameters) {
public ErrorPageException(KeycloakSession session, AuthenticationSessionModel authSession, Response.Status status, String errorMessage, Object... parameters) {
this.session = session;
this.status = status;
this.errorMessage = errorMessage;
this.parameters = parameters;
this.authSession = authSession;
@ -52,7 +55,7 @@ public class ErrorPageException extends WebApplicationException {
@Override
public Response getResponse() {
return ErrorPage.error(session, authSession, errorMessage, parameters);
return ErrorPage.error(session, authSession, status, errorMessage, parameters);
}
}

View file

@ -156,14 +156,14 @@ public class IdentityBrokerService implements IdentityProvider.AuthenticationCal
private void checkRealm() {
if (!realmModel.isEnabled()) {
event.error(Errors.REALM_DISABLED);
throw new ErrorPageException(session, Messages.REALM_NOT_ENABLED);
throw new ErrorPageException(session, Response.Status.BAD_REQUEST, Messages.REALM_NOT_ENABLED);
}
}
private ClientModel checkClient(String clientId) {
if (clientId == null) {
event.error(Errors.INVALID_REQUEST);
throw new ErrorPageException(session, Messages.MISSING_PARAMETER, OIDCLoginProtocol.CLIENT_ID_PARAM);
throw new ErrorPageException(session, Response.Status.BAD_REQUEST, Messages.MISSING_PARAMETER, OIDCLoginProtocol.CLIENT_ID_PARAM);
}
event.client(clientId);
@ -171,12 +171,12 @@ public class IdentityBrokerService implements IdentityProvider.AuthenticationCal
ClientModel client = realmModel.getClientByClientId(clientId);
if (client == null) {
event.error(Errors.CLIENT_NOT_FOUND);
throw new ErrorPageException(session, Messages.INVALID_REQUEST);
throw new ErrorPageException(session, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
if (!client.isEnabled()) {
event.error(Errors.CLIENT_DISABLED);
throw new ErrorPageException(session, Messages.INVALID_REQUEST);
throw new ErrorPageException(session, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
return client;
@ -210,14 +210,14 @@ public class IdentityBrokerService implements IdentityProvider.AuthenticationCal
redirectUri = RedirectUtils.verifyRedirectUri(uriInfo, redirectUri, realmModel, client);
if (redirectUri == null) {
event.error(Errors.INVALID_REDIRECT_URI);
throw new ErrorPageException(session, Messages.INVALID_REQUEST);
throw new ErrorPageException(session, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
event.detail(Details.REDIRECT_URI, redirectUri);
if (nonce == null || hash == null) {
event.error(Errors.INVALID_REDIRECT_URI);
throw new ErrorPageException(session, Messages.INVALID_REQUEST);
throw new ErrorPageException(session, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
@ -245,7 +245,7 @@ public class IdentityBrokerService implements IdentityProvider.AuthenticationCal
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new ErrorPageException(session, Messages.UNEXPECTED_ERROR_HANDLING_REQUEST);
throw new ErrorPageException(session, Response.Status.INTERNAL_SERVER_ERROR, Messages.UNEXPECTED_ERROR_HANDLING_REQUEST);
}
String input = nonce + cookieResult.getSession().getId() + clientId + providerId;
byte[] check = md.digest(input.getBytes(StandardCharsets.UTF_8));
@ -257,7 +257,7 @@ public class IdentityBrokerService implements IdentityProvider.AuthenticationCal
}
if (clientSession == null) {
event.error(Errors.INVALID_TOKEN);
throw new ErrorPageException(session, Messages.INVALID_REQUEST);
throw new ErrorPageException(session, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
event.detail(Details.IDENTITY_PROVIDER, providerId);
@ -371,13 +371,12 @@ public class IdentityBrokerService implements IdentityProvider.AuthenticationCal
return response;
}
} catch (IdentityBrokerException e) {
e.printStackTrace();
return redirectToErrorPage(Messages.COULD_NOT_SEND_AUTHENTICATION_REQUEST, e, providerId);
return redirectToErrorPage(Response.Status.BAD_GATEWAY, Messages.COULD_NOT_SEND_AUTHENTICATION_REQUEST, e, providerId);
} catch (Exception e) {
return redirectToErrorPage(Messages.UNEXPECTED_ERROR_HANDLING_REQUEST, e, providerId);
return redirectToErrorPage(Response.Status.INTERNAL_SERVER_ERROR, Messages.UNEXPECTED_ERROR_HANDLING_REQUEST, e, providerId);
}
return redirectToErrorPage(Messages.COULD_NOT_PROCEED_WITH_AUTHENTICATION_REQUEST);
return redirectToErrorPage(Response.Status.INTERNAL_SERVER_ERROR, Messages.COULD_NOT_PROCEED_WITH_AUTHENTICATION_REQUEST);
}
@Path("{provider_id}/endpoint")
@ -458,9 +457,9 @@ public class IdentityBrokerService implements IdentityProvider.AuthenticationCal
return badRequest("Invalid token.");
} catch (IdentityBrokerException e) {
return redirectToErrorPage(Messages.COULD_NOT_OBTAIN_TOKEN, e, providerId);
return redirectToErrorPage(Response.Status.BAD_GATEWAY, Messages.COULD_NOT_OBTAIN_TOKEN, e, providerId);
} catch (Exception e) {
return redirectToErrorPage(Messages.UNEXPECTED_ERROR_RETRIEVING_TOKEN, e, providerId);
return redirectToErrorPage(Response.Status.BAD_GATEWAY, Messages.UNEXPECTED_ERROR_RETRIEVING_TOKEN, e, providerId);
}
}
@ -562,12 +561,12 @@ public class IdentityBrokerService implements IdentityProvider.AuthenticationCal
public Response validateUser(AuthenticationSessionModel authSession, UserModel user, RealmModel realm) {
if (!user.isEnabled()) {
event.error(Errors.USER_DISABLED);
return ErrorPage.error(session, authSession, Messages.ACCOUNT_DISABLED);
return ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, Messages.ACCOUNT_DISABLED);
}
if (realm.isBruteForceProtected()) {
if (session.getProvider(BruteForceProtector.class).isTemporarilyDisabled(session, realm, user)) {
event.error(Errors.USER_TEMPORARILY_DISABLED);
return ErrorPage.error(session, authSession, Messages.ACCOUNT_DISABLED);
return ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, Messages.ACCOUNT_DISABLED);
}
}
return null;
@ -847,7 +846,7 @@ public class IdentityBrokerService implements IdentityProvider.AuthenticationCal
authSession.removeAuthNote(LINKING_IDENTITY_PROVIDER);
return true;
} else {
throw new ErrorPageException(session, Messages.BROKER_LINKING_SESSION_EXPIRED);
throw new ErrorPageException(session, Response.Status.BAD_REQUEST, Messages.BROKER_LINKING_SESSION_EXPIRED);
}
}
@ -964,7 +963,7 @@ public class IdentityBrokerService implements IdentityProvider.AuthenticationCal
private ParsedCodeContext parseSessionCode(String code, String clientId) {
if (code == null || clientId == null) {
logger.debugf("Invalid request. Authorization code or clientId was null. Code=" + code + ", clientId=" + clientId);
Response staleCodeError = redirectToErrorPage(Messages.INVALID_REQUEST);
Response staleCodeError = redirectToErrorPage(Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
return ParsedCodeContext.response(staleCodeError);
}
@ -1015,7 +1014,7 @@ public class IdentityBrokerService implements IdentityProvider.AuthenticationCal
if (! oClient.isPresent()) {
event.error(Errors.CLIENT_NOT_FOUND);
return ParsedCodeContext.response(redirectToErrorPage(Messages.CLIENT_NOT_FOUND));
return ParsedCodeContext.response(redirectToErrorPage(Response.Status.BAD_REQUEST, Messages.CLIENT_NOT_FOUND));
}
LoginProtocolFactory factory = (LoginProtocolFactory) session.getKeycloakSessionFactory().getProviderFactory(LoginProtocol.class, SamlProtocol.LOGIN_PROTOCOL);
@ -1062,11 +1061,11 @@ public class IdentityBrokerService implements IdentityProvider.AuthenticationCal
return redirectToErrorPage(authSession, message, null, parameters);
}
private Response redirectToErrorPage(String message, Object ... parameters) {
return redirectToErrorPage(null, message, null, parameters);
private Response redirectToErrorPage(Response.Status status, String message, Object ... parameters) {
return redirectToErrorPage(null, status, message, null, parameters);
}
private Response redirectToErrorPage(AuthenticationSessionModel authSession, String message, Throwable throwable, Object ... parameters) {
private Response redirectToErrorPage(AuthenticationSessionModel authSession, Response.Status status, String message, Throwable throwable, Object ... parameters) {
if (message == null) {
message = Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR;
}
@ -1078,7 +1077,7 @@ public class IdentityBrokerService implements IdentityProvider.AuthenticationCal
return webEx.getResponse();
}
return ErrorPage.error(this.session, authSession, message, parameters);
return ErrorPage.error(this.session, authSession, status, message, parameters);
}
private Response redirectToAccountErrorPage(AuthenticationSessionModel authSession, String message, Object ... parameters) {

View file

@ -340,7 +340,7 @@ public class LoginActionsService {
if (!realm.isResetPasswordAllowed()) {
event.event(EventType.RESET_PASSWORD);
event.error(Errors.NOT_ALLOWED);
return ErrorPage.error(session, authSession, Messages.RESET_CREDENTIAL_NOT_ALLOWED);
return ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, Messages.RESET_CREDENTIAL_NOT_ALLOWED);
}
authSession = createAuthenticationSessionForClient();
@ -384,7 +384,7 @@ public class LoginActionsService {
if (!realm.isResetPasswordAllowed()) {
event.error(Errors.NOT_ALLOWED);
return ErrorPage.error(session, authSession, Messages.RESET_CREDENTIAL_NOT_ALLOWED);
return ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, Messages.RESET_CREDENTIAL_NOT_ALLOWED);
}
@ -553,7 +553,7 @@ public class LoginActionsService {
} else if (RESET_CREDENTIALS_PATH.equals(flowPath)) {
return processResetCredentials(false, null, authSession, errorMessage);
} else {
return ErrorPage.error(session, authSession, errorMessage == null ? Messages.INVALID_REQUEST : errorMessage);
return ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, errorMessage == null ? Messages.INVALID_REQUEST : errorMessage);
}
}
@ -577,7 +577,7 @@ public class LoginActionsService {
event
.detail(Details.REASON, ex == null ? "<unknown>" : ex.getMessage())
.error(eventError == null ? Errors.INVALID_CODE : eventError);
return ErrorPage.error(session, null, errorMessage == null ? Messages.INVALID_CODE : errorMessage);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, errorMessage == null ? Messages.INVALID_CODE : errorMessage);
}
protected Response processResetCredentials(boolean actionRequest, String execution, AuthenticationSessionModel authSession, String errorMessage) {
@ -626,7 +626,7 @@ public class LoginActionsService {
event.event(EventType.REGISTER);
if (!realm.isRegistrationAllowed()) {
event.error(Errors.REGISTRATION_DISABLED);
return ErrorPage.error(session, null, Messages.REGISTRATION_NOT_ALLOWED);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.REGISTRATION_NOT_ALLOWED);
}
SessionCodeChecks checks = checksForCode(code, execution, clientId, REGISTRATION_PATH);
@ -692,7 +692,7 @@ public class LoginActionsService {
SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(authSession, noteKey);
if (serializedCtx == null) {
ServicesLogger.LOGGER.notFoundSerializedCtxInClientSession(noteKey);
throw new WebApplicationException(ErrorPage.error(session, authSession, "Not found serialized context in authenticationSession."));
throw new WebApplicationException(ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, "Not found serialized context in authenticationSession."));
}
BrokeredIdentityContext brokerContext = serializedCtx.deserialize(session, authSession);
final String identityProviderAlias = brokerContext.getIdpConfig().getAlias();
@ -700,12 +700,12 @@ public class LoginActionsService {
String flowId = firstBrokerLogin ? brokerContext.getIdpConfig().getFirstBrokerLoginFlowId() : brokerContext.getIdpConfig().getPostBrokerLoginFlowId();
if (flowId == null) {
ServicesLogger.LOGGER.flowNotConfigForIDP(identityProviderAlias);
throw new WebApplicationException(ErrorPage.error(session, authSession, "Flow not configured for identity provider"));
throw new WebApplicationException(ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, "Flow not configured for identity provider"));
}
AuthenticationFlowModel brokerLoginFlow = realm.getAuthenticationFlowById(flowId);
if (brokerLoginFlow == null) {
ServicesLogger.LOGGER.flowNotFoundForIDP(flowId, identityProviderAlias);
throw new WebApplicationException(ErrorPage.error(session, authSession, "Flow not found for identity provider"));
throw new WebApplicationException(ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, "Flow not found for identity provider"));
}
event.detail(Details.IDENTITY_PROVIDER, identityProviderAlias)
@ -886,7 +886,7 @@ public class LoginActionsService {
if (factory == null) {
ServicesLogger.LOGGER.actionProviderNull();
event.error(Errors.INVALID_CODE);
throw new WebApplicationException(ErrorPage.error(session, authSession, Messages.INVALID_CODE));
throw new WebApplicationException(ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, Messages.INVALID_CODE));
}
RequiredActionProvider provider = factory.create(session);

View file

@ -123,12 +123,12 @@ public class SessionCodeChecks {
// Basic realm checks
if (!checkSsl()) {
event.error(Errors.SSL_REQUIRED);
response = ErrorPage.error(session, null, Messages.HTTPS_REQUIRED);
response = ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.HTTPS_REQUIRED);
return null;
}
if (!realm.isEnabled()) {
event.error(Errors.REALM_DISABLED);
response = ErrorPage.error(session, null, Messages.REALM_NOT_ENABLED);
response = ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.REALM_NOT_ENABLED);
return null;
}
@ -190,7 +190,7 @@ public class SessionCodeChecks {
ClientModel client = authSession.getClient();
if (client == null) {
event.error(Errors.CLIENT_NOT_FOUND);
response = ErrorPage.error(session, authSession, Messages.UNKNOWN_LOGIN_REQUESTER);
response = ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, Messages.UNKNOWN_LOGIN_REQUESTER);
clientCode.removeExpiredClientSession();
return false;
}
@ -200,7 +200,7 @@ public class SessionCodeChecks {
if (!client.isEnabled()) {
event.error(Errors.CLIENT_DISABLED);
response = ErrorPage.error(session,authSession, Messages.LOGIN_REQUESTER_NOT_ENABLED);
response = ErrorPage.error(session,authSession, Response.Status.BAD_REQUEST, Messages.LOGIN_REQUESTER_NOT_ENABLED);
clientCode.removeExpiredClientSession();
return false;
}
@ -285,7 +285,7 @@ public class SessionCodeChecks {
return false;
} else {
logger.errorf("Bad action. Expected action '%s', current action '%s'", expectedAction, authSession.getAction());
response = ErrorPage.error(session, authSession, Messages.EXPIRED_CODE);
response = ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, Messages.EXPIRED_CODE);
return false;
}
}
@ -370,7 +370,7 @@ public class SessionCodeChecks {
} else {
// Finally need to show error as all the fallbacks failed
event.error(Errors.INVALID_CODE);
return ErrorPage.error(session, authSession, Messages.INVALID_CODE);
return ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, Messages.INVALID_CODE);
}
}

View file

@ -173,7 +173,7 @@ public class AccountFormService extends AbstractSecuredLocalService {
try {
auth.require(AccountRoles.MANAGE_ACCOUNT);
} catch (ForbiddenException e) {
return session.getProvider(LoginFormsProvider.class).setError(Messages.NO_ACCESS).createErrorPage();
return session.getProvider(LoginFormsProvider.class).setError(Messages.NO_ACCESS).createErrorPage(Response.Status.FORBIDDEN);
}
setReferrerOnPage();
@ -185,7 +185,7 @@ public class AccountFormService extends AbstractSecuredLocalService {
if (forwardedError != null) {
try {
FormMessage errorMessage = JsonSerialization.readValue(forwardedError, FormMessage.class);
account.setError(errorMessage.getMessage(), errorMessage.getParameters());
account.setError(Response.Status.INTERNAL_SERVER_ERROR, errorMessage.getMessage(), errorMessage.getParameters());
authSession.removeAuthNote(ACCOUNT_MGMT_FORWARDED_ERROR_NOTE);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
@ -318,7 +318,7 @@ public class AccountFormService extends AbstractSecuredLocalService {
List<FormMessage> errors = Validation.validateUpdateProfileForm(realm.isEditUsernameAllowed(), formData);
if (errors != null && !errors.isEmpty()) {
setReferrerOnPage();
return account.setErrors(errors).setProfileFormData(formData).createResponse(AccountPages.ACCOUNT);
return account.setErrors(Response.Status.BAD_REQUEST, errors).setProfileFormData(formData).createResponse(AccountPages.ACCOUNT);
}
try {
@ -336,10 +336,10 @@ public class AccountFormService extends AbstractSecuredLocalService {
return account.setSuccess(Messages.ACCOUNT_UPDATED).createResponse(AccountPages.ACCOUNT);
} catch (ReadOnlyException roe) {
setReferrerOnPage();
return account.setError(Messages.READ_ONLY_USER).setProfileFormData(formData).createResponse(AccountPages.ACCOUNT);
return account.setError(Response.Status.BAD_REQUEST, Messages.READ_ONLY_USER).setProfileFormData(formData).createResponse(AccountPages.ACCOUNT);
} catch (ModelDuplicateException mde) {
setReferrerOnPage();
return account.setError(mde.getMessage()).setProfileFormData(formData).createResponse(AccountPages.ACCOUNT);
return account.setError(Response.Status.CONFLICT, mde.getMessage()).setProfileFormData(formData).createResponse(AccountPages.ACCOUNT);
}
}
@ -408,11 +408,11 @@ public class AccountFormService extends AbstractSecuredLocalService {
String clientId = formData.getFirst("clientId");
if (clientId == null) {
return account.setError(Messages.CLIENT_NOT_FOUND).createResponse(AccountPages.APPLICATIONS);
return account.setError(Response.Status.BAD_REQUEST, Messages.CLIENT_NOT_FOUND).createResponse(AccountPages.APPLICATIONS);
}
ClientModel client = realm.getClientById(clientId);
if (client == null) {
return account.setError(Messages.CLIENT_NOT_FOUND).createResponse(AccountPages.APPLICATIONS);
return account.setError(Response.Status.BAD_REQUEST, Messages.CLIENT_NOT_FOUND).createResponse(AccountPages.APPLICATIONS);
}
// Revoke grant in UserModel
@ -472,10 +472,10 @@ public class AccountFormService extends AbstractSecuredLocalService {
if (Validation.isBlank(totp)) {
setReferrerOnPage();
return account.setError(Messages.MISSING_TOTP).createResponse(AccountPages.TOTP);
return account.setError(Response.Status.BAD_REQUEST, Messages.MISSING_TOTP).createResponse(AccountPages.TOTP);
} else if (!CredentialValidation.validOTP(realm, totp, totpSecret)) {
setReferrerOnPage();
return account.setError(Messages.INVALID_TOTP).createResponse(AccountPages.TOTP);
return account.setError(Response.Status.BAD_REQUEST, Messages.INVALID_TOTP).createResponse(AccountPages.TOTP);
}
UserCredentialModel credentials = new UserCredentialModel();
@ -535,27 +535,27 @@ public class AccountFormService extends AbstractSecuredLocalService {
if (Validation.isBlank(password)) {
setReferrerOnPage();
errorEvent.error(Errors.PASSWORD_MISSING);
return account.setError(Messages.MISSING_PASSWORD).createResponse(AccountPages.PASSWORD);
return account.setError(Response.Status.BAD_REQUEST, Messages.MISSING_PASSWORD).createResponse(AccountPages.PASSWORD);
}
UserCredentialModel cred = UserCredentialModel.password(password);
if (!session.userCredentialManager().isValid(realm, user, cred)) {
setReferrerOnPage();
errorEvent.error(Errors.INVALID_USER_CREDENTIALS);
return account.setError(Messages.INVALID_PASSWORD_EXISTING).createResponse(AccountPages.PASSWORD);
return account.setError(Response.Status.BAD_REQUEST, Messages.INVALID_PASSWORD_EXISTING).createResponse(AccountPages.PASSWORD);
}
}
if (Validation.isBlank(passwordNew)) {
setReferrerOnPage();
errorEvent.error(Errors.PASSWORD_MISSING);
return account.setError(Messages.MISSING_PASSWORD).createResponse(AccountPages.PASSWORD);
return account.setError(Response.Status.BAD_REQUEST, Messages.MISSING_PASSWORD).createResponse(AccountPages.PASSWORD);
}
if (!passwordNew.equals(passwordConfirm)) {
setReferrerOnPage();
errorEvent.error(Errors.PASSWORD_CONFIRM_ERROR);
return account.setError(Messages.INVALID_PASSWORD_CONFIRM).createResponse(AccountPages.PASSWORD);
return account.setError(Response.Status.BAD_REQUEST, Messages.INVALID_PASSWORD_CONFIRM).createResponse(AccountPages.PASSWORD);
}
try {
@ -563,17 +563,17 @@ public class AccountFormService extends AbstractSecuredLocalService {
} catch (ReadOnlyException mre) {
setReferrerOnPage();
errorEvent.error(Errors.NOT_ALLOWED);
return account.setError(Messages.READ_ONLY_PASSWORD).createResponse(AccountPages.PASSWORD);
return account.setError(Response.Status.BAD_REQUEST, Messages.READ_ONLY_PASSWORD).createResponse(AccountPages.PASSWORD);
} catch (ModelException me) {
ServicesLogger.LOGGER.failedToUpdatePassword(me);
setReferrerOnPage();
errorEvent.detail(Details.REASON, me.getMessage()).error(Errors.PASSWORD_REJECTED);
return account.setError(me.getMessage(), me.getParameters()).createResponse(AccountPages.PASSWORD);
return account.setError(Response.Status.INTERNAL_SERVER_ERROR, me.getMessage(), me.getParameters()).createResponse(AccountPages.PASSWORD);
} catch (Exception ape) {
ServicesLogger.LOGGER.failedToUpdatePassword(ape);
setReferrerOnPage();
errorEvent.detail(Details.REASON, ape.getMessage()).error(Errors.PASSWORD_REJECTED);
return account.setError(ape.getMessage()).createResponse(AccountPages.PASSWORD);
return account.setError(Response.Status.INTERNAL_SERVER_ERROR, ape.getMessage()).createResponse(AccountPages.PASSWORD);
}
List<UserSessionModel> sessions = session.sessions().getUserSessions(realm, user);
@ -606,12 +606,12 @@ public class AccountFormService extends AbstractSecuredLocalService {
if (Validation.isEmpty(providerId)) {
setReferrerOnPage();
return account.setError(Messages.MISSING_IDENTITY_PROVIDER).createResponse(AccountPages.FEDERATED_IDENTITY);
return account.setError(Response.Status.BAD_REQUEST, Messages.MISSING_IDENTITY_PROVIDER).createResponse(AccountPages.FEDERATED_IDENTITY);
}
AccountSocialAction accountSocialAction = AccountSocialAction.getAction(action);
if (accountSocialAction == null) {
setReferrerOnPage();
return account.setError(Messages.INVALID_FEDERATED_IDENTITY_ACTION).createResponse(AccountPages.FEDERATED_IDENTITY);
return account.setError(Response.Status.BAD_REQUEST, Messages.INVALID_FEDERATED_IDENTITY_ACTION).createResponse(AccountPages.FEDERATED_IDENTITY);
}
boolean hasProvider = false;
@ -624,12 +624,12 @@ public class AccountFormService extends AbstractSecuredLocalService {
if (!hasProvider) {
setReferrerOnPage();
return account.setError(Messages.IDENTITY_PROVIDER_NOT_FOUND).createResponse(AccountPages.FEDERATED_IDENTITY);
return account.setError(Response.Status.BAD_REQUEST, Messages.IDENTITY_PROVIDER_NOT_FOUND).createResponse(AccountPages.FEDERATED_IDENTITY);
}
if (!user.isEnabled()) {
setReferrerOnPage();
return account.setError(Messages.ACCOUNT_DISABLED).createResponse(AccountPages.FEDERATED_IDENTITY);
return account.setError(Response.Status.BAD_REQUEST, Messages.ACCOUNT_DISABLED).createResponse(AccountPages.FEDERATED_IDENTITY);
}
switch (accountSocialAction) {
@ -653,7 +653,7 @@ public class AccountFormService extends AbstractSecuredLocalService {
.build();
} catch (Exception spe) {
setReferrerOnPage();
return account.setError(Messages.IDENTITY_PROVIDER_REDIRECT_ERROR).createResponse(AccountPages.FEDERATED_IDENTITY);
return account.setError(Response.Status.INTERNAL_SERVER_ERROR, Messages.IDENTITY_PROVIDER_REDIRECT_ERROR).createResponse(AccountPages.FEDERATED_IDENTITY);
}
case REMOVE:
FederatedIdentityModel link = session.users().getFederatedIdentity(user, providerId, realm);
@ -675,11 +675,11 @@ public class AccountFormService extends AbstractSecuredLocalService {
return account.setSuccess(Messages.IDENTITY_PROVIDER_REMOVED).createResponse(AccountPages.FEDERATED_IDENTITY);
} else {
setReferrerOnPage();
return account.setError(Messages.FEDERATED_IDENTITY_REMOVING_LAST_PROVIDER).createResponse(AccountPages.FEDERATED_IDENTITY);
return account.setError(Response.Status.BAD_REQUEST, Messages.FEDERATED_IDENTITY_REMOVING_LAST_PROVIDER).createResponse(AccountPages.FEDERATED_IDENTITY);
}
} else {
setReferrerOnPage();
return account.setError(Messages.FEDERATED_IDENTITY_NOT_ACTIVE).createResponse(AccountPages.FEDERATED_IDENTITY);
return account.setError(Response.Status.BAD_REQUEST, Messages.FEDERATED_IDENTITY_NOT_ACTIVE).createResponse(AccountPages.FEDERATED_IDENTITY);
}
default:
throw new IllegalArgumentException();

View file

@ -238,7 +238,7 @@ public class TwitterIdentityProvider extends AbstractIdentityProvider<OAuth2Iden
} catch (Exception e) {
logger.error("Could get user profile from twitter.", e);
sendErrorEvent();
return ErrorPage.error(session, authSession, Messages.UNEXPECTED_ERROR_HANDLING_RESPONSE);
return ErrorPage.error(session, authSession, Response.Status.BAD_GATEWAY, Messages.UNEXPECTED_ERROR_HANDLING_RESPONSE);
}
}

View file

@ -144,7 +144,7 @@ public class BasicSamlTest extends AbstractSamlTest {
try (CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new RedirectStrategyWithSwitchableFollowRedirect()).build();
CloseableHttpResponse response = client.execute(post)) {
assertThat(response, statusCodeIsHC(Response.Status.INTERNAL_SERVER_ERROR));
assertThat(response, statusCodeIsHC(Status.BAD_REQUEST));
}
}
@ -161,7 +161,7 @@ public class BasicSamlTest extends AbstractSamlTest {
@Test
public void testWrongPortInDestination() throws Exception {
testWithOverriddenPort(123, Response.Status.INTERNAL_SERVER_ERROR, containsString("Invalid Request"));
testWithOverriddenPort(123, Status.BAD_REQUEST, containsString("Invalid Request"));
}
private void testWithOverriddenPort(int port, Response.Status expectedHttpCode, Matcher<String> pageTextMatcher) throws Exception {