org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails Java Examples

The following examples show how to use org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails. 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: Oauth2ClientRestTemplate.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 演示 grant_type=authorization_code 时,获取资源的方法
 * -
 *
 * @param client_id
 * @param client_secret     取决于 AuthorizationServer 设置,如果 client 设置了secret,则此项参数为必需,否则可以没有
 * @param access_token_uri
 * @param authorization_uri
 * @param scope
 * @return
 */

public OAuth2RestOperations authorizationCodeRestTemplate(String client_id, String client_secret, String authorization_uri, String access_token_uri, String... scope) {

    // 防止 url 写错
    if (!access_token_uri.contains("token") || !authorization_uri.contains("authorize"))
        throw new RuntimeException("uri is wrong :  access_token_uri = " + access_token_uri + " , authorization_uri" + authorization_uri);


    AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
    details.setId("1");
    details.setClientId(client_id);
    if (client_secret != null && !client_secret.isEmpty())
        details.setClientSecret(client_secret);
    details.setAccessTokenUri(access_token_uri);
    details.setUserAuthorizationUri(authorization_uri);
    details.setUseCurrentUri(true); //将当前请求的 uri 作为参数 redirect_uri 接受返回值。设置为 faslse 是,需要设置 redirect_uri 参数, details.setPreEstablishedRedirectUri("http://anywhere");
    details.setScope(Arrays.asList(scope));
    return new OAuth2RestTemplate(details, oAuth2ClientContext);
}
 
Example #2
Source File: OAuth2Util.java    From DAFramework with MIT License 6 votes vote down vote up
public static Filter general(AuthorizationCodeResourceDetails client, ResourceServerProperties resourceServerProperties, String path, OAuth2ClientContext oauth2ClientContext) {
	OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationFilter = new OAuth2ClientAuthenticationProcessingFilter(path){
		protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
		                                        FilterChain chain, Authentication authResult) throws IOException, ServletException {
			super.successfulAuthentication(request, response, chain, authResult);
			OAuth2AccessToken accessToken = restTemplate.getAccessToken();
			log.warn(new Gson().toJson(authResult));
			log.warn(new Gson().toJson(accessToken));
		}
	};
	OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(client, oauth2ClientContext);
	oAuth2ClientAuthenticationFilter.setRestTemplate(oAuth2RestTemplate);
	UserInfoTokenServices tokenServices = new UserInfoTokenServices(resourceServerProperties.getUserInfoUri(), client.getClientId());
	tokenServices.setRestTemplate(oAuth2RestTemplate);
	oAuth2ClientAuthenticationFilter.setTokenServices(tokenServices);
	return oAuth2ClientAuthenticationFilter;
}
 
Example #3
Source File: OAuth2Util.java    From DAFramework with MIT License 6 votes vote down vote up
public static Filter wechat(AuthorizationCodeResourceDetails client, ResourceServerProperties resourceServerProperties, String path, OAuth2ClientContext oauth2ClientContext) {
	OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationFilter = new OAuth2ClientAuthenticationProcessingFilter(path);

	OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(client, oauth2ClientContext);
	AuthorizationCodeAccessTokenProvider accessTokenProvider = new AuthorizationCodeAccessTokenProvider();
	accessTokenProvider.setAuthorizationRequestEnhancer((request, resource, form, headers) -> {
		form.set("appid", resource.getClientId());
		form.set("secret", resource.getClientSecret());
		form.set("scope", "snsapi_userinfo");
		form.set("response_type", "code");
		form.set("#wechat_redirect", "");
	});
	accessTokenProvider.setMessageConverters(converters());
	oAuth2RestTemplate.setAccessTokenProvider(accessTokenProvider);

	oAuth2RestTemplate.setRetryBadAccessTokens(true);
	oAuth2ClientAuthenticationFilter.setRestTemplate(oAuth2RestTemplate);

	UserInfoTokenServices tokenServices = new UserInfoTokenServices(resourceServerProperties.getUserInfoUri(), client.getClientId());
	tokenServices.setRestTemplate(oAuth2RestTemplate);
	oAuth2ClientAuthenticationFilter.setTokenServices(tokenServices);
	return oAuth2ClientAuthenticationFilter;
}
 
