spring boot and react login with facebook - spring

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();
}
}

Related

Spring boot 3 multiple security filter chains doesn't work

I am using Spring Boot 3.0.1. In my WebSecurityConfig class, I want to filter 2 types of api urls.
So I have 2 SecurityFilterChains. This is what I want to achieve.
1.) Login api: This one, I want to permit this url and save the session id to the database using Spring Sessions.
2.) Other white apis: I want to permit some urls without any security/session checks
3.) Any other api calls need to have the x-auth-token
The following code has only 1 SecurityFilterChain and it works perfectly fine to satisfy all the above 1,2,3 points.
For 1, it will create the session id in the spring_session table with the login user as the principal_name.
For 2, it will also create another session id in spring_session table with "client" as the principal_name.
I do not want to create a session id for 2. I only want to create session id when I call the 1 (login api). So I believe that I have to write 2 Filter chains. First one only for login api and create session id, second one for all the white apis to go through with out security/session checks.
How do I write 2 security filter chains?
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class WebSecurityConfig {
#Autowired
private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private AuthenticationFailureHandler authenticationFailureHandler;
#Autowired
private PasswordEncoder passwordEncoder;
#Bean
public AuthenticationManager authenticationManager(HttpSecurity http)
throws Exception {
var daoAC = new DaoAuthenticationConfigurer(userDetailsService);
daoAC.passwordEncoder(passwordEncoder);
var builder = http.getSharedObject(AuthenticationManagerBuilder.class);
builder.apply(daoAC);
return builder.build();
}
private static final String[] AUTH_WHITELIST = {
"/api/usermanager/auth/login",
"/api/usermanager/auth/app-login",
"/api/usermanager/auth/resetPassword",
"/api/usermanager/auth/health",
"/api/usermanager/back-office/login",
"/actuator/**",
"/get-user-names",
"/get-users",
"/get-user",
"/api/usermanager/users/activate",
"/actuator/**",
"/health/**",
"/api/usermanager/org",
"/api/usermanager/org/*/theme",
"/api/usermanager/image/org/*/all",
"/api/usermanager/image/org/*/logo.png"
};
#Bean
public SecurityFilterChain loginFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable().exceptionHandling()
.authenticationEntryPoint(restAuthenticationEntryPoint)
.and().securityContext((securityContext) -> securityContext.requireExplicitSave(false))
.cors()
.and()
.httpBasic()
.and()
.securityMatcher("/api/**")
.authorizeHttpRequests(
requests -> requests.
requestMatchers(AUTH_WHITELIST).permitAll()
.anyRequest().authenticated()
).httpBasic(withDefaults())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.sessionFixation()
.migrateSession()
.maximumSessions(1)
.expiredUrl("/sessionExpired.html")
.maxSessionsPreventsLogin(false));
return http.build();
}
#Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().requestMatchers(HttpMethod.GET,
"/docs/**", "/resources/**", "/static/**", "/img/**");
}
#Bean
public AuthenticationFailureHandler myFailureHandler() {
return new CustomAuthenticationFailureHandler();
}
#Bean
public HttpSessionIdResolver httpSessionStrategy() {
return HeaderHttpSessionIdResolver.xAuthToken();
}
#Bean
public HttpSessionIdResolver httpSessionIdResolver() {
return HeaderHttpSessionIdResolver.xAuthToken();
}
#Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
}
Create more SecurityFilterChain Bean and add #Order(1) and #Order(2) annotations.
Check the Spring docs: https://docs.spring.io/spring-security/reference/servlet/architecture.html#servlet-securityfilterchain

EnableOAuth2Sso Access token expires after 1 hour of activity and UserRedirectRequiredException thrown

