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 ... -->


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 *