I'm pretty new with Spring Security, so please, forgive any lack of clarity. I have this Spring boot project with Java configuration.
The project has a UI (my-app) with login form and a Rest API (my-app/api). I want to protect both with Spring Security, and I succeeded on protect the UI part. When an unauthorized user tries to request a forbidden resource, is redirected to login page. My problem is when I try to protect the Rest API. With the following setting I protect the UI part.
http
.authorizeRequests()
.antMatchers("/login", "/about", "/resource/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.failureUrl("/login?error=true")
.and()
.logout()
.logoutSuccessUrl("/login")
The UI is well protected and logout and login error redirects to login page, the only caveat is on forbidden access to the API, returns the login HTML text. With the next settings
http.antMatcher("/my-app/**")
.authorizeRequests().anyRequest().authenticated();
only API is protected, and on any unauthorized request, it returns a JSON with the error (which is the desired behaviour), and no a redirect/html text print. I know my API has been accessed with authentication because I use a Bearer token (Oauth2 password grant type) and works well.
I have a problem in mixing both settings in order to get the desired result.
Any suggestion is welcome.
You can use multiple http security configurations as defined at
https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity