org.springframework.security.oauth2.client.resource.UserRedirectRequiredException Java Examples

The following examples show how to use org.springframework.security.oauth2.client.resource.UserRedirectRequiredException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SmartlingAuthorizationCodeAccessTokenProvider.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails details, AccessTokenRequest accessTokenRequest) throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException {


    logger.debug("Get access token");
    Map<String, String> request = new HashMap<>();
    request.put("userIdentifier", details.getClientId());
    request.put("userSecret", details.getClientSecret());

    DefaultOAuth2AccessToken defaultOAuth2AccessToken = null;
    try {
        DateTime now = getNowForToken();
        AuthenticationResponse authenticationResponse = restTemplate.postForObject(details.getAccessTokenUri(), request, AuthenticationResponse.class);
        defaultOAuth2AccessToken = getDefaultOAuth2AccessToken(now, authenticationResponse);
    } catch (Exception e) {
        String msg = "Can't get Smartling token";
        logger.debug(msg, e);
        throw new OAuth2AccessDeniedException(msg, details, e);
    }

    return defaultOAuth2AccessToken;
}
 
Example #2
Source File: GoogleFitShim.java    From shimmer with Apache License 2.0 6 votes vote down vote up
@Override
protected String getAuthorizationUrl(UserRedirectRequiredException exception, Map<String, String> addlParameters) {

    final OAuth2ProtectedResourceDetails resource = getResource();

    UriComponentsBuilder uriBuilder = UriComponentsBuilder
            .fromUriString(exception.getRedirectUri())
            .queryParam("state", exception.getStateKey())
            .queryParam("client_id", resource.getClientId())
            .queryParam("response_type", "code")
            .queryParam("access_type", "offline")
            .queryParam("approval_prompt", "force")
            .queryParam("scope", StringUtils.collectionToDelimitedString(resource.getScope(), " "))
            .queryParam("redirect_uri", getDefaultRedirectUrl());

    return uriBuilder.build().encode().toUriString();
}
 
Example #3
Source File: MovesShim.java    From shimmer with Apache License 2.0 6 votes vote down vote up
@Override
protected String getAuthorizationUrl(
        UserRedirectRequiredException exception,
        Map<String, String> additionalParameters) {

    final OAuth2ProtectedResourceDetails resource = getResource();

    UriComponentsBuilder uriBuilder = UriComponentsBuilder
            .fromUriString(exception.getRedirectUri())
            .queryParam("response_type", "code")
            .queryParam("client_id", resource.getClientId())
            .queryParam("redirect_uri", getDefaultRedirectUrl())
            .queryParam("scope", Joiner.on(" ").join(resource.getScope()))
            .queryParam("state", exception.getStateKey());

    return uriBuilder.build().encode().toUriString();
}
 
Example #4
Source File: SmartlingAuthorizationCodeAccessTokenProvider.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource, OAuth2RefreshToken refreshToken, AccessTokenRequest accessTokenRequest) throws UserRedirectRequiredException {

    logger.debug("Get refresh token");

    SmartlingOAuth2ProtectedResourceDetails smartlingOAuth2ProtectedResourceDetails = (SmartlingOAuth2ProtectedResourceDetails) resource;
    Map<String, String> request = new HashMap<>();
    request.put("refreshToken", refreshToken.getValue());

    DefaultOAuth2AccessToken defaultOAuth2AccessToken = null;
    try {
        DateTime now = getNowForToken();
        AuthenticationResponse authenticationResponse = restTemplate.postForObject(smartlingOAuth2ProtectedResourceDetails.getRefreshUri(), request, AuthenticationResponse.class);
        defaultOAuth2AccessToken = getDefaultOAuth2AccessToken(now, authenticationResponse);
    } catch (Exception e) {
        String msg = "Can't get Smartling refresh token";
        logger.debug(msg, e);
        throw new OAuth2AccessDeniedException(msg, resource, e);
    }

    return defaultOAuth2AccessToken;
}
 
Example #5
Source File: OAuth2FeignRequestInterceptor.java    From spring-cloud-security with Apache License 2.0 6 votes vote down vote up
/**
 * Extract the access token within the request or try to acquire a new one by
 * delegating it to {@link #acquireAccessToken()}.
 * @return valid token
 */
