Spring security OAuth parsing the response into an object - spring

I'm new to spring.
I have been following http://spring.io/guides/tutorials/spring-boot-oauth2/ using google oauth in place of facebook.
I am able to return the principle as described in the tutorial, which sends to the browser the json returned by the api call and can use this client side.
#RestController
public class UserControllers {
#RequestMapping("/user")
public Principal user(Principal principal) {
return principal;
}
}
But how would I use this data on the server side? Suppose I wanted just to return the email address on the /user route? Or maybe I want to further populate the Principal with information from a database?
Below is the code I use to set up the oauth authentication.
#EnableWebSecurity
#EnableOAuth2Client
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
OAuth2ClientContext oauth2ClientContext;
#Override
protected void configure(HttpSecurity http) throws Exception {
http .csrf().disable()
.logout().logoutSuccessUrl("/").permitAll() //logout logic handled by spring
.and()
.antMatcher("/**")
.authorizeRequests()
.antMatchers("/", "/login**", "/webjars/**", "/user")
.permitAll()
.anyRequest().authenticated()
.and().exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/"))
.and()
.addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
}
#Bean
public FilterRegistrationBean oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(filter);
registration.setOrder(-100);
return registration;
}
protected Filter ssoFilter() {
CompositeFilter filter = new CompositeFilter();
List<Filter> filters = new ArrayList<>();
filters.add(constructFilter("/login/google", google(), googleResource()));
filter.setFilters(filters);
return filter;
}
private Filter constructFilter(String endpoint, OAuth2ProtectedResourceDetails clientDetails, ResourceServerProperties resourceDetails) {
OAuth2ClientAuthenticationProcessingFilter filter = new CustomOauth2AuthFilter(endpoint);
OAuth2RestTemplate template = new OAuth2RestTemplate(clientDetails, oauth2ClientContext);
filter.setRestTemplate(template);
filter.setTokenServices(new UserInfoTokenServices(resourceDetails.getUserInfoUri(), clientDetails.getClientId()));
return filter;
}
/*
/Returns a new AuthorizationCodeResourceDetails object configured with the properties from the application.yml file
*/
#Bean
#ConfigurationProperties("google.client")
OAuth2ProtectedResourceDetails google() {
return new AuthorizationCodeResourceDetails();
}
/*
/Returns a new ResourceServerProperties object configured with the properties from the application.yml file
*/
#Bean
#ConfigurationProperties("google.resource")
ResourceServerProperties googleResource() {
return new ResourceServerProperties();
}
}
Thanks in advance,
Dan

Related

receiving null when trying to get connected user from Principal interface

I created some apis and I protected them using jwt, authntication part is working well and I can validate the token when I get it from the header, now I want to add some role based rules, to get them I need to pass the email information from the token to another api.
The problem is that when I try to get information from the token using Principal interface I got a null response, here is the security config :
#EnableWebSecurity(debug = true)
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Value("${security.allowed-origin:*}")
private String allowedOriginPattern;
#Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
private String jwtSetUri;
#Bean
JwtDecoder jwtDecoder() {
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwtSetUri).build();
return jwtDecoder;
}
#Override
public void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests(authRequests - > {
// Permissions on your endpoints
authRequests.mvcMatchers(HttpMethod.OPTIONS).permitAll();
// Management endpoints
authRequests.mvcMatchers("/management/**", "/docs/**", "/webjars/**").permitAll();
// else
authRequests.anyRequest().authenticated();
});
http.oauth2ResourceServer().jwt();
http.cors()
.and()
.cors().and()
.csrf().disable()
.exceptionHandling()
.accessDeniedHandler(securityAccessDeniedHandler())
.authenticationEntryPoint(securityAuthEntryPoint());
}
#Bean
CorsConfigurationSource corsConfigurationSource() {
var corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedHeaders(List.of("*"));
corsConfiguration.setAllowedMethods(List.of("*"));
corsConfiguration.setAllowedOriginPatterns(List.of("*"));
var source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return source;
}
#Bean
public AccessDeniedHandler securityAccessDeniedHandler() {
return new SecurityAccessDeniedHandler();
}
#Bean
public AuthenticationEntryPoint securityAuthEntryPoint() {
return new SecurityAuthEntryPoint();
}
}
and here is the api :
#GetMapping("/user")
public String getConnectedUser(Principal principal) {
// principal is null here
return principal.getName();
}

