Search in sources :

Example 16 with OAuth2Exception

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());
}
Also used : BaseClientDetails(org.springframework.security.oauth2.provider.client.BaseClientDetails) BaseClientDetails(org.springframework.security.oauth2.provider.client.BaseClientDetails) ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) ExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken) OAuth2RefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) ClientDetailsService(org.springframework.security.oauth2.provider.ClientDetailsService) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) Date(java.util.Date) Test(org.junit.Test)

Example 17 with OAuth2Exception

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());
}
Also used : OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) Test(org.junit.Test)

Example 18 with OAuth2Exception

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));
    }
}
Also used : ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) HttpServletRequest(javax.servlet.http.HttpServletRequest) UserSession(com.haulmont.cuba.security.global.UserSession) SecurityContext(com.haulmont.cuba.core.sys.SecurityContext) LoginException(com.haulmont.cuba.security.global.LoginException) RestUserSessionInfo(com.haulmont.cuba.restapi.RestUserSessionInfo) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) TrustedClientCredentials(com.haulmont.cuba.security.auth.TrustedClientCredentials)

Example 19 with OAuth2Exception

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());
    }
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) RestError(com.epam.ta.reportportal.commons.exception.rest.RestError) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 20 with OAuth2Exception

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);
    }
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) Jwt(org.springframework.security.jwt.Jwt) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) ServletException(javax.servlet.ServletException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) AuthenticationException(org.springframework.security.core.AuthenticationException) IOException(java.io.IOException)

Aggregations

OAuth2Exception (org.springframework.security.oauth2.common.exceptions.OAuth2Exception)57 Test (org.junit.Test)15 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)13 AuthenticationException (org.springframework.security.core.AuthenticationException)11 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)11 Authentication (org.springframework.security.core.Authentication)9 HashMap (java.util.HashMap)8 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 OAuth2Exception (org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception)7 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)7 ModelAndView (org.springframework.web.servlet.ModelAndView)7 RedirectView (org.springframework.web.servlet.view.RedirectView)7 AccessDeniedException (org.springframework.security.access.AccessDeniedException)6 InsufficientScopeException (org.springframework.security.oauth2.common.exceptions.InsufficientScopeException)6 InvalidGrantException (org.springframework.security.oauth2.common.exceptions.InvalidGrantException)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)6 Date (java.util.Date)5 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 ResponseEntity (org.springframework.http.ResponseEntity)5 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)5