public OAuth2AccessToken getToken() {

	OAuth2AccessToken accessToken = oAuth2ClientContext.getAccessToken();
	if (accessToken == null || accessToken.isExpired()) {
		try {
			accessToken = acquireAccessToken();
		}
		catch (UserRedirectRequiredException e) {
			oAuth2ClientContext.setAccessToken(null);
			String stateKey = e.getStateKey();
			if (stateKey != null) {
				Object stateToPreserve = e.getStateToPreserve();
				if (stateToPreserve == null) {
					stateToPreserve = "NONE";
				}
				oAuth2ClientContext.setPreservedState(stateKey, stateToPreserve);
			}
			throw e;
		}
	}
	return accessToken;
}
 
Example #6
Source File: AuthorizationHeaderUtil.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 6 votes vote down vote up
public Optional<String> getAuthorizationHeaderFromOAuth2Context() {
    OAuth2AccessToken previousAccessToken = oAuth2RestTemplate.getOAuth2ClientContext().getAccessToken();
    if (previousAccessToken == null) {
        return Optional.empty();
    } else {
        OAuth2AccessToken accessToken;
        try {
            // Get the token from OAuth2ClientContext and refresh it if necessary
            accessToken = oAuth2RestTemplate.getAccessToken();
        } catch (UserRedirectRequiredException e) {
            // It's a refresh failure (because previous token wasn't null)
            // If it's an AJAX Request, this sends a 401 error
            throw new AccessTokenRequiredException("Refreshing access token failed",null);
        }

        String tokenType = accessToken.getTokenType();
        if (!StringUtils.hasText(tokenType)) {
            tokenType = OAuth2AccessToken.BEARER_TYPE;
        }
        String authorizationHeaderValue = String.format("%s %s", tokenType, accessToken.getValue());
        return Optional.of(authorizationHeaderValue);
    }
}
 
Example #7
Source File: AuthorizationHeaderUtil.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 6 votes vote down vote up
public Optional<String> getAuthorizationHeaderFromOAuth2Context() {
    OAuth2AccessToken previousAccessToken = oAuth2RestTemplate.getOAuth2ClientContext().getAccessToken();
    if (previousAccessToken == null) {
        return Optional.empty();
    } else {
        OAuth2AccessToken accessToken;
        try {
            // Get the token from OAuth2ClientContext and refresh it if necessary
            accessToken = oAuth2RestTemplate.getAccessToken();
        } catch (UserRedirectRequiredException e) {
            // It's a refresh failure (because previous token wasn't null)
            // If it's an AJAX Request, this sends a 401 error
            throw new AccessTokenRequiredException("Refreshing access token failed",null);
        }

        String tokenType = accessToken.getTokenType();
        if (!StringUtils.hasText(tokenType)) {
            tokenType = OAuth2AccessToken.BEARER_TYPE;
        }
        String authorizationHeaderValue = String.format("%s %s", tokenType, accessToken.getValue());
        return Optional.of(authorizationHeaderValue);
    }
}
 
Example #8
Source File: AuthorizationHeaderUtil.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 6 votes vote down vote up
public Optional<String> getAuthorizationHeaderFromOAuth2Context() {
    OAuth2AccessToken previousAccessToken = oAuth2RestTemplate.getOAuth2ClientContext().getAccessToken();
    if (previousAccessToken == null) {
        return Optional.empty();
    } else {
        OAuth2AccessToken accessToken;
        try {
            // Get the token from OAuth2ClientContext and refresh it if necessary
            accessToken = oAuth2RestTemplate.getAccessToken();
        } catch (UserRedirectRequiredException e) {
            // It's a refresh failure (because previous token wasn't null)
            // If it's an AJAX Request, this sends a 401 error
            throw new AccessTokenRequiredException("Refreshing access token failed",null);
        }

        String tokenType = accessToken.getTokenType();
        if (!StringUtils.hasText(tokenType)) {
            tokenType = OAuth2AccessToken.BEARER_TYPE;
        }
        String authorizationHeaderValue = String.format("%s %s", tokenType, accessToken.getValue());
        return Optional.of(authorizationHeaderValue);
    }
}
 
