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

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

Introduction

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

Prototype

public InvalidTokenException(String msg) 

Source Link

Usage

From source file:com.epam.reportportal.auth.OAuthErrorHandlerTest.java

@Test
public void testOAuthException() throws Exception {
    String msg = "some exception!";
    ResponseEntity<OAuth2Exception> translate = errorHandler.translate(new InvalidTokenException(msg));
    Map<String, String> additionalInformation = translate.getBody().getAdditionalInformation();

    Assert.assertThat("Incorrect exception conversion", additionalInformation,
            Matchers.hasEntry("message", translate.getBody().getMessage()));

}

From source file:org.joyrest.oauth2.interceptor.AuthenticationInterceptor.java

@Override
public InternalResponse<Object> around(InterceptorChain chain, InternalRequest<Object> req,
        InternalResponse<Object> resp) throws Exception {
    InternalRoute route = chain.getRoute();

    if (route.isSecured()) {
        Authentication authentication = extractToken(req).orElseThrow(
                () -> new InvalidTokenException("There is no access token in headers or in query params"));

        Authentication principal = authenticationManager.authenticate(authentication);
        req.setPrincipal(principal);/*from ww  w  .ja  v a2 s  .c  om*/
    }

    return chain.proceed(req, resp);
}

From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateUserAuthenticationConverter.java

/**
 * {@inheritDoc}/*w  ww  .  j  a  va 2s.  c  o  m*/
 */
//TODO: might be too much unnecessary validation in here
@Override
public Authentication extractAuthentication(final Map<String, ?> map) {
    // Make sure we have a client id to use as the Principle
    if (!map.containsKey(CLIENT_ID_KEY)) {
        throw new InvalidTokenException("No client id key found in map");
    }

    final Object clientIdObject = map.get(CLIENT_ID_KEY);
    if (!(clientIdObject instanceof String)) {
        throw new InvalidTokenException("Client id wasn't string");
    }

    final String userName = (String) clientIdObject;
    if (StringUtils.isBlank(userName)) {
        throw new InvalidTokenException("Client id was blank. Unable to use as user name");
    }

    // Scopes were already validated in PingFederateRemoteTokenServices
    final Object scopeObject = map.get(SCOPE_KEY);
    if (!(scopeObject instanceof Collection)) {
        throw new InvalidTokenException("Scopes were not a collection");
    }

    @SuppressWarnings("unchecked")
    final Collection<String> scopes = (Collection<String>) scopeObject;
    if (scopes.isEmpty()) {
        throw new InvalidTokenException("No scopes available. Unable to authenticate");
    }

    // Default to user role
    final Set<GrantedAuthority> authorities = Sets.newHashSet(USER_AUTHORITY);

    scopes.stream().filter(scope -> scope.contains(GENIE_PREFIX)).distinct()
            .forEach(scope -> authorities.add(new SimpleGrantedAuthority(
                    ROLE_PREFIX + StringUtils.removeStartIgnoreCase(scope, GENIE_PREFIX).toUpperCase())));

    return new UsernamePasswordAuthenticationToken(userName, "N/A", authorities);
}

From source file:eu.trentorise.smartcampus.permissionprovider.oauth.NonRemovingTokenServices.java

/**
 * Do not remove access token if expired
 *//*w  w w .  j ava2 s.com*/
@Override
public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException {
    OAuth2AccessToken accessToken = localtokenStore.readAccessToken(accessTokenValue);
    if (accessToken == null) {
        throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
    } else if (accessToken.isExpired()) {
        logger.error("Accessing expired token: " + accessTokenValue);
        throw new InvalidTokenException("Access token expired: " + accessTokenValue);
    }

    OAuth2Authentication result = localtokenStore.readAuthentication(accessToken);
    return result;
}

From source file:org.zalando.stups.oauth2.spring.server.AbstractAuthenticationExtractor.java

protected Set<String> validateUidScope(final Set<String> scopes, final Map<String, Object> map) {
    Set<String> result = new HashSet<String>(scopes);
    String uidValue = (String) map.get(UID_SCOPE);

    if (StringUtils.hasText(uidValue)) {
        result.add(UID_SCOPE);//from w w w  . j a  v  a 2s.  c  om
    } else {
        if (isThrowExceptionOnEmptyUid()) {
            throw new InvalidTokenException("'uid' in accessToken should never be empty!");
        }
    }

    return result;
}

From source file:com.example.TokenServices.java

private Supplier<InvalidTokenException> invalidAccessToken(final String accessToken) {
    return () -> new InvalidTokenException("invalid access_token[" + accessToken + "]");
}

From source file:org.cloudfoundry.identity.uaa.authentication.manager.ScopeAuthenticationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    try {/*from  w  w  w.  ja  v a2  s  .  co  m*/
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || (!(authentication instanceof OAuth2Authentication))) {
            throw new InvalidTokenException("Missing oauth token.");
        }
        authenticationManager.authenticate(authentication);
        chain.doFilter(request, response);
    } catch (AuthenticationException e) {
        authenticationEntryPoint.commence((HttpServletRequest) request, (HttpServletResponse) response, e);
        SecurityContextHolder.clearContext();
    }
}

From source file:org.zalando.stups.oauth2.spring.server.AbstractAuthenticationExtractor.java

protected Object getPrincipal(final Map<String, Object> map) {
    for (String key : getPossibleUserIdKeys()) {
        if (map.containsKey(key)) {
            return map.get(key);
        }//  w ww. j a  va2 s  . c  o  m
    }

    throw new InvalidTokenException("No 'uid'-scope found in access-token!");

    // return "unknown";
}

From source file:org.cloudfoundry.identity.uaa.authentication.manager.ScopeAuthenticationManager.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication instanceof OAuth2Authentication) {
        AuthorizationRequest creq = ((OAuth2Authentication) authentication).getAuthorizationRequest();
        List<String> scopes = dedup(creq.getScope());
        int matches = 0;
        int requiredMatches = getRequiredScopes().size();
        for (String scope : scopes) {
            if (requiredScopes.contains(scope)) {
                matches++;/*from  w w w .  j  a va 2s.  c o m*/
            }
        }
        if (matches == requiredMatches) {
            ((DefaultAuthorizationRequest) creq).setApproved(true);
            authentication.setAuthenticated(true);
            return authentication;
        } else if (isThrowOnNotAuthenticated()) {
            throw new InsufficientScopeException("Insufficient scopes");
        }
    } else if (isThrowOnNotAuthenticated()) {
        throw new InvalidTokenException("Missing Oauth 2 authentication.");
    }
    return authentication;
}