Spring boot Security, Oauth2 replace access token with long-lived token from facebook

I have been following Dave Syer astounding tutorial to implement OAuth2 in microservices which provide RESTful APIs for mobile devices (Android and iOS). I have configured gateway security with the following code:
#SpringBootApplication
#EnableDiscoveryClient
#EnableZuulProxy
#EnableCircuitBreaker
#EnableFeignClients
#EnableOAuth2Client
public class GatewayApplication extends WebSecurityConfigurerAdapter {
private OAuth2ClientContext oauth2ClientContext;
private SimpleUrlAuthenticationSuccessHandler simpleUrlAuthenticationSuccessHandler;
private ScoreAuthorizationFilter scoreAuthorizationFilter;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.antMatcher("/**")
.authorizeRequests()
.antMatchers("/", "/test", "/login**", "/webjars/**", "/error**")
.permitAll()
.anyRequest()
.authenticated()
.and().logout().logoutSuccessUrl("/").permitAll()
.and().addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class)
.addFilterBefore(scoreAuthorizationFilter, BasicAuthenticationFilter.class)
;
}
private Filter ssoFilter() {
OAuth2ClientAuthenticationProcessingFilter facebookFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/facebook");
OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(facebook(), oauth2ClientContext);
facebookFilter.setRestTemplate(facebookTemplate);
UserInfoTokenServices tokenServices = new UserInfoTokenServices(facebookResource().getUserInfoUri(), facebook().getClientId());
tokenServices.setRestTemplate(facebookTemplate);
facebookFilter.setTokenServices(tokenServices);
facebookFilter.setAuthenticationSuccessHandler(simpleUrlAuthenticationSuccessHandler);
return facebookFilter;
}
#Bean
#ConfigurationProperties("facebook.client")
public AuthorizationCodeResourceDetails facebook() {
return new AuthorizationCodeResourceDetails();
}
#Bean
#ConfigurationProperties("facebook.resource")
public ResourceServerProperties facebookResource() {
return new ResourceServerProperties();
}
#Bean
public FilterRegistrationBean<OAuth2ClientContextFilter> oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
FilterRegistrationBean<OAuth2ClientContextFilter> registration = new FilterRegistrationBean<OAuth2ClientContextFilter>();
registration.setFilter(filter);
registration.setOrder(-100);
return registration;
}
#Bean
public RequestInterceptor getFeignClientInterceptor() {
return new FeignClientInterceptor();
}
}
It turns out that the user's session expires after a while. As I dug a little deeper, I found out that Facebook doesn't provide refresh tokens. Instead, we can exchange a short-lived token for a long-lived token (Facebook long-lived token). How can I override the standard OAuth2 flow implemented in Spring Security to send another request to Facebook for getting the long-lived token and then replacing the old access token?
You can achieve what you want by extending the OAuth2ClientAuthenticationProcessingFilter class like this:
public class CustomAuthenticationProcessingFilter extends OAuth2ClientAuthenticationProcessingFilter {
private ResourceServerTokenServices tokenServices;
private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new OAuth2AuthenticationDetailsSource();
private ApplicationEventPublisher eventPublisher;
private AuthorizationCodeResourceDetails facebook;
private String longLivedTokenUri;
public CustomAuthenticationProcessingFilter(String defaultFilterProcessesUrl) {
super(defaultFilterProcessesUrl);
setAuthenticationDetailsSource(authenticationDetailsSource);
}
#Override
public void setTokenServices(ResourceServerTokenServices tokenServices) {
this.tokenServices = tokenServices;
super.setTokenServices(tokenServices);
}
#Override
public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
super.setApplicationEventPublisher(eventPublisher);
}
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
OAuth2AccessToken accessToken;
try {
accessToken = restTemplate.getAccessToken();
} catch (OAuth2Exception e) {
BadCredentialsException bad = new BadCredentialsException("Could not obtain access token", e);
publish(new OAuth2AuthenticationFailureEvent(bad));
throw bad;
}
String longLivedToken = getFromFacebook(); //Get long lived token from facebook here
try {
OAuth2Authentication result = tokenServices.loadAuthentication(longLivedToken);
if (authenticationDetailsSource != null) {
request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, longLivedToken);
request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, accessToken.getTokenType());
result.setDetails(authenticationDetailsSource.buildDetails(request));
}
publish(new AuthenticationSuccessEvent(result));
return result;
} catch (InvalidTokenException e) {
BadCredentialsException bad = new BadCredentialsException("Could not obtain user details from token", e);
publish(new OAuth2AuthenticationFailureEvent(bad));
throw bad;
}
}
private void publish(ApplicationEvent event) {
if (eventPublisher != null) {
eventPublisher.publishEvent(event);
}
}
}
I hope this helps.

