Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MODLOGINKC-35: fix error code while 401 in Keycloak #100

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@
import static org.folio.login.domain.dto.ErrorCode.TOKEN_LOGOUT_UNPROCESSABLE;
import static org.folio.login.domain.dto.ErrorCode.TOKEN_PARSE_FAILURE;
import static org.folio.login.domain.dto.ErrorCode.TOKEN_REFRESH_UNPROCESSABLE;
import static org.folio.login.domain.dto.ErrorCode.UNAUTHORIZED_ERROR;
import static org.folio.login.domain.dto.ErrorCode.UNKNOWN_ERROR;
import static org.folio.login.domain.dto.ErrorCode.VALIDATION_ERROR;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.HttpStatus.NOT_FOUND;
import static org.springframework.http.HttpStatus.NOT_IMPLEMENTED;
import static org.springframework.http.HttpStatus.UNAUTHORIZED;
import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY;

import jakarta.persistence.EntityExistsException;
Expand All @@ -38,6 +40,7 @@
import org.folio.login.exception.TokenLogoutException;
import org.folio.login.exception.TokenParsingException;
import org.folio.login.exception.TokenRefreshException;
import org.folio.login.exception.UnauthorizedException;
import org.folio.spring.cql.CqlQueryValidationException;
import org.folio.spring.exception.NotFoundException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
Expand Down Expand Up @@ -298,6 +301,12 @@ public ResponseEntity<ErrorResponse> handleAllOtherExceptions(Exception exceptio
return buildResponseEntity(exception, INTERNAL_SERVER_ERROR, UNKNOWN_ERROR);
}

@ExceptionHandler(UnauthorizedException.class)
public ResponseEntity<ErrorResponse> handleUnauthorizedException(UnauthorizedException exception) {
logException(DEBUG, exception);
return buildResponseEntity(exception, UNAUTHORIZED, UNAUTHORIZED_ERROR);
}

private static ErrorResponse buildValidationError(Exception exception, List<Parameter> parameters) {
return buildErrorResponse(exception, parameters, VALIDATION_ERROR);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package org.folio.login.exception;

public class UnauthorizedException extends RuntimeException {

/**
* Creates {@link org.folio.login.exception.UnauthorizedException} with error message and error cause.
*
* @param message - error message as {@link String} object
* @param cause - error cause as {@link Throwable} object
*/
public UnauthorizedException(String message, Throwable cause) {
super(message, cause);
}
}
3 changes: 3 additions & 0 deletions src/main/java/org/folio/login/service/KeycloakService.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.folio.login.domain.model.UserCredentials;
import org.folio.login.exception.RequestValidationException;
import org.folio.login.exception.ServiceException;
import org.folio.login.exception.UnauthorizedException;
import org.folio.login.integration.kafka.LogoutEventPublisher;
import org.folio.login.integration.keycloak.KeycloakClient;
import org.folio.login.util.TokenRequestHelper;
Expand Down Expand Up @@ -183,6 +184,8 @@ private KeycloakAuthentication getToken(String userAgent, String forwardedFor, M
var tenantId = folioExecutionContext.getTenantId();
try {
return keycloakClient.callTokenEndpoint(tenantId, payload, userAgent, forwardedFor);
} catch (FeignException.Unauthorized e) {
throw new UnauthorizedException("Unauthorized error", e);
} catch (FeignException cause) {
throw new ServiceException("Failed to obtain a token", cause);
}
Expand Down
3 changes: 2 additions & 1 deletion src/main/resources/swagger.api/schemas/errorCode.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"found_error",
"token.parse.failure",
"token.refresh.unprocessable",
"token.logout.unprocessable"
"token.logout.unprocessable",
"unauthorized_error"
]
}
2 changes: 1 addition & 1 deletion src/test/java/org/folio/login/it/LogEventsIT.java
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ private static void callLoginEndpointWithInvalidCreds() {
.contentType(APPLICATION_JSON)
.header(XOkapiHeaders.TENANT, TENANT)
.content(asJsonString(invalidLoginCredentials())))
.andExpect(status().isBadRequest());
.andExpect(status().isUnauthorized());
}

@SneakyThrows
Expand Down
2 changes: 1 addition & 1 deletion src/test/java/org/folio/login/it/LoginAttemptsIT.java
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ private static void callLoginEndpointWithInvalidCreds() throws Exception {
.contentType(APPLICATION_JSON)
.header(XOkapiHeaders.TENANT, TENANT)
.content(asJsonString(invalidLoginCredentials())))
.andExpect(status().isBadRequest());
.andExpect(status().isUnauthorized());
}

@SneakyThrows
Expand Down
18 changes: 18 additions & 0 deletions src/test/java/org/folio/login/service/KeycloakServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import feign.FeignException;
import feign.RetryableException;
import jakarta.persistence.EntityNotFoundException;
import jakarta.ws.rs.core.Form;
Expand All @@ -48,6 +49,7 @@
import org.folio.login.domain.model.UserCredentials;
import org.folio.login.exception.RequestValidationException;
import org.folio.login.exception.ServiceException;
import org.folio.login.exception.UnauthorizedException;
import org.folio.login.integration.kafka.LogoutEventPublisher;
import org.folio.login.integration.keycloak.KeycloakClient;
import org.folio.login.support.TestConstants;
Expand Down Expand Up @@ -136,6 +138,22 @@ void getUserToken_negative_KeycloakError() {
.hasMessage("Failed to obtain a token");
}

@Test
void getUserToken_negative_unauthorizedException() {
var requestData = loginRequest(USERNAME, PASSWORD, CLIENT_ID, CLIENT_SECRET);
var realmConfig = keycloakRealmConfiguration();

when(folioExecutionContext.getTenantId()).thenReturn(TENANT);
when(realmConfigurationProvider.getRealmConfiguration()).thenReturn(realmConfig);
when(keycloakClient.callTokenEndpoint(TENANT, requestData, null, null))
.thenThrow(FeignException.Unauthorized.class);

var credentials = loginCredentials();
assertThatThrownBy(() -> keycloakService.getUserToken(credentials, null, null))
.isInstanceOf(UnauthorizedException.class)
.hasMessage("Unauthorized error");
}

@Test
void updateCredentials_positive() {
changePassword();
Expand Down