Example usage for org.springframework.security.oauth2.common.exceptions OAuth2Exception OAuth2Exception

List of usage examples for org.springframework.security.oauth2.common.exceptions OAuth2Exception OAuth2Exception

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.common.exceptions OAuth2Exception OAuth2Exception.

Prototype

public OAuth2Exception(String msg) 

Source Link

Usage

From source file:org.zalando.stups.oauth2.spring.client.SecurityContextTokenProvider.java

@Override
public OAuth2AccessToken obtainAccessToken(final OAuth2ProtectedResourceDetails details,
        final AccessTokenRequest parameters) {
    final Optional<String> accessToken = AccessTokenUtils.getAccessTokenFromSecurityContext();
    if (!accessToken.isPresent()) {
        throw new OAuth2Exception("No access token available in current security context");
    }/*from w  ww. j a v a  2 s  .co  m*/
    final Map<String, String> tokenParams = new HashMap<>();
    tokenParams.put(ACCESS_TOKEN, accessToken.get());
    tokenParams.put(TOKEN_TYPE, BEARER_TYPE);
    return DefaultOAuth2AccessToken.valueOf(tokenParams);
}

From source file:eu.trentorise.smartcampus.resourceprovider.filter.ResourceFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    try {//from   w w w . j a v  a  2 s  . c  o m

        String tokenValue = parseToken(request);
        if (HttpMethod.OPTIONS.equals(HttpMethod.valueOf(request.getMethod()))) {
            chain.doFilter(request, response);
            //            throw new OAuth2Exception("options");
        } else if (tokenValue == null) {
            if (debug) {
                logger.debug("No token in request, will continue chain.");
            }
            throw new OAuth2Exception("empty token");
        } else {
            ResourceCallAuthenticationToken authentication = new ResourceCallAuthenticationToken(tokenValue,
                    "");
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, tokenValue);
            authentication.setDetails(authenticationDetailsSource.buildDetails(request));
            authentication.setRequestPath(getFullURL(request));
            authentication.setHttpMethod(HttpMethod.valueOf(request.getMethod()));
            Authentication authResult = authenticationManager.authenticate(authentication);

            SecurityContextHolder.getContext().setAuthentication(authResult);

            chain.doFilter(request, response);

        }
    } catch (OAuth2Exception failed) {
        SecurityContextHolder.clearContext();

        if (debug) {
            logger.debug("Authentication request failed: " + failed);
        }

        authenticationEntryPoint.commence(request, response,
                new InsufficientAuthenticationException(failed.getMessage(), failed));

        return;
    }

}

From source file:eu.trentorise.smartcampus.resourceprovider.filter.ResourceAuthenticationManager.java

/**
 * Check whether the access to the specific resource is granted. The The
 * resource is identified from the {@link ResourceCallAuthenticationToken}
 * fields {@link ResourceCallAuthenticationToken#getRequestPath()} and
 * {@link ResourceCallAuthenticationToken#getHttpMethod()}.
 * /*from   w w  w  .  j  a  v a  2  s. c  o m*/
 * @param authentication
 *            the authentication token object as instance of
 *            {@link ResourceCallAuthenticationToken}.
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    assert authentication instanceof ResourceCallAuthenticationToken;
    ResourceCallAuthenticationToken rcAuth = (ResourceCallAuthenticationToken) authentication;

    String token = (String) rcAuth.getPrincipal();
    OAuth2Authentication auth = loadAuthentication(token);

    if (auth == null) {
        throw new InvalidTokenException("Invalid token: " + token);
    }

    String resourceUri;
    try {
        resourceUri = getUriManager().getUriFromRequest(rcAuth.getRequestPath(), rcAuth.getHttpMethod(),
                auth.getAuthorities());
    } catch (IOException e) {
        throw new OAuth2Exception("Problem accessing resource descriptor");
    }

    String resourceID = resourceUri;// resourceStore.loadResourceByResourceUri(resourceUri);
    // test senza lettura db

    Collection<String> resourceIds = auth.getAuthorizationRequest().getScope();

    if (resourceID == null || resourceIds.isEmpty() || !resourceIds.contains(resourceID)) {
        throw new OAuth2AccessDeniedException(
                "Invalid token does not contain resource id (" + resourceUri + ")");
    }

    String authority = authServices.loadResourceAuthorityByResourceUri(resourceUri);
    if (ROLE_USER.equals(authority) && auth.isClientOnly()) {
        throw new OAuth2AccessDeniedException("Incorrect access method");
    }
    if (ROLE_CLIENT.equals(authority) && !auth.isClientOnly()) {
        throw new OAuth2AccessDeniedException("Incorrect access method");
    }

    auth.setDetails(authentication.getDetails());

    return auth;
}

From source file:org.springframework.security.oauth2.common.exceptions.OAuth2ExceptionJackson2Deserializer.java