spring boot and react login with facebook

I have spring rest api and react frontned application. I want to facilitate user to authenticate with facebook. After successful authentication i use facebookId to check if that user is in my database, if he isn't i create a user and save him. It's the only way to create accounts in my application. I used this tutorial to create authentication, and it's works fine...
But two days ago i decided that i want to connect my backend with frontend and I am unable to send request to protected endpoint. When i do it, my request is redirected to /connect/facebook(with OPTIONS request method - have no idea why) and nothing happen.
I read about that i should generate tokens, but I have no idea how to associate it with facebook, and I don't even know if it is a good approach.
edit.
#Order(200)
#Configuration
#EnableOAuth2Client
#EnableAuthorizationServer
#RequiredArgsConstructor
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final OAuth2ClientContext oauth2ClientContext;
private final AuthSuccessHandler customAuthenticationSuccessHandler;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/login**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login/facebook"))
.and()
.logout().logoutSuccessUrl("/").permitAll()
.and()
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
}
#Bean
public FilterRegistrationBean<OAuth2ClientContextFilter> oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
var registration = new FilterRegistrationBean<OAuth2ClientContextFilter>();
registration.setFilter(filter);
registration.setOrder(-100);
return registration;
}
private Filter ssoFilter() {
var filter = new CompositeFilter();
List<Filter> filters = new ArrayList<>();
filters.add(ssoFilter(facebook()));
filter.setFilters(filters);
return filter;
}
private Filter ssoFilter(ClientResources client) {
var filter = new OAuth2ClientAuthenticationProcessingFilter("/login/facebook");
var template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
filter.setRestTemplate(template);
var tokenServices = new UserInfoTokenServices(client.getResource().getUserInfoUri(), client.getClient().getClientId());
tokenServices.setRestTemplate(template);
filter.setTokenServices(tokenServices);
filter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler);
return filter;
}
#Bean
#ConfigurationProperties("facebook")
public ClientResources facebook() {
return new ClientResources();
}
}

OAuth 2 with spring security and setting the State parameter in the redirect