Example #4
Source File: ClientConfiguration.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
@Bean
public AuthorizationCodeResourceDetails authorizationCode() {
    AuthorizationCodeResourceDetails resourceDetails = new AuthorizationCodeResourceDetails();

    resourceDetails.setId("oauth2server");
    resourceDetails.setTokenName("oauth_token");
    resourceDetails.setClientId("clientapp");
    resourceDetails.setClientSecret("123456");
    resourceDetails.setAccessTokenUri("http://localhost:8080/oauth/token");
    resourceDetails.setUserAuthorizationUri("http://localhost:8080/oauth/authorize");
    resourceDetails.setScope(Arrays.asList("read_profile"));
    resourceDetails.setPreEstablishedRedirectUri(("http://localhost:9000/callback"));
    resourceDetails.setUseCurrentUri(false);
    resourceDetails.setClientAuthenticationScheme(AuthenticationScheme.header);

    return resourceDetails;
}
 
Example #5
Source File: ClientConfiguration.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
@Bean
public OAuth2ProtectedResourceDetails authorizationCode() {
    AuthorizationCodeResourceDetails resourceDetails = new AuthorizationCodeResourceDetails();

    //@formatter:off
    resourceDetails.setId("oauth2server");
    resourceDetails.setTokenName("oauth_token");
    resourceDetails.setClientId("clientapp");
    resourceDetails.setClientSecret("123456");
    resourceDetails.setAccessTokenUri("http://localhost:8080/oauth/token");
    resourceDetails.setUserAuthorizationUri("http://localhost:8080/oauth/authorize");
    resourceDetails.setScope(Arrays.asList("read_profile"));
    resourceDetails.setPreEstablishedRedirectUri(("http://localhost:9000/callback"));
    resourceDetails.setUseCurrentUri(false);
    resourceDetails.setClientAuthenticationScheme(AuthenticationScheme.header);
    //@formatter:on

    return resourceDetails;
}
 
Example #6
Source File: ClientConfiguration.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
@Bean
public OAuth2ProtectedResourceDetails authorizationCode() {
    AuthorizationCodeResourceDetails resourceDetails = new AuthorizationCodeResourceDetails();

    //@formatter:off
    resourceDetails.setId("oauth2server");
    resourceDetails.setTokenName("oauth_token");
    resourceDetails.setClientId("clientapp");
    resourceDetails.setClientSecret("123456");
    resourceDetails.setAccessTokenUri("http://localhost:8080/oauth/token");
    resourceDetails.setUserAuthorizationUri("http://localhost:8080/oauth/authorize");
    resourceDetails.setScope(Arrays.asList("read_profile"));
    resourceDetails.setPreEstablishedRedirectUri(("http://localhost:9000/callback"));
    resourceDetails.setUseCurrentUri(false);
    resourceDetails.setClientAuthenticationScheme(AuthenticationScheme.header);
    //@formatter:on

    return resourceDetails;
}
 
Example #7
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 #8
Source File: IHealthShim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2ProtectedResourceDetails getResource() {

    AuthorizationCodeResourceDetails resource = (AuthorizationCodeResourceDetails) super.getResource();
    resource.setAuthenticationScheme(AuthenticationScheme.none);
    return resource;
}
 
Example #9
Source File: OAuth2Shim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
public OAuth2ProtectedResourceDetails getResource() {

        AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails();

        resource.setAccessTokenUri(getAccessTokenUrl());
        resource.setUserAuthorizationUri(getUserAuthorizationUrl());
        resource.setClientId(getClientSettings().getClientId());
        resource.setScope(getClientSettings().getScopes());
        resource.setClientSecret(getClientSettings().getClientSecret());
        resource.setUseCurrentUri(true);

        return resource;
    }
 
Example #10
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 #11
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
private MultiValueMap<String, String> getParametersForAuthorizeRequest(AuthorizationCodeResourceDetails resource, AccessTokenRequest request) {
    MultiValueMap<String, String> form = new LinkedMultiValueMap();
    form.set("response_type", "code");
    form.set("client_id", resource.getClientId());
    if(request.get("scope") != null) {
        form.set("scope", request.getFirst("scope"));
    } else {
        form.set("scope", OAuth2Utils.formatParameterList(resource.getScope()));
    }

    String redirectUri = resource.getPreEstablishedRedirectUri();
    Object preservedState = request.getPreservedState();
    if(redirectUri == null && preservedState != null) {
        redirectUri = String.valueOf(preservedState);
    } else {
        redirectUri = request.getCurrentUri();
    }

    String stateKey = request.getStateKey();
    if(stateKey != null) {
        form.set("state", stateKey);
        if(preservedState == null) {
            throw new InvalidRequestException("Possible CSRF detected - state parameter was present but no state could be found");
        }
    }

    if(redirectUri != null) {
        form.set("redirect_uri", redirectUri);
    }

    return form;
}
 