@Override
public OAuth2Exception deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    JsonToken t = jp.getCurrentToken();//from w  w w . j  a v a 2  s  . c  om
    if (t == JsonToken.START_OBJECT) {
        t = jp.nextToken();
    }
    Map<String, Object> errorParams = new HashMap<String, Object>();
    for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
        // Must point to field name
        String fieldName = jp.getCurrentName();
        // And then the value...
        t = jp.nextToken();
        // Note: must handle null explicitly here; value deserializers won't
        Object value;
        if (t == JsonToken.VALUE_NULL) {
            value = null;
        }
        // Some servers might send back complex content
        else if (t == JsonToken.START_ARRAY) {
            value = jp.readValueAs(List.class);
        } else if (t == JsonToken.START_OBJECT) {
            value = jp.readValueAs(Map.class);
        } else {
            value = jp.getText();
        }
        errorParams.put(fieldName, value);
    }

    Object errorCode = errorParams.get("error");
    String errorMessage = errorParams.containsKey("error_description")
            ? errorParams.get("error_description").toString()
            : null;
    if (errorMessage == null) {
        errorMessage = errorCode == null ? "OAuth Error" : errorCode.toString();
    }

    OAuth2Exception ex;
    if ("invalid_client".equals(errorCode)) {
        ex = new InvalidClientException(errorMessage);
    } else if ("unauthorized_client".equals(errorCode)) {
        ex = new UnauthorizedUserException(errorMessage);
    } else if ("invalid_grant".equals(errorCode)) {
        if (errorMessage.toLowerCase().contains("redirect") && errorMessage.toLowerCase().contains("match")) {
            ex = new RedirectMismatchException(errorMessage);
        } else {
            ex = new InvalidGrantException(errorMessage);
        }
    } else if ("invalid_scope".equals(errorCode)) {
        ex = new InvalidScopeException(errorMessage);
    } else if ("invalid_token".equals(errorCode)) {
        ex = new InvalidTokenException(errorMessage);
    } else if ("invalid_request".equals(errorCode)) {
        ex = new InvalidRequestException(errorMessage);
    } else if ("redirect_uri_mismatch".equals(errorCode)) {
        ex = new RedirectMismatchException(errorMessage);
    } else if ("unsupported_grant_type".equals(errorCode)) {
        ex = new UnsupportedGrantTypeException(errorMessage);
    } else if ("unsupported_response_type".equals(errorCode)) {
        ex = new UnsupportedResponseTypeException(errorMessage);
    } else if ("insufficient_scope".equals(errorCode)) {
        ex = new InsufficientScopeException(errorMessage,
                OAuth2Utils.parseParameterList((String) errorParams.get("scope")));
    } else if ("access_denied".equals(errorCode)) {
        ex = new UserDeniedAuthorizationException(errorMessage);
    } else {
        ex = new OAuth2Exception(errorMessage);
    }

    Set<Map.Entry<String, Object>> entries = errorParams.entrySet();
    for (Map.Entry<String, Object> entry : entries) {
        String key = entry.getKey();
        if (!"error".equals(key) && !"error_description".equals(key)) {
            Object value = entry.getValue();
            ex.addAdditionalInformation(key, value == null ? null : value.toString());
        }
    }

    return ex;

}

From source file:com.haulmont.restapi.idp.IdpAuthController.java

@GetMapping(value = "/v2/idp/login")
public ResponseEntity login(@RequestParam(value = "redirectUrl", required = false) String redirectUrl) {
    if (!idpConfig.getIdpEnabled()) {
        log.debug("IDP authentication is disabled. Property cuba.rest.idp.enabled is false");

        throw new InvalidGrantException("IDP is not supported");
    }//from w  w  w .  ja v a2 s  .  com

    if (redirectUrl == null) {
        redirectUrl = idpDefaultRedirectUrl;
    }

    if (redirectUrl == null) {
        log.debug("IDP defaultRedirectUrl is not set. Client did not provide redirectUrl parameter");

        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(new OAuth2Exception("Client did not provide redirectUrl parameter"));
    }

    return ResponseEntity.status(HttpStatus.FOUND).location(URI.create(getIdpLoginUrl(redirectUrl))).build();
}

From source file:org.osiam.security.helper.LessStrictRedirectUriAuthorizationCodeTokenGranter.java

private AuthorizationRequestHolder getAuthorizationRequestHolder(Map<String, String> parameters) {
    String authorizationCode = parameters.get("code");
    if (authorizationCode == null) {
        throw new OAuth2Exception("An authorization code must be supplied.");
    }/*from   w  w w. jav a2 s .c  om*/

    AuthorizationRequestHolder storedAuth = authorizationCodeServices
            .consumeAuthorizationCode(authorizationCode);
    if (storedAuth == null) {
        throw new InvalidGrantException("Invalid authorization code: " + authorizationCode);
    }
    return storedAuth;
}

From source file:com.haulmont.restapi.auth.ClientProxyTokenStore.java