I am using Spring boot with Spring security, with custom "Filter" Class calling to CIAM server with OAuth 2 authentication. I want to set explicitly or override the default setting so that I could set custom dynamic STATE parameter in the redirect URL that Spring Security prepares under the hood and sends the user to the CIAM server login page. This seamed trivial to me but it turned out to be far from that.
The goal is to add the custom STATE parameter of the OAuth2 redirect link so that after the authentication is finished and the CIAM server redirects me back to my page I take back the STATE parameter which is automatically included in the successful redirect link from the CIAM server.
The Security configuration
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true,
proxyTargetClass = true)
#EnableOAuth2Client
#Order(3)
public class OAuth2LoginWebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
CiamOAuth2ClientFilter oAuth2CiamClientFilter;
#Bean
public InMemoryUserDetailsManager inMemoryUserDetailsManager() {
return new InMemoryUserDetailsManager();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/**/*.css", "/**/*.png", "/**/*.gif", "/**/*.jpg", "/h2-console/**", "/css/**",
"/img/**", "/font-awesome/**", "/fonts/**", "/js/**", "/signout","/signout/**", "/health");
}
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.antMatcher("/**")
.authorizeRequests()
.antMatchers("/user/**").hasRole("USER")
.antMatchers("/backoffice/**").hasRole("ADMIN")
.antMatchers("/api/**").hasRole("API")
.antMatchers(/*"/", */"/login**", "/webjars/**", "/favicon.*", "/resources/**",
"/auth/**", "/signin/**","css/**","js/**", "/signup/**", "/signout/", "/health", "/awsTest/login")
.permitAll()
.anyRequest()
.authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login/callback"))
.and()
.addFilterBefore(oAuth2CiamClientFilter.ciamFilter(), BasicAuthenticationFilter.class)
.logout()
.logoutUrl("/signout")
.logoutSuccessUrl("/logout");
}
}
The custom filter class
#Configuration
public class CiamOAuth2ClientFilter {
#Autowired
AuthorizationCodeResourceDetails oauth2CiamResourceDetails;
#Autowired
CiamOAuth2ClientProperties oauth2CiamClientProperties;
#Autowired
OAuth2ClientContext oauth2ClientContext;
#Autowired
CiamPrincipalExtractor ciamPrincipalExtractor;
#Bean
public FilterRegistrationBean oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(filter);
registration.setOrder(-100);
registration.addInitParameter("test", "trrrrrrr");
System.out.println("333333333333333333333333");
System.out.println(registration);
return registration;
}
public Filter ciamFilter() {
System.out.println("postaeget");
System.out.println(oauth2CiamClientProperties);
System.out.println(" _-------------------------------: " + oauth2CiamClientProperties.getResource().getUserInfoUri());
UserInfoTokenServices tokenService = new UserInfoTokenServices(oauth2CiamClientProperties.getResource().getUserInfoUri(), oauth2CiamResourceDetails.getClientId());
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(oauth2CiamResourceDetails, oauth2ClientContext);
OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter("/login/callback");
tokenService.setRestTemplate(restTemplate);
tokenService.setPrincipalExtractor(ciamPrincipalExtractor);
filter.setRestTemplate(restTemplate);
filter.setTokenServices(tokenService);
return filter;
}
}
Application yml settings file connected with the issue
security:
oauth2:
client:
clientId: ...
clientSecret: ....
accessTokenUri: ...
userAuthorizationUri: ...
useCurrentUri: false
preEstablishedRedirectUri: https://localhost/login/callback
clientAuthenticationScheme: query
authenticationScheme: header
serverLogoutUrl: ..
postLogoutRedirectUri: https://localhost/signout
scope:
- openid
- profile
- email
- offline_access
state: TEST
resource:
userInfoUri: ...
preferTokenInfo: ...
In my case
I configure OAuth2ClientAuthenticationProcessingFilter somewhere in #Configuration:
private Filter ssoFilter() {
OAuth2ClientAuthenticationProcessingFilter facebookFilter = new OAuth2ClientAuthenticationProcessingFilter(API_LOGIN_FACEBOOK);
OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(facebook(), oauth2ClientContext);
AuthorizationCodeAccessTokenProvider authorizationCodeAccessTokenProviderWithUrl = new AuthorizationCodeAccessTokenProvider();
authorizationCodeAccessTokenProviderWithUrl.setStateKeyGenerator(new StateKeyGeneratorWithRedirectUrl());
facebookTemplate.setAccessTokenProvider(authorizationCodeAccessTokenProviderWithUrl);
facebookFilter.setRestTemplate(facebookTemplate);
UserInfoTokenServices tokenServices = new CheckedUserInfoTokenServices(
facebookResource().getUserInfoUri(), facebook().getClientId(),
facebookPrincipalExtractor, blogPreAuthenticationChecks(), blogPostAuthenticationChecks());
tokenServices.setAuthoritiesExtractor(new FacebookAuthoritiesExtractor());
tokenServices.setRestTemplate(facebookTemplate);
facebookFilter.setTokenServices(tokenServices);
facebookFilter.setAuthenticationSuccessHandler(new OAuth2AuthenticationSuccessHandler());
return facebookFilter;
}
And you can access to current request in StateKeyGeneratorWithRedirectUrl with:
RequestContextHolder.getRequestAttributes()
so you can extract Referer header for example:
public class StateKeyGeneratorWithRedirectUrl extends DefaultStateKeyGenerator {
private RandomValueStringGenerator generator = new RandomValueStringGenerator();
#Override
public String generateKey(OAuth2ProtectedResourceDetails resource) {
HttpServletRequest currentHttpRequest = getCurrentHttpRequest();
if (currentHttpRequest!=null){
String referer = currentHttpRequest.getHeader("Referer");
if (!StringUtils.isEmpty(referer)){
return generator.generate()+","+referer;
}
}
return generator.generate();
}
private static HttpServletRequest getCurrentHttpRequest(){
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
return ((ServletRequestAttributes)requestAttributes).getRequest();
}
return null;
}
}
Next - read state from callback:
public class OAuth2AuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
public static final String DEFAULT = "/";
#Override
protected String determineTargetUrl(HttpServletRequest request,
HttpServletResponse response) {
UriComponents uriComponents = UriComponentsBuilder.newInstance()
.query(request.getQueryString())
.build();
MultiValueMap<String, String> queryParams = uriComponents.getQueryParams();
String stateEncoded = queryParams.getFirst("state");
if (stateEncoded == null) {
return DEFAULT;
}
String stateDecoded = URLDecoder.decode(stateEncoded, StandardCharsets.UTF_8);
String[] split = stateDecoded.split(",");
String redirect;
if (split.length != 2){
return DEFAULT;
} else {
return split[1];
}
}
}