Example #12
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
private MultiValueMap<String, String> getParametersForTokenRequest(AuthorizationCodeResourceDetails resource, AccessTokenRequest request) {
        MultiValueMap<String, String> form = new LinkedMultiValueMap();
        String state = request.getStateKey();
//        if (state.contains("session")) {
//            form.set("appid", resource.getClientId());
//            form.set("secret", resource.getClientSecret());
//        } else {
//            form.set("appid", "wx38871ac04c8208af");
//            form.set("secret", "50f7e835165d91006bf32fb3ba8d53dd");
//        }
        form.set("appid", resource.getClientId());
        form.set("secret", resource.getClientSecret());
        form.set("code", request.getAuthorizationCode());
        form.set("grant_type", "authorization_code");
        Object preservedState = request.getPreservedState();
        //if((request.getStateKey() != null || this.stateMandatory) && preservedState == null) {
        if(false) {
            throw new InvalidRequestException("Possible CSRF detected - state parameter was required but no state could be found");
        } else {
            String redirectUri = null;
            if(preservedState instanceof String) {
                redirectUri = String.valueOf(preservedState);
            } else {
                redirectUri = resource.getRedirectUri(request);
            }

            if(redirectUri != null && !"NONE".equals(redirectUri)) {
                form.set("redirect_uri", redirectUri);
            }

            return form;
        }
    }
 
Example #13
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 #14
Source File: OAuth2Configuration.java    From oauth2lab with MIT License 5 votes vote down vote up
@Bean
public OAuth2ProtectedResourceDetails authorizationCode() {
    AuthorizationCodeResourceDetails details =
        new AuthorizationCodeResourceDetails();
    details.setId("oauth2server");
    details.setClientId("clientapp");
    details.setClientSecret("112233");
    details.setUseCurrentUri(true);
    details.setUserAuthorizationUri("http://localhost:8080/oauth/authorize");
    details.setAccessTokenUri("http://localhost:8080/oauth/token");
    return details;
}
 
Example #15
Source File: OAuth2Configuration.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Bean
public OAuth2ProtectedResourceDetails authorizationCode() {
    AuthorizationCodeResourceDetails details =
        new AuthorizationCodeResourceDetails();
    details.setId("oauth2server");
    details.setClientId("clientapp");
    details.setClientSecret("123");
    details.setUseCurrentUri(true);
    details.setUserAuthorizationUri("http://localhost:8080/oauth/authorize");
    details.setAccessTokenUri("http://localhost:8080/oauth/token");
    return details;
}
 
Example #16
Source File: GoogleConfiguration.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Bean
public OAuth2ProtectedResourceDetails resourceDetails() {
    AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
    details.setClientId(properties.getClientId());
    details.setClientSecret(properties.getClientSecret());

    // URLs retrieved from https://accounts.google.com/.well-known/openid-configuration
    details.setUserAuthorizationUri("https://accounts.google.com/o/oauth2/v2/auth");
    details.setAccessTokenUri("https://www.googleapis.com/oauth2/v4/token");
    details.setPreEstablishedRedirectUri("http://localhost:8080/google/callback");
    details.setScope(Arrays.asList("openid", "email", "profile"));
    details.setUseCurrentUri(false);

    return details;
}
 
Example #17
Source File: GoogleConfiguration.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Bean
public OAuth2ProtectedResourceDetails resourceDetails() {
    AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
    details.setClientId(properties.getClientId());
    details.setClientSecret(properties.getClientSecret());

    // URLs retrieved from https://accounts.google.com/.well-known/openid-configuration
    details.setUserAuthorizationUri("https://accounts.google.com/o/oauth2/v2/auth");
    details.setAccessTokenUri("https://www.googleapis.com/oauth2/v4/token");
    details.setPreEstablishedRedirectUri("http://localhost:8080/google/callback");
    details.setScope(Arrays.asList("openid", "email", "profile"));
    details.setUseCurrentUri(false);
    return details;
}
 
Example #18
Source File: FacebookConfiguration.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Bean
public OAuth2ProtectedResourceDetails resourceDetails() {
    AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
    details.setClientId(properties.getClientId());
    details.setClientSecret(properties.getClientSecret());
    details.setUserAuthorizationUri(properties.getAppAuthorizationUri());
    details.setAccessTokenUri(properties.getAppTokenUri());
    details.setPreEstablishedRedirectUri(properties.getRedirectUri());
    details.setScope(Arrays.asList("email", "public_profile"));
    details.setClientAuthenticationScheme(AuthenticationScheme.query);
    details.setUseCurrentUri(false);
    return details;
}
 