Example #9
Source File: IHealthShim.java    From shimmer with Apache License 2.0 6 votes vote down vote up
@Override
protected String getAuthorizationUrl(UserRedirectRequiredException exception, Map<String, String> addlParameters) {

    final OAuth2ProtectedResourceDetails resource = getResource();

    UriComponentsBuilder callBackUriBuilder = UriComponentsBuilder.fromUriString(getDefaultRedirectUrl())
            .queryParam("state", exception.getStateKey());

    UriComponentsBuilder authorizationUriBuilder = UriComponentsBuilder.fromUriString(exception.getRedirectUri())
            .queryParam("client_id", resource.getClientId())
            .queryParam("response_type", "code")
            .queryParam("APIName", Joiner.on(' ').join(resource.getScope()))
            .queryParam("RequiredAPIName", Joiner.on(' ').join(resource.getScope()))
            .queryParam("redirect_uri", callBackUriBuilder.build().toString());

    return authorizationUriBuilder.build().encode().toString();
}
 
Example #10
Source File: MyOAuth2RestTemplate.java    From springboot-security-wechat with Apache License 2.0 6 votes vote down vote up
public OAuth2AccessToken getAccessToken() throws UserRedirectRequiredException {
    OAuth2AccessToken accessToken = this.context.getAccessToken();
    if(accessToken == null || accessToken.isExpired()) {
        try {
            accessToken = this.acquireAccessToken(this.context);
        } catch (UserRedirectRequiredException var5) {
            this.context.setAccessToken((OAuth2AccessToken)null);
            accessToken = null;
            String stateKey = var5.getStateKey();
            if(stateKey != null) {
                Object stateToPreserve = var5.getStateToPreserve();
                if(stateToPreserve == null) {
                    stateToPreserve = "NONE";
                }

                this.context.setPreservedState(stateKey, stateToPreserve);
            }

            throw var5;
        }
    }

    return accessToken;
}
 
Example #11
Source File: FitbitShim.java    From shimmer with Apache License 2.0 6 votes vote down vote up
@Override
protected String getAuthorizationUrl(
        UserRedirectRequiredException exception,
        Map<String, String> additionalParameters) {

    final OAuth2ProtectedResourceDetails resource = getResource();

    // TODO this override won't work, see FitbitAccessTokenRequestEnhancer for details
    String redirectUrl = additionalParameters.get(REDIRECT_URL_KEY) == null
            ? getDefaultRedirectUrl()
            : additionalParameters.get(REDIRECT_URL_KEY);

    UriComponentsBuilder uriBuilder = UriComponentsBuilder
            .fromUriString(exception.getRedirectUri())
            .queryParam("response_type", "code")
            .queryParam("client_id", resource.getClientId())
            .queryParam("redirect_uri", redirectUrl)
            .queryParam("scope", Joiner.on(" ").join(resource.getScope()))
            .queryParam("state", exception.getStateKey())
            .queryParam("prompt", fitbitClientSettings.getPromptType().getQueryParameterValue());

    return uriBuilder.build().encode().toUriString();
}
 
Example #12
Source File: OAuth2Shim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
@Override
public AuthorizationRequestParameters getAuthorizationRequestParameters(
        String username,
        Map<String, String> additionalParameters)
        throws ShimException {

    OAuth2RestOperations restTemplate = restTemplate();

    try {
        // TODO replace with restTemplate.getAccessToken();
        trigger(restTemplate, getTriggerDataRequest());

        // if no exception has been thrown, assume that the current authorization is valid
        return AuthorizationRequestParameters.authorized();
    }
    catch (UserRedirectRequiredException e) {
        // if an exception was thrown it means a redirect is required
        AccessTokenRequest accessTokenRequest = restTemplate.getOAuth2ClientContext().getAccessTokenRequest();

        String stateKey = accessTokenRequest.getStateKey();

        /**
         * Build an authorization request from the exception
         * parameters. We also serialize spring's accessTokenRequest.
         */
        AuthorizationRequestParameters authRequestParams = new AuthorizationRequestParameters();
        authRequestParams.setRedirectUri(e.getRedirectUri());
        authRequestParams.setStateKey(e.getStateKey());
        authRequestParams.setAuthorizationUrl(getAuthorizationUrl(e, additionalParameters));
        authRequestParams.setSerializedRequest(SerializationUtils.serialize(accessTokenRequest));
        authRequestParams.setStateKey(stateKey);
        authRequestParams.setRequestParams(additionalParameters);

        return authorizationRequestParametersRepo.save(authRequestParams);
    }
}
 