Spring Oauth 2 Facebook Authentication Redirects User To My Home Page

I am trying to redirect a user who have been authenticated to another page other than the home page. I am using spring boot 1.5.6 and Oauth 2. User is authenticated but was redirected to the home page. I don't understand why this is happening. Please, someone should help me. Some answers to related problem on stackoverflow and the internet didn't help me.
Here is my SecurityConfig file
#Configuration
#EnableGlobalAuthentication
#EnableOAuth2Client
#EnableGlobalMethodSecurity(prePostEnabled = true)
#Order(2)
public class SecurityConfig extends WebSecurityConfigurerAdapter{
protected final Log logger = LogFactory.getLog(getClass());
#Autowired
private OAuth2ClientContext oauth2ClientContext;
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private GeneralConfig generalConfig;
#Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
#Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/user*")
.access("hasRole('CUSTOMER')")
.and()
.formLogin()
.loginPage("/loginUser")
.loginProcessingUrl("/user_login")
.failureUrl("/loginUser?error=loginError")
.defaultSuccessUrl("/customer/dashboard")
.and()
.logout()
.logoutUrl("/user_logout")
.logoutSuccessUrl("/loginUser").permitAll()
.deleteCookies("JSESSIONID")
.and()
.exceptionHandling()
.accessDeniedPage("/403")
.and()
.csrf().disable()
.addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).
passwordEncoder(bCryptPasswordEncoder());
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws
Exception {
auth.userDetailsService(userDetailsService);
}
#Bean
public FilterRegistrationBeanoauth2ClientFilterRegistration
(OAuth2ClientContextFilter filter) {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(filter);
registration.setOrder(-100);
return registration;
}
private Filter ssoFilter(ClientResources client, String path) {
OAuth2ClientAuthenticationProcessingFilter filter = new
OAuth2ClientAuthenticationProcessingFilter(path);
OAuth2RestTemplate template = new
OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
filter.setRestTemplate(template);
UserInfoTokenServices tokenServices = new
UserInfoTokenServices(client.getResource().getUserInfoUri(),
client.getClient().getClientId());
tokenServices.setRestTemplate(template);
filter.setTokenServices(tokenServices);
return filter;
}
private Filter ssoFilter() {
CompositeFilter filter = new CompositeFilter();
List<Filter> filters = new ArrayList<>();
filters.add(ssoFilter(facebook(), "/signin/facebook"));
filters.add(ssoFilter(google(), "/signin/google"));
filter.setFilters(filters);
return filter;
}
#Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
#ConfigurationProperties("google")
public ClientResources google() {
return new ClientResources();
}
#Bean
#ConfigurationProperties("facebook")
public ClientResources facebook() {
return new ClientResources();
}
}
From the SecurityConfig I expect the user upon successful authentication to be redirected to customer/dashboard so that I can do further processing. I know the user is authenticated because I can access their data. It's not just redirecting to the right page
But instead it keep redirecting the user to the home page. What am I doing wrong? I also have another Security Config File for admin. I can provide it if required.
To change the default strategy, you have to set an AuthenticationSuccessHandler, see AbstractAuthenticationProcessingFilter#setAuthenticationSuccessHandler:
Sets the strategy used to handle a successful authentication. By default a SavedRequestAwareAuthenticationSuccessHandler is used.
Your modified code:
private Filter ssoFilter(ClientResources client, String path) {
OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(path);
OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
filter.setRestTemplate(template);
UserInfoTokenServices tokenServices = new UserInfoTokenServices(client.getResource().getUserInfoUri(),client.getClient().getClientId());
tokenServices.setRestTemplate(template);
filter.setTokenServices(tokenServices);
filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/customer/dashboard")‌​;
return filter;
}

Resources