Example #19
Source File: UserInfoTokenServicesRefreshTokenTests.java    From spring-security-oauth2-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void withRestTemplateChangesState() {
	OAuth2ProtectedResourceDetails resource = new AuthorizationCodeResourceDetails();
	OAuth2ClientContext context = new DefaultOAuth2ClientContext();
	context.setAccessToken(new DefaultOAuth2AccessToken("FOO"));
	this.services.setRestTemplate(new OAuth2RestTemplate(resource, context));
	assertThat(this.services.loadAuthentication("BAR").getName()).isEqualTo("me");
	assertThat(context.getAccessToken().getValue()).isEqualTo("BAR");
}
 
Example #20
Source File: UserInfoTokenServicesRefreshTokenTests.java    From spring-security-oauth2-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void withRestTemplate() {
	OAuth2ProtectedResourceDetails resource = new AuthorizationCodeResourceDetails();
	OAuth2ClientContext context = new DefaultOAuth2ClientContext();
	DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken("FOO");
	token.setRefreshToken(new DefaultExpiringOAuth2RefreshToken("BAR", new Date(0L)));
	context.setAccessToken(token);
	this.services.setRestTemplate(new OAuth2RestTemplate(resource, context));
	assertThat(this.services.loadAuthentication("FOO").getName()).isEqualTo("me");
	assertThat(context.getAccessToken().getValue()).isEqualTo("FOO");
	// The refresh token is still intact
	assertThat(context.getAccessToken().getRefreshToken()).isEqualTo(token.getRefreshToken());
}
 
Example #21
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 4 votes vote down vote up
public boolean supportsResource(OAuth2ProtectedResourceDetails resource) {
    return resource instanceof AuthorizationCodeResourceDetails && "authorization_code".equals(resource.getGrantType());
}
 
Example #22
Source File: SecurityConfig.java    From springboot-security-wechat with Apache License 2.0 4 votes vote down vote up
public AuthorizationCodeResourceDetails getClient() {
    return client;
}
 
Example #23
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 4 votes vote down vote up
protected UserApprovalRequiredException getUserApprovalSignal(AuthorizationCodeResourceDetails resource, AccessTokenRequest request) {
    String message = String.format("Do you approve the client '%s' to access your resources with scope=%s", new Object[]{resource.getClientId(), resource.getScope()});
    return new UserApprovalRequiredException(resource.getUserAuthorizationUri(), Collections.singletonMap("user_oauth_approval", message), resource.getClientId(), resource.getScope());
}
 
Example #24
Source File: SecurityConfig.java    From movie-db-java-on-azure with MIT License 4 votes vote down vote up
@Bean
@ConfigurationProperties("facebook.client")
public AuthorizationCodeResourceDetails facebook() {
    return new AuthorizationCodeResourceDetails();
}
 
Example #25
Source File: OAuth2ClientResources.java    From DAFramework with MIT License 4 votes vote down vote up
public AuthorizationCodeResourceDetails getClient() {
	return client;
}
 
Example #26
Source File: SpringSecurityConfiguration.java    From crnk-example with Apache License 2.0 4 votes vote down vote up
public AuthorizationCodeResourceDetails getClient() {
	return client;
}
 
Example #27
Source File: WebSecurityConfig.java    From docs-manage with MIT License 4 votes vote down vote up
@Bean
@ConfigurationProperties("spring.oauth2.client")
public OAuth2ProtectedResourceDetails resourceDetails() {
    return new AuthorizationCodeResourceDetails();
}
 
Example #28
Source File: WebSecurityConfig.java    From mojito with Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnProperty(value = "l10n.security.oauth2.enabled", havingValue = "true")
@ConfigurationProperties("l10n.security.oauth2.client")
public AuthorizationCodeResourceDetails oauth2() {
    return new AuthorizationCodeResourceDetails();
}
 
Example #29
Source File: OAuth2ProtectedResourceDetailsConfiguration.java    From spring-security-oauth2-boot with Apache License 2.0 4 votes vote down vote up
@Bean
@ConfigurationProperties(prefix = "security.oauth2.client")
@Primary
public AuthorizationCodeResourceDetails oauth2RemoteResource() {
	return new AuthorizationCodeResourceDetails();
}