use of org.keycloak.services.ErrorResponseException in project keycloak by keycloak.
the class BackchannelAuthenticationCallbackEndpoint method verifyAuthenticationRequest.
private BackchannelAuthCallbackContext verifyAuthenticationRequest(HttpHeaders headers) {
String rawBearerToken = AppAuthManager.extractAuthorizationHeaderTokenOrReturnNull(headers);
if (rawBearerToken == null) {
throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.UNAUTHORIZED);
}
AccessToken bearerToken;
try {
bearerToken = TokenVerifier.createWithoutSignature(session.tokens().decode(rawBearerToken, AccessToken.class)).withDefaultChecks().realmUrl(Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName())).checkActive(true).audience(Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName())).verify().getToken();
} catch (Exception e) {
event.error(Errors.INVALID_TOKEN);
// authentication channel id format is invalid or it has already been used
throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.FORBIDDEN);
}
OAuth2DeviceTokenStoreProvider store = session.getProvider(OAuth2DeviceTokenStoreProvider.class);
OAuth2DeviceCodeModel deviceCode = store.getByUserCode(realm, bearerToken.getId());
if (deviceCode == null) {
throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.FORBIDDEN);
}
if (!deviceCode.isPending()) {
cancelRequest(bearerToken.getId());
throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.FORBIDDEN);
}
ClientModel issuedFor = realm.getClientByClientId(bearerToken.getIssuedFor());
if (issuedFor == null || !issuedFor.isEnabled()) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Invalid token recipient", Response.Status.BAD_REQUEST);
}
if (!deviceCode.getClientId().equals(issuedFor.getClientId())) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Token recipient mismatch", Response.Status.BAD_REQUEST);
}
session.getContext().setClient(issuedFor);
event.client(issuedFor);
return new BackchannelAuthCallbackContext(bearerToken, deviceCode);
}
use of org.keycloak.services.ErrorResponseException in project keycloak by keycloak.
the class BackchannelAuthenticationCallbackEndpoint method processAuthenticationChannelResult.
@Path("/")
@POST
@NoCache
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response processAuthenticationChannelResult(AuthenticationChannelResponse response) {
event.event(EventType.LOGIN);
BackchannelAuthCallbackContext ctx = verifyAuthenticationRequest(httpRequest.getHttpHeaders());
AccessToken bearerToken = ctx.bearerToken;
OAuth2DeviceCodeModel deviceModel = ctx.deviceModel;
Status status = response.getStatus();
if (status == null) {
event.error(Errors.INVALID_REQUEST);
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Invalid authentication status", Response.Status.BAD_REQUEST);
}
switch(status) {
case SUCCEED:
approveRequest(bearerToken, response.getAdditionalParams());
break;
case CANCELLED:
case UNAUTHORIZED:
denyRequest(bearerToken, status);
break;
}
// Call the notification endpoint
ClientModel client = session.getContext().getClient();
CibaConfig cibaConfig = realm.getCibaPolicy();
if (cibaConfig.getBackchannelTokenDeliveryMode(client).equals(CibaConfig.CIBA_PING_MODE)) {
sendClientNotificationRequest(client, cibaConfig, deviceModel);
}
return Response.ok(MediaType.APPLICATION_JSON_TYPE).build();
}
use of org.keycloak.services.ErrorResponseException in project keycloak by keycloak.
the class UserResource method resetPassword.
/**
* Set up a new password for the user.
*
* @param cred The representation must contain a rawPassword with the plain-text password
*/
@Path("reset-password")
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public void resetPassword(CredentialRepresentation cred) {
auth.users().requireManage(user);
if (cred == null || cred.getValue() == null) {
throw new BadRequestException("No password provided");
}
if (Validation.isBlank(cred.getValue())) {
throw new BadRequestException("Empty password not allowed");
}
try {
session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password(cred.getValue(), false));
} catch (IllegalStateException ise) {
throw new BadRequestException("Resetting to N old passwords is not allowed.");
} catch (ReadOnlyException mre) {
throw new BadRequestException("Can't reset password as account is read only");
} catch (ModelException e) {
logger.warn("Could not update user password.", e);
Properties messages = AdminRoot.getMessages(session, realm, auth.adminAuth().getToken().getLocale());
throw new ErrorResponseException(e.getMessage(), MessageFormat.format(messages.getProperty(e.getMessage(), e.getMessage()), e.getParameters()), Status.BAD_REQUEST);
}
if (cred.isTemporary() != null && cred.isTemporary()) {
user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
} else {
// Remove a potentially existing UPDATE_PASSWORD action when explicitly assigning a non-temporary password.
user.removeRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
}
adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).success();
}
use of org.keycloak.services.ErrorResponseException in project keycloak by keycloak.
the class RoleByIdResource method deleteRole.
/**
* Delete the role
*
* @param id id of role
*/
@Path("{role-id}")
@DELETE
@NoCache
public void deleteRole(@PathParam("role-id") final String id) {
if (realm.getDefaultRole() == null) {
logger.warnf("Default role for realm with id '%s' doesn't exist.", realm.getId());
} else if (realm.getDefaultRole().getId().equals(id)) {
throw new ErrorResponseException(ErrorResponse.error(realm.getDefaultRole().getName() + " is default role of the realm and cannot be removed.", Response.Status.BAD_REQUEST));
}
RoleModel role = getRoleModel(id);
auth.roles().requireManage(role);
deleteRole(role);
if (role.isClientRole()) {
adminEvent.resource(ResourceType.CLIENT_ROLE);
} else {
adminEvent.resource(ResourceType.REALM_ROLE);
}
adminEvent.operation(OperationType.DELETE).resourcePath(session.getContext().getUri()).success();
}
use of org.keycloak.services.ErrorResponseException in project keycloak by keycloak.
the class AuthenticationManager method frontchannelLogoutClientSession.
private static Response frontchannelLogoutClientSession(KeycloakSession session, RealmModel realm, AuthenticatedClientSessionModel clientSession, AuthenticationSessionModel logoutAuthSession, UriInfo uriInfo, HttpHeaders headers) {
UserSessionModel userSession = clientSession.getUserSession();
ClientModel client = clientSession.getClient();
if (!client.isFrontchannelLogout() || AuthenticationSessionModel.Action.LOGGED_OUT.name().equals(clientSession.getAction())) {
return null;
}
final AuthenticationSessionModel.Action logoutState = getClientLogoutAction(logoutAuthSession, client.getId());
if (logoutState == AuthenticationSessionModel.Action.LOGGED_OUT || logoutState == AuthenticationSessionModel.Action.LOGGING_OUT) {
return null;
}
try {
session.clientPolicy().triggerOnEvent(new LogoutRequestContext());
} catch (ClientPolicyException cpe) {
throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
}
try {
setClientLogoutAction(logoutAuthSession, client.getId(), AuthenticationSessionModel.Action.LOGGING_OUT);
String authMethod = clientSession.getProtocol();
// must be a keycloak service like account
if (authMethod == null)
return null;
logger.debugv("frontchannel logout to: {0}", client.getClientId());
LoginProtocol protocol = session.getProvider(LoginProtocol.class, authMethod);
protocol.setRealm(realm).setHttpHeaders(headers).setUriInfo(uriInfo);
Response response = protocol.frontchannelLogout(userSession, clientSession);
if (response != null) {
logger.debug("returning frontchannel logout request to client");
if (!AuthenticationSessionModel.Action.LOGGING_OUT.name().equals(clientSession.getAction())) {
setClientLogoutAction(logoutAuthSession, client.getId(), AuthenticationSessionModel.Action.LOGGED_OUT);
}
return response;
}
} catch (Exception e) {
ServicesLogger.LOGGER.failedToLogoutClient(e);
}
return null;
}
Aggregations