Spring Security: Using OAuth2 and web security both in same project

Hi,

I’ve been experiencing a pretty annoying trouble using both web security and OAuth2. I implemented OAuth2 first for my rest api and then when I tried form login using, it was giving an error and user wans’t logged in.

So I dug a bit deeper in google and found the solution. It wan’t the problem of configuration, it was a silly mistake that wasn’t suppose to happen.

Anyway I’m posting both Resource Server and Web security config classed here.

Configure Resource Server

(ResourceServer.java)

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .antMatcher("/api/**")
                .authorizeRequests()
                .antMatchers("/", "/login**")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and().logout().logoutSuccessUrl("/").permitAll();
    }
}
Putting .antMatcher(“/api/**”).authorizeRequests()¬† after http is like telling ResourseServer to start authorising all of the requests after /api endpoint.

And it’s needed for resource server to be able to imply security interceptors of spring security oAuth.

Configure WebSecurity

SecurityConfigAdapter.java

@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfigAdapter extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
                .ignoring()
                .antMatchers("/resources/**", "/fonts/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/","/api/**", "/login", "/logout", "/register", "/fonts/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login")
                .failureUrl("/login?error")
                .permitAll()
                .and()
                .rememberMe()
                .key("whatever");
        http
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login")
                .deleteCookies("JSESSIONID")
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(this.customUserDetailsService)
                .passwordEncoder(new ShaPasswordEncoder(256));
    }
}

Notice one thing, I’ve included¬†@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)

in WebSecurity configuration. Why is that? Because we are giving WebSecurity highest priority with it as this order was changed after an earlier spring security version(might be spring boot 1.5 or something).

You need to exclude /api, /login, /logout endpoints from here too. So that you aren’t in an infinity loop trying to login forever!

Hope that works. Oh, fyi, you need to add those dependencies:

Maven Dependencies

<!-- ... SPRING SECURITY ... -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>

 

A Sample Implementation

You can see my implementation on github for this project. It’s a skeleton project, so you can just clone it and start building.

This project includes built in mechanism for authentication, firebase push, mail, FileUpload, account validation, activity logging etc.

See ya!

3 thoughts on “Spring Security: Using OAuth2 and web security both in same project

  1. Wow that was strange. I just wrote an very long comment but after
    I clicked submit my comment didn't appear. Grrrr…
    well I'm not writing all that over again. Anyway, just wanted to say wonderful blog!

  2. Can you please share a sample code either on github. I need to understand the complete follow of this. As I am facing the same issue.

Leave a Reply

Your email address will not be published. Required fields are marked *