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


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

public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    public void configure(HttpSecurity http) throws Exception {
                .antMatchers("/", "/login**")

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


public class SecurityConfigAdapter extends WebSecurityConfigurerAdapter {

    private CustomUserDetailsService customUserDetailsService;

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

    protected void configure(HttpSecurity http) throws Exception {
                .antMatchers("/","/api/**", "/login", "/logout", "/register", "/fonts/**").permitAll()

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
                .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 ... -->

See ya!


  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!


Post a Comment

Popular posts from this blog

Deploy Spring Boot app in digitalocean cloud (or any cloud as long asyou have ssh access)

Upload large files : Spring Boot

User activity logging: Spring