I have a simple web application which uses the default Spring Security form authentication and, once authenticated, the user is allowed to browse between Thymeleaf views and access content.
I'm able to provide JSON for REST client applications instead of web views, for the same endpoint, simply by using Spring mapping like this:
// response for web application, thymeleaf views
@RequestMapping("/fruits", produces = MediaType.TEXT_HTML_VALUE)
public String index(Model model) {
model.addAttribute("fruits", fruits);
return "fruitsView";
}
// response for REST client applications
@RequestMapping("/fruits", produces = MediaType.APPLICATION_JSON_VALUE)
public Fruits[] index() {
return fruits;
}
The problem is: is it possible to accept Basic Authentication instead of responding with a login web form when the request accepts JSON (Accept header field) instead of first accepting HTML?
My security configuration:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// works well for web views:
http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin();
// works well for REST clients:
// http.authorizeRequests().antMatchers("/**").hasRole("USER").and().httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
}
Is it possible to configure both httpBasic and formLogin authentication in the way each one responds for a specif Accept content type header field?
I've learned that it's possible to have two different authentications for different URL patterns: Spring REST security - Secure different URLs differently. But how about two different authentication mechanisms for the same URL where the requests are differentiated by Accept content header field?