Example #13
Source File: OAuth2FeignRequestInterceptor.java    From spring-cloud-security with Apache License 2.0 5 votes vote down vote up
/**
 * Try to acquire the token using a access token provider.
 * @return valid access token
 * @throws UserRedirectRequiredException in case the user needs to be redirected to an
 * approval page or login page
 */
protected OAuth2AccessToken acquireAccessToken()
		throws UserRedirectRequiredException {
	AccessTokenRequest tokenRequest = oAuth2ClientContext.getAccessTokenRequest();
	if (tokenRequest == null) {
		throw new AccessTokenRequiredException(
				"Cannot find valid context on request for resource '"
						+ resource.getId() + "'.",
				resource);
	}
	String stateKey = tokenRequest.getStateKey();
	if (stateKey != null) {
		tokenRequest.setPreservedState(
				oAuth2ClientContext.removePreservedState(stateKey));
	}
	OAuth2AccessToken existingToken = oAuth2ClientContext.getAccessToken();
	if (existingToken != null) {
		oAuth2ClientContext.setAccessToken(existingToken);
	}
	OAuth2AccessToken obtainableAccessToken;
	obtainableAccessToken = accessTokenProvider.obtainAccessToken(resource,
			tokenRequest);
	if (obtainableAccessToken == null || obtainableAccessToken.getValue() == null) {
		throw new IllegalStateException(
				" Access token provider returned a null token, which is illegal according to the contract.");
	}
	oAuth2ClientContext.setAccessToken(obtainableAccessToken);
	return obtainableAccessToken;
}
 
Example #14
Source File: MockAccessTokenProvider.java    From spring-cloud-security with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2AccessToken obtainAccessToken(
		OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails,
		AccessTokenRequest accessTokenRequest) throws UserRedirectRequiredException,
		UserApprovalRequiredException, AccessDeniedException {
	return token;
}
 
Example #15
Source File: MockAccessTokenProvider.java    From spring-cloud-security with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(
		OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails,
		OAuth2RefreshToken oAuth2RefreshToken, AccessTokenRequest accessTokenRequest)
		throws UserRedirectRequiredException {
	return null;
}
 
Example #16
Source File: RunkeeperShim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
@Override
protected String getAuthorizationUrl(UserRedirectRequiredException exception, Map<String, String> addlParameters) {

    final OAuth2ProtectedResourceDetails resource = getResource();

    UriComponentsBuilder uriBuilder = UriComponentsBuilder
            .fromUriString(exception.getRedirectUri())
            .queryParam("state", exception.getStateKey())
            .queryParam("client_id", resource.getClientId())
            .queryParam("response_type", "code")
            .queryParam("redirect_uri", getDefaultRedirectUrl());

    return uriBuilder.build().encode().toUriString();
}
 
Example #17
Source File: OpenIdAccessTokenProvider.java    From cola with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource, OAuth2RefreshToken refreshToken, AccessTokenRequest request) throws UserRedirectRequiredException {
	MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
	form.add("grant_type", "refresh_token");
	form.add("refresh_token", refreshToken.getValue());
	return retrieveToken(request, resource, form, new HttpHeaders());
}
 
Example #18
Source File: JawboneShim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
@Override
protected String getAuthorizationUrl(UserRedirectRequiredException exception, Map<String, String> addlParameters) {

    final OAuth2ProtectedResourceDetails resource = getResource();

    UriComponentsBuilder uriBuilder = UriComponentsBuilder
            .fromUriString(exception.getRedirectUri())
            .queryParam("state", exception.getStateKey())
            .queryParam("client_id", resource.getClientId())
            .queryParam("response_type", "code")
            .queryParam("scope", StringUtils.collectionToDelimitedString(resource.getScope(), " "))
            .queryParam("redirect_uri", getDefaultRedirectUrl());

    return uriBuilder.build().encode().toUriString();
}
 
