use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project spring-security-oauth by spring-projects.
the class DefaultTokenServicesWithInMemoryTests method testDifferentRefreshTokenMaintainsState.
@Test
public void testDifferentRefreshTokenMaintainsState() throws Exception {
// create access token
getTokenServices().setAccessTokenValiditySeconds(1);
getTokenServices().setClientDetailsService(new ClientDetailsService() {
public ClientDetails loadClientByClientId(String clientId) throws OAuth2Exception {
BaseClientDetails client = new BaseClientDetails();
client.setAccessTokenValiditySeconds(1);
client.setAuthorizedGrantTypes(Arrays.asList("authorization_code", "refresh_token"));
return client;
}
});
OAuth2Authentication expectedAuthentication = new OAuth2Authentication(RequestTokenFactory.createOAuth2Request("id", false, Collections.singleton("read")), new TestAuthentication("test2", false));
DefaultOAuth2AccessToken firstAccessToken = (DefaultOAuth2AccessToken) getTokenServices().createAccessToken(expectedAuthentication);
OAuth2RefreshToken expectedExpiringRefreshToken = firstAccessToken.getRefreshToken();
// Make it expire (and rely on mutable state in volatile token store)
firstAccessToken.setExpiration(new Date(System.currentTimeMillis() - 1000));
// create another access token
OAuth2AccessToken secondAccessToken = getTokenServices().createAccessToken(expectedAuthentication);
assertFalse("The new access token should be different", firstAccessToken.getValue().equals(secondAccessToken.getValue()));
assertEquals("The new access token should have the same refresh token", expectedExpiringRefreshToken.getValue(), secondAccessToken.getRefreshToken().getValue());
// refresh access token with refresh token
TokenRequest tokenRequest = new TokenRequest(Collections.singletonMap("client_id", "id"), "id", Collections.singleton("read"), null);
getTokenServices().refreshAccessToken(expectedExpiringRefreshToken.getValue(), tokenRequest);
assertEquals(1, getAccessTokenCount());
}
use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project spring-security-oauth by spring-projects.
the class DefaultWebResponseExceptionTranslatorTests method translateWhenGeneralExceptionThenReturnInternalServerError.
// gh-1200
@Test
public void translateWhenGeneralExceptionThenReturnInternalServerError() throws Exception {
String errorMessage = "An error message that contains sensitive information that should not be exposed to the caller.";
ResponseEntity<OAuth2Exception> response = this.translator.translate(new Exception(errorMessage));
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), response.getBody().getMessage());
}
use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project cuba by cuba-platform.
the class ClientProxyTokenStore method processSession.
/**
* Tries to find the session associated with the given {@code authentication}. If the session id is in the store and
* exists then it is set to the {@link SecurityContext}. If the session id is not in the store or the session with
* the id doesn't exist in the middleware, then the trusted login attempt is performed.
*/
protected void processSession(OAuth2Authentication authentication, String tokenValue) {
RestUserSessionInfo sessionInfo = serverTokenStore.getSessionInfoByTokenValue(tokenValue);
UUID sessionId = sessionInfo != null ? sessionInfo.getId() : null;
if (sessionId == null) {
@SuppressWarnings("unchecked") Map<String, String> userAuthenticationDetails = (Map<String, String>) authentication.getUserAuthentication().getDetails();
// sessionId parameter was put in the CubaUserAuthenticationProvider
String sessionIdStr = userAuthenticationDetails.get("sessionId");
if (!Strings.isNullOrEmpty(sessionIdStr)) {
sessionId = UUID.fromString(sessionIdStr);
}
}
UserSession session = null;
if (sessionId != null) {
try {
session = trustedClientService.findSession(restApiConfig.getTrustedClientPassword(), sessionId);
} catch (LoginException e) {
throw new RuntimeException("Unable to login with trusted client password");
}
}
if (session == null) {
@SuppressWarnings("unchecked") Map<String, String> userAuthenticationDetails = (Map<String, String>) authentication.getUserAuthentication().getDetails();
String username = userAuthenticationDetails.get("username");
if (Strings.isNullOrEmpty(username)) {
throw new IllegalStateException("Empty username extracted from user authentication details");
}
Locale locale = sessionInfo != null ? sessionInfo.getLocale() : null;
TrustedClientCredentials credentials = new TrustedClientCredentials(username, restApiConfig.getTrustedClientPassword(), locale);
credentials.setClientType(ClientType.REST_API);
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
credentials.setIpAddress(request.getRemoteAddr());
credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT)));
} else {
credentials.setClientInfo(makeClientInfo(""));
}
// if locale was not determined then use the user locale
if (locale == null) {
credentials.setOverrideLocale(false);
}
try {
session = authenticationService.login(credentials).getSession();
} catch (LoginException e) {
throw new OAuth2Exception("Cannot login to the middleware", e);
}
log.debug("New session created for token '{}' since the original session has been expired", tokenValue);
}
if (session != null) {
serverTokenStore.putSessionInfo(tokenValue, new RestUserSessionInfo(session));
AppContext.setSecurityContext(new SecurityContext(session));
}
}
use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project service-authorization by reportportal.
the class OAuthErrorHandler method translate.
@Override
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
if (e instanceof OAuth2Exception) {
ResponseEntity<OAuth2Exception> translate = super.translate(e);
OAuth2Exception body = translate.getBody();
body.addAdditionalInformation("message", body.getMessage());
body.addAdditionalInformation("error_code", String.valueOf(ErrorType.ACCESS_DENIED.getCode()));
return translate;
} else {
RestError restError = errorResolver.resolveError(e);
OAuth2Exception exception = OAuth2Exception.create(String.valueOf(restError.getErrorRS().getErrorType().getCode()), restError.getErrorRS().getMessage());
exception.addAdditionalInformation("message", restError.getErrorRS().getMessage());
return new ResponseEntity<>(exception, restError.getHttpStatus());
}
}
use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project tutorials by eugenp.
the class OpenIdConnectFilter method attemptAuthentication.
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
OAuth2AccessToken accessToken;
try {
accessToken = restTemplate.getAccessToken();
} catch (final OAuth2Exception e) {
throw new BadCredentialsException("Could not obtain access token", e);
}
try {
final String idToken = accessToken.getAdditionalInformation().get("id_token").toString();
String kid = JwtHelper.headers(idToken).get("kid");
final Jwt tokenDecoded = JwtHelper.decodeAndVerify(idToken, verifier(kid));
final Map<String, String> authInfo = new ObjectMapper().readValue(tokenDecoded.getClaims(), Map.class);
verifyClaims(authInfo);
final OpenIdConnectUserDetails user = new OpenIdConnectUserDetails(authInfo, accessToken);
return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
} catch (final Exception e) {
throw new BadCredentialsException("Could not obtain user details from token", e);
}
}
Aggregations