I have implemented SSO using spring-security-oauth2-autoconfigure 2.1.8.RELEASE and it works fine on first launch. I am able to login and call my backend api.
After one hour of activity, the REST calls to my backend api fails due to UserRedirectRequiredException because the access token has expired and OAuth2RestTemplate is unable to refresh it. I get this stack:
org.springframework.security.oauth2.client.resource.UserRedirectRequiredException: A redirect is required to get the users approval
at org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider.getRedirectForAuthorization(AuthorizationCodeAccessTokenProvider.java:359)
at org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider.obtainAccessToken(AuthorizationCodeAccessTokenProvider.java:205)
at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainNewAccessTokenInternal(AccessTokenProviderChain.java:148)
at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainAccessToken(AccessTokenProviderChain.java:121)
at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:221)
at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:173)
My App Configuration code is:
#Configuration
#EnableOAuth2Sso
#Order(value = 0)
public class AppConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private Environment env;
#Autowired
OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails;
#Autowired
OAuth2ClientContext oauth2ClientContext;
#Autowired
private OAuth2ClientContextFilter oauth2ClientContextFilter;
#Value("${security.oauth2.resource.user-info-uri}")
private String userInfoUri;
#Value("${security.oauth2.client.access-token-uri}")
private String accessTokenUri;
#Value("${security.oauth2.client.user-authorization-uri}")
private String userAuthorizationUri;
#Value("${security.oauth2.client.client-id}")
private String clientID;
#Value("${security.oauth2.client.client-secret}")
private String clientSecret;
#Value("${security.oauth2.client.pre-established-redirect-uri}")
private String preEstRedirectUri;
#Value("#{'${security.oauth2.client.scope}'.split(' ')}")
private List<String> scope;
#Override
public void configure(HttpSecurity http) throws Exception {
String logoutUrl = env.getProperty("endSessionEndpoint") + "?post_logout_redirect_uri=" +
URLEncoder.encode(env.getProperty("homePage"), "UTF-8");
http.requiresChannel().anyRequest().requiresSecure();
http.antMatcher("/**")
.authorizeRequests(a -> a
.antMatchers("/", "/static/**", "/webjars/**", "/login**", "/error**", "/js/**", "/css/**", "/img/**").permitAll()
.anyRequest().authenticated()
)
.csrf(c -> c
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
)
.logout(l -> l
.deleteCookies()
.invalidateHttpSession(true)
.logoutSuccessUrl(logoutUrl)
);
http.addFilterAfter(oauth2ClientContextFilter, SecurityContextPersistenceFilter.class);
http.addFilterBefore(swqSSOFilter(), BasicAuthenticationFilter.class);
http.exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint());
}
private Filter swqSSOFilter() {
private Filter swqSSOFilter() {
OAuth2ClientAuthenticationProcessingFilter azureSsoFilter = new OAuth2ClientAuthenticationProcessingFilter(preEstRedirectUri);
OAuth2RestTemplate oauth2RestTemplate = new OAuth2RestTemplate(oAuth2ProtectedResourceDetails, oauth2ClientContext);
azureSsoFilter.setRestTemplate(oauth2RestTemplate);
UserInfoTokenServices tokenServices = new UserInfoTokenServices(userInfoUri, oAuth2ProtectedResourceDetails.getClientId());
tokenServices.setRestTemplate(oauth2RestTemplate);
azureSsoFilter.setTokenServices(tokenServices);
return azureSsoFilter;
}
#Bean
public AuthenticationEntryPoint unauthorizedEntryPoint() {
return (request, response, authException) -> response.sendRedirect(preEstRedirectUri);
}
#Bean
public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext, OAuth2ProtectedResourceDetails details) {
return new OAuth2RestTemplate(details, oauth2ClientContext);
}
#Bean
public FilterRegistrationBean<OAuth2ClientContextFilter> oauth2ClientFilterRegistration(
OAuth2ClientContextFilter filter) {
FilterRegistrationBean<OAuth2ClientContextFilter> registration = new FilterRegistrationBean<OAuth2ClientContextFilter>();
registration.setFilter(filter);
registration.setOrder(-100);
return registration;
}
}
I followed a lot of stackoverflow posts, but none of the solutions worked for me.
Can someone advise what I am doing wrong?
Moving answer from comments,
To be specific in order to increase your token lifetime you need to implement refresh token in your code.Please refer ms docs.

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;
}

Spring security OAuth parsing the response into an object

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

Resources