Example #19
Source File: MisfitShim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
@Override
protected String getAuthorizationUrl(UserRedirectRequiredException exception, Map<String, String> addlParameters) {

    final OAuth2ProtectedResourceDetails resource = getResource();

    UriComponentsBuilder uriBuilder = UriComponentsBuilder
            .fromUriString(exception.getRedirectUri())
            .queryParam("state", exception.getStateKey())
            .queryParam("client_id", resource.getClientId())
            .queryParam("response_type", "code")
            .queryParam("scope", Joiner.on(',').join(resource.getScope()))
            .queryParam("redirect_uri", getDefaultRedirectUrl());

    return uriBuilder.build().encode().toUriString();
}
 
Example #20
Source File: GoogleFitShim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(
        OAuth2ProtectedResourceDetails resource,
        OAuth2RefreshToken refreshToken, AccessTokenRequest request)
        throws UserRedirectRequiredException,
        OAuth2AccessDeniedException {

    OAuth2AccessToken accessToken = super.refreshAccessToken(resource, refreshToken, request);
    // Google does not replace refresh tokens, so we need to hold on to the existing refresh token...
    if (accessToken.getRefreshToken() == null) {
        ((DefaultOAuth2AccessToken) accessToken).setRefreshToken(refreshToken);
    }
    return accessToken;
}
 
Example #21
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
private UserRedirectRequiredException getRedirectForAuthorization(AuthorizationCodeResourceDetails resource, AccessTokenRequest request) {
    TreeMap<String, String> requestParameters = new TreeMap();
    requestParameters.put("response_type", "code");
    requestParameters.put("client_id", resource.getClientId());
    String redirectUri = resource.getRedirectUri(request);
    if(redirectUri != null) {
        requestParameters.put("redirect_uri", redirectUri);
    }

    if(resource.isScoped()) {
        StringBuilder builder = new StringBuilder();
        List<String> scope = resource.getScope();
        if(scope != null) {
            Iterator scopeIt = scope.iterator();

            while(scopeIt.hasNext()) {
                builder.append((String)scopeIt.next());
                if(scopeIt.hasNext()) {
                    builder.append(' ');
                }
            }
        }

        requestParameters.put("scope", builder.toString());
    }

    UserRedirectRequiredException redirectException = new UserRedirectRequiredException(resource.getUserAuthorizationUri(), requestParameters);
    String stateKey = this.stateKeyGenerator.generateKey(resource);
    redirectException.setStateKey(stateKey);
    request.setStateKey(stateKey);
    redirectException.setStateToPreserve(redirectUri);
    request.setPreservedState(redirectUri);
    return redirectException;
}
 
Example #22
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource, OAuth2RefreshToken refreshToken, AccessTokenRequest request) throws UserRedirectRequiredException, OAuth2AccessDeniedException {
    MultiValueMap<String, String> form = new LinkedMultiValueMap();
    form.add("grant_type", "refresh_token");
    form.add("refresh_token", refreshToken.getValue());
    form.add("appid", resource.getClientId());

    try {
        return this.retrieveToken(request, resource, form, this.getHeadersForTokenRequest(request));
    } catch (OAuth2AccessDeniedException var6) {
        throw this.getRedirectForAuthorization((AuthorizationCodeResourceDetails)resource, request);
    }
}
 
Example #23
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails details, AccessTokenRequest request) throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException, OAuth2AccessDeniedException {
    AuthorizationCodeResourceDetails resource = (AuthorizationCodeResourceDetails)details;
    System.out.println(request.getCurrentUri());
    if(request.getAuthorizationCode() == null) {
        if(request.getStateKey() == null) {
            throw this.getRedirectForAuthorization(resource, request);
        }

        this.obtainAuthorizationCode(resource, request);
    }
    System.out.println("code == " + request.getAuthorizationCode());
    return this.retrieveToken(request,
            resource, this.getParametersForTokenRequest(resource, request), this.getHeadersForTokenRequest(request));
}
 
