use of net.petafuel.styx.core.persistence.PersistenceEmptyResultSetException in project styx by petafuel.
the class AccessTokenFilter method checkToken.
@Override
public boolean checkToken(String tokenHash) {
AccessToken accessToken;
try {
accessToken = PersistentAccessToken.get(tokenHash);
} catch (PersistenceEmptyResultSetException persistenceEmptyResultSetException) {
// if there was no matching token found in the database, always return unauthorized
ResponseEntity responseEntity = new ResponseEntity(ResponseConstant.UNAUTHORIZED, ResponseCategory.ERROR, ResponseOrigin.CLIENT);
throw new StyxException(responseEntity);
}
if (accessToken.getLastUsedOn() == null && (TimeUnit.MILLISECONDS.toSeconds(new Date().getTime() - accessToken.getCreatedAt().getTime())) > accessToken.getExpiresIn()) {
MasterToken masterToken = PersistentClientApp.get(accessToken.getClientMasterToken());
LOG.warn("Access token expired before first usage, invalidated. master={}, access_token_created={}, serviceBinding={}", masterToken.getName(), accessToken.getCreatedAt(), accessToken.getServiceType());
PersistentAccessToken.setValid(tokenHash, false);
return false;
}
// get master token and check restrictions
MasterToken masterToken = PersistentClientApp.get(accessToken.getClientMasterToken());
checkRestrictions(masterToken, accessToken.getServiceType());
// check if maxUsages is reached
checkMaxUsages(masterToken, accessToken);
// log necessary token information
LOG.info("Request sent with following token information: accessToken={} valid={} serviceType={} usages={} clientReference={} createdAt={} masterTokenName={} masterTokenEnabled={}", accessToken.getId(), accessToken.isValid(), accessToken.getServiceType(), accessToken.getUsages(), accessToken.getClientReference(), accessToken.getCreatedAt(), masterToken.getName(), masterToken.isEnabled());
// get service requirements from Target-Resource class or method
List<XS2ATokenType> serviceRequirements = null;
if (ri.getResourceMethod().getAnnotation(CheckAccessToken.class) != null) {
serviceRequirements = Arrays.asList(ri.getResourceMethod().getAnnotation(CheckAccessToken.class).allowedServices());
} else if (ri.getResourceClass().getAnnotation(CheckAccessToken.class) != null) {
serviceRequirements = Arrays.asList(ri.getResourceClass().getAnnotation(CheckAccessToken.class).allowedServices());
}
// Get all TokenTypeMapperSPI implementations
List<TokenTypeMapperSPI> tokenTypeMapperImpls = new TokenTypeMapperService().providers();
TokenTypeMapperSPI concreteTokenTypeMapper = tokenTypeMapperImpls.stream().filter(tokenTypeMapperSPI -> tokenTypeMapperSPI.getMapping(accessToken.getServiceType()) != null).findFirst().orElse(null);
if (concreteTokenTypeMapper == null || (serviceRequirements != null && !serviceRequirements.contains(concreteTokenTypeMapper.getMapping(accessToken.getServiceType())))) {
if (concreteTokenTypeMapper == null) {
LOG.error("There was not TokenTypeMapperSPI implementation found within the classpath, tokens cannot be validated against access controll");
}
ResponseEntity responseEntity = new ResponseEntity(ResponseConstant.STYX_TOKEN_ACCESS_VIOLATION, ResponseCategory.ERROR, ResponseOrigin.CLIENT);
throw new StyxException(responseEntity);
}
// update lastUsedOn and increase usages of accessToken
if (ri.getResourceClass().isAnnotationPresent(CheckAccessToken.class) && ri.getResourceClass().getAnnotation(CheckAccessToken.class).incrementUsage()) {
PersistentAccessToken.updateLastUsedOn(tokenHash);
}
return accessToken.isValid() && masterToken.isEnabled();
}
use of net.petafuel.styx.core.persistence.PersistenceEmptyResultSetException in project styx by petafuel.
the class PreAuthAccessFilter method filter.
/**
* Supressing java:S3776 -> need to rework logic to reduce code complexity
*
* @param containerRequestContext
*/
@Override
@SuppressWarnings("java:S3776")
public void filter(ContainerRequestContext containerRequestContext) {
XS2AStandard xs2AStandard = (XS2AStandard) containerRequestContext.getProperty(XS2AStandard.class.getName());
IOParser ioParser = new IOParser(xs2AStandard.getAspsp());
ImplementerOption ioPreAuthRequired = ioParser.get("IO6");
if (ioPreAuthRequired != null && ioPreAuthRequired.getOptions().get(IOParser.Option.REQUIRED)) {
LOG.info("ASPSP bic={} requires pre-auth", xs2AStandard.getAspsp().getBic());
// preauth is available and required for this bank -> check if preauth id is present
String preAuthIdString = containerRequestContext.getHeaderString(PRE_AUTH_ID);
if (preAuthIdString == null || "".equals(preAuthIdString)) {
throw new StyxException(new ResponseEntity("The requested aspsps requires a pre-step authorisation, preAuthId Header is missing", ResponseConstant.STYX_PREAUTH_HEADER_REQUIRED, ResponseCategory.ERROR, ResponseOrigin.CLIENT));
}
try {
UUID preAuthId = UUID.fromString(preAuthIdString);
OAuthSession oAuthSession = PersistentOAuthSession.getById(preAuthId);
LOG.info("Loaded state={} oauth_session", oAuthSession.getState());
STYX03.setPreauthId(preAuthId);
if (oAuthSession.getAccessToken() == null || oAuthSession.getAccessTokenExpiresAt() == null) {
throw new PersistenceEmptyResultSetException("The access_token data should be set");
}
if (oAuthSession.getAccessTokenExpiresAt().before(new Date())) {
if (oAuthSession.getRefreshTokenExpiresAt().after(new Date())) {
oAuthSession = refreshToken(oAuthSession);
} else {
throw new OAuthTokenExpiredException(OAuthTokenExpiredException.MESSAGE);
}
}
// Add the Authorization: <type> <credentials> header to the request context so we can use it later on demand
Map<String, String> additionalHeaders = new HashMap<>();
additionalHeaders.put(XS2AHeader.AUTHORIZATION, oAuthSession.getTokenType() + " " + oAuthSession.getAccessToken());
containerRequestContext.setProperty(PreAuthAccessFilter.class.getName(), additionalHeaders);
LOG.info("Successfully attached pre-auth from oAuthSessionState={}", oAuthSession.getState());
} catch (PersistenceEmptyResultSetException noOauthSessionFound) {
throw new StyxException(new ResponseEntity("There was no valid pre-step authorisation found for the specified preAuthId", ResponseConstant.STYX_PREAUTH_NOT_AVAILABLE, ResponseCategory.ERROR, ResponseOrigin.CLIENT));
} catch (OAuthTokenExpiredException tokenExpired) {
throw new StyxException(new ResponseEntity(tokenExpired.getMessage(), ResponseConstant.STYX_PREAUTH_EXPIRED, ResponseCategory.ERROR, ResponseOrigin.CLIENT));
}
}
}
use of net.petafuel.styx.core.persistence.PersistenceEmptyResultSetException in project styx by petafuel.
the class OAuthCallbackProcessor method handlePreStepOAuth2.
/**
* Legacy method to handle pre-step authentication for Sparda, might be deprecated in the future
*
* @param code received from the bank
* @param state received from the bank - matches in styx database
* @param error received from the bank on error
* @param errorMessage received from the bank on error
* @param path to be used as redirect url to styx
* @return returns a jaxrs response object to be returned to a client
*/
public static Response handlePreStepOAuth2(String code, String state, String error, String errorMessage, String path) {
OAuthSession oAuthSession = new OAuthSession();
try {
oAuthSession = PersistentOAuthSession.getByState(state);
} catch (PersistenceEmptyResultSetException oauthSessionNotFound) {
LOG.warn("Error retrieving oAuthSession within prestep callback error={}", oauthSessionNotFound.getMessage());
error += " " + STYX_PREAUTH_NOT_AVAILABLE.name();
}
if (error == null && handleSuccessfulOAuth2(code, state, path)) {
RedirectStatus redirectStatus = new RedirectStatus(StatusType.SUCCESS, oAuthSession.getState(), RedirectStep.PREAUTH);
return StatusHelper.createStatusRedirection(redirectStatus);
} else {
LOG.error(FAILED_OAUTH2, error, errorMessage, state);
RedirectStatus redirectStatus = new RedirectStatus(StatusType.ERROR, oAuthSession.getState(), RedirectStep.PREAUTH);
return StatusHelper.createStatusRedirection(redirectStatus);
}
}
use of net.petafuel.styx.core.persistence.PersistenceEmptyResultSetException in project styx by petafuel.
the class PersistentAccessToken method get.
/**
* @param accessToken this should be the hashed styx access token
* @return accesstoken with metadata
* @throws PersistenceException if any sql error happened
* @throws PersistenceEmptyResultSetException if there was no matching token found in the database
*/
public static AccessToken get(String accessToken) {
Connection connection = Persistence.getInstance().getConnection();
AccessToken model = new AccessToken();
try (PreparedStatement query = connection.prepareStatement("SELECT * FROM get_token(?);")) {
query.setString(1, accessToken);
try (ResultSet resultSet = query.executeQuery()) {
if (resultSet.next()) {
model = dbToModel(resultSet);
} else {
throw new PersistenceEmptyResultSetException("No entry found matching the specified token");
}
}
} catch (SQLException e) {
logSQLError(e);
}
return model;
}
use of net.petafuel.styx.core.persistence.PersistenceEmptyResultSetException in project styx by petafuel.
the class PreAuthResource method getPreStepAuthentication.
/**
* @param preauthId this id should match a state column within the oauth_sessions table
* @return a GetPreStepResponse Object which contains certain values from an OAuthSession object
*/
@GET
@CheckAccessToken(allowedServices = { XS2ATokenType.AIS, XS2ATokenType.PIS, XS2ATokenType.AISPIS, XS2ATokenType.PIIS })
@Path("/preauth/{preauthId}")
public Response getPreStepAuthentication(@NotBlank @PathParam("preauthId") String preauthId) {
OAuthSession oAuthSession;
try {
oAuthSession = PersistentOAuthSession.getById(UUID.fromString(preauthId));
} catch (PersistenceEmptyResultSetException unknownPreauth) {
throw new StyxException(new ResponseEntity(ResponseConstant.STYX_PREAUTH_NOT_FOUND, ResponseCategory.ERROR, ResponseOrigin.CLIENT));
}
LOG.info("Successfully retrieved preauth from oauth_session state={}", oAuthSession.getState());
return Response.status(ResponseConstant.OK).entity(new GetPreStepResponse(oAuthSession)).build();
}
Aggregations