I tried to implement a SecurityConfig similar to https://stackoverflow.com/a/33608459 and https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity
I want my API ( /rest/**
) to be secured by HttpBasic, and other requests via FormLogin. This works well... as long as I provide the correct credentials to HttpBasic.
If I provide correct credentials - it response with normal answer.
If I provide no credentials - it responds with a 401 Unauthorized
- perfect!
If I provide wrong credentials - it responds with a 302 Found
with Location: /login
The last part is what I don't want - I also want a 401 Unauthorized on wrong credentials.
http http://localhost:8081/rest/
HTTP/1.1 401
WWW-Authenticate: Basic realm="My Realm"
http -a correct:password http://localhost:8081/rest/some/api/
HTTP/1.1 200
http -a wrong:password http://localhost:8081/rest/some/api/
HTTP/1.1 302
Location: http://hive.local:8081/login WWW-Authenticate: Basic realm="My Realm"
@Configuration
@Order(1)
public static class RestSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthorizationProperties properties;
@Override protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http.antMatcher("/rest/**")
.authorizeRequests()
.anyRequest().hasRole("API").and()
.httpBasic()
.realmName(properties.getRealm()).and()
.formLogin().disable()
.csrf().disable();
// @formatter:on
}
}
@Configuration
@Order(2)
public static class FrontendSecurityConfig extends WebSecurityConfigurerAdapter {
@Override public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/app/**", "/webjars/**", "/static/**", "/js/**");
}
@Override protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().hasAnyRole("USER").and()
.formLogin();
// @formatter:on
}
}
I was able to bring some light into this.
The redirect to form login after a failed basic auth request is cause by the dispatcher servlet trying to redirect to the URL /error
after failing to validate the credentials.
To get the appropriate error response you need to add /error
to the antMatchers
that are ignored in your web security config.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.