Example #24
Source File: MyOAuth2RestTemplate.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
protected OAuth2AccessToken acquireAccessToken(OAuth2ClientContext oauth2Context) throws UserRedirectRequiredException {
    AccessTokenRequest accessTokenRequest = oauth2Context.getAccessTokenRequest();
    if (accessTokenRequest != null) {
        System.out.println("accesstokeRequest == " + accessTokenRequest.getCurrentUri());
    }
    if(accessTokenRequest == null) {
        throw new AccessTokenRequiredException("No OAuth 2 security context has been established. Unable to access resource '" + this.resource.getId() + "'.", this.resource);
    } else {
        String stateKey = accessTokenRequest.getStateKey();
        if(stateKey != null) {
            System.out.println("stateKey == " + stateKey);
            accessTokenRequest.setPreservedState(oauth2Context.removePreservedState(stateKey));
        }

        OAuth2AccessToken existingToken = oauth2Context.getAccessToken();
        if(existingToken != null) {
            accessTokenRequest.setExistingToken(existingToken);
        }

        OAuth2AccessToken accessToken = null;
        accessToken = this.accessTokenProvider.obtainAccessToken(this.resource, accessTokenRequest);
        if(accessToken != null && accessToken.getValue() != null) {
            oauth2Context.setAccessToken(accessToken);
            return accessToken;
        } else {
            throw new IllegalStateException("Access token provider returned a null access token, which is illegal according to the contract.");
        }
    }
}
 
Example #25
Source File: CustomImplicitAccessTokenProvider.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(
        OAuth2ProtectedResourceDetails resource,
        OAuth2RefreshToken refreshToken, AccessTokenRequest request)
        throws UserRedirectRequiredException {
    return null;
}
 
Example #26
Source File: CustomImplicitAccessTokenProvider.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken obtainAccessToken(
        OAuth2ProtectedResourceDetails details, AccessTokenRequest request)
        throws RuntimeException {

    ImplicitResourceDetails resource = (ImplicitResourceDetails) details;

    Map<String, String> requestParameters = getParametersForTokenRequest(
            resource, request);

    UserRedirectRequiredException redirectException = new UserRedirectRequiredException(
            resource.getUserAuthorizationUri(), requestParameters);

    throw redirectException;
}
 
Example #27
Source File: UserInfoTokenServicesTests.java    From spring-security-oauth2-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void badToken() {
	this.services.setRestTemplate(this.template);
	given(this.template.getForEntity(any(String.class), eq(Map.class)))
			.willThrow(new UserRedirectRequiredException("foo:bar", Collections.<String, String>emptyMap()));
	this.expected.expect(InvalidTokenException.class);
	assertThat(this.services.loadAuthentication("FOO").getName()).isEqualTo("unknown");
}
 
Example #28
Source File: AcAccessTokenProvider.java    From cola with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource, OAuth2RefreshToken refreshToken, AccessTokenRequest request) throws UserRedirectRequiredException {
	MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
	form.add("grant_type", "refresh_token");
	form.add("refresh_token", refreshToken.getValue());
	return retrieveToken(request, resource, form, new HttpHeaders());
}
 
Example #29
Source File: AuthorizationCodeGrantTests.java    From spring-boot-demo with MIT License 4 votes vote down vote up
@Test
void testAttemptedTokenAcquisitionWithNoRedirect() {
    AuthorizationCodeAccessTokenProvider provider = new AuthorizationCodeAccessTokenProvider();
    assertThrows(UserRedirectRequiredException.class,
        () -> provider.obtainAccessToken(resource, new DefaultAccessTokenRequest()));
}
 
Example #30
Source File: AuthorizationCodeGrantTests.java    From spring-boot-demo with MIT License 4 votes vote down vote up
@Test
void testCannotConnectWithoutToken() {
    OAuth2RestTemplate template = new OAuth2RestTemplate(resource);
    assertThrows(UserRedirectRequiredException.class,
        () -> template.getForObject(getUrl("/oauth/me"), String.class));
}