/**
 * 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.
 *///from   w w  w.  j a v a 2  s.  c  o m
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");
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                    .currentRequestAttributes();
            Locale locale = sessionInfo != null ? sessionInfo.getLocale() : null;
            TrustedClientCredentials credentials = new TrustedClientCredentials(username,
                    restApiConfig.getTrustedClientPassword(), locale);
            credentials.setClientType(ClientType.REST_API);
            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);
            }

            session = authenticationService.login(credentials).getSession();
        } catch (LoginException e) {
            throw new OAuth2Exception("Cannot login to the middleware");
        }
    }

    if (session != null) {
        serverTokenStore.putSessionInfo(tokenValue, new RestUserSessionInfo(session));
        AppContext.setSecurityContext(new SecurityContext(session));
    }
}

From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaController.java

@RequestMapping(value = "/oauth/authorize", params = "response_type")
public ModelAndView startAuthorization(HttpServletRequest request, @RequestParam Map<String, String> parameters,
        Map<String, Object> model, @RequestHeader HttpHeaders headers, Principal principal) throws Exception {

    String path = extractPath(request);

    MultiValueMap<String, String> map = new LinkedMaskingMultiValueMap<String, String>();
    map.setAll(parameters);//from   w ww .ja  v  a  2s  .  c  o  m

    String redirectUri = parameters.get("redirect-uri");
    if (redirectUri != null && !redirectUri.matches("(http:|https:)?//.*")) {
        redirectUri = "http://" + redirectUri;
        map.set("redirect-uri", redirectUri);
    }

    if (principal != null) {
        map.set("source", "login");
        map.setAll(getLoginCredentials(principal));
        map.remove("credentials"); // legacy cf might break otherwise
        map.remove("password"); // request for token will not use password
    } else {
        throw new BadCredentialsException("No principal found in authorize endpoint");
    }

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.putAll(getRequestHeaders(headers));
    requestHeaders.remove(AUTHORIZATION.toLowerCase());
    requestHeaders.remove(USER_AGENT);
    requestHeaders.remove(ACCEPT.toLowerCase());
    requestHeaders.remove(CONTENT_TYPE.toLowerCase());
    requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    requestHeaders.remove(COOKIE);
    requestHeaders.remove(COOKIE.toLowerCase());

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response;

    response = authorizationTemplate.exchange(getUaaBaseUrl() + "/" + path, HttpMethod.POST,
            new HttpEntity<MultiValueMap<String, String>>(map, requestHeaders), Map.class);

    saveCookie(response.getHeaders(), model);

    @SuppressWarnings("unchecked")
    Map<String, Object> body = response.getBody();
    if (body != null) {
        // User approval is required
        logger.debug("Response: " + body);
        model.putAll(body);
        model.put("links", getLinksInfo());
        if (!body.containsKey("options")) {
            String errorMsg = "No options returned from UAA for user approval";
            if (body.containsKey("error")) {
                throw OAuth2Exception.create((String) body.get("error"),
                        (String) (body.containsKey("error_description") ? body.get("error_description")
                                : errorMsg));
            } else {
                throw new OAuth2Exception(errorMsg);
            }
        }
        logger.info("Approval required in /oauth/authorize for: " + principal.getName());
        return new ModelAndView("access_confirmation", model);
    }

    String location = response.getHeaders().getFirst("Location");
    if (location != null) {
        logger.info("Redirect in /oauth/authorize for: " + principal.getName());
        // Don't expose model attributes (cookie) in redirect
        return new ModelAndView(new RedirectView(location, false, true, false));
    }

    throw new IllegalStateException("Neither a redirect nor a user approval");

}

From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaController.java

@RequestMapping(value = "/oauth/**")
@ResponseBody//w ww . j  a v a2  s .co  m
public void invalid(HttpServletRequest request) throws Exception {
    throw new OAuth2Exception("no matching handler for request: " + request.getServletPath());
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java

private OAuth2AccessToken getAccessTokenForImplicitGrantOrHybrid(TokenRequest tokenRequest,
        OAuth2Request storedOAuth2Request, String grantType) throws OAuth2Exception {
    // These 1 method calls have to be atomic, otherwise the ImplicitGrantService can have a race condition where
    // one thread removes the token request before another has a chance to redeem it.
    synchronized (this.implicitLock) {
        switch (grantType) {
        case GRANT_TYPE_IMPLICIT:
            return getTokenGranter().grant(grantType,
                    new ImplicitTokenRequest(tokenRequest, storedOAuth2Request));
        case GRANT_TYPE_AUTHORIZATION_CODE:
            return getHybridTokenGranterForAuthCode().grant(grantType,
                    new ImplicitTokenRequest(tokenRequest, storedOAuth2Request));
        default:/*from   w w w .  j a v a2s. c o  m*/
            throw new OAuth2Exception(OAuth2Exception.INVALID_GRANT);
        }
    }
}