【发布时间】:2017-07-31 22:22:08
【问题描述】:
我有一个简单的 Web 应用程序,它使用默认的 Spring Security 表单身份验证,一旦通过身份验证,用户就可以在 Thymeleaf 视图之间浏览并访问内容。
我能够为 REST 客户端应用程序提供 JSON,而不是 Web 视图,对于同一个端点,只需使用这样的 Spring 映射:
// 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;
}
问题是:当请求接受 JSON(Accept 标头字段)而不是首先接受 HTML 时,是否可以接受基本身份验证而不是使用登录 Web 表单进行响应?
我的安全配置:
@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");
}
}
是否可以同时配置 httpBasic 和 formLogin 身份验证,以分别响应特定的 Accept 内容类型标头字段?
我了解到对于不同的 URL 模式可以有两种不同的身份验证:Spring REST security - Secure different URLs differently。但是对于同一个 URL 的两种不同的身份验证机制,其中请求由 Accept 内容头字段区分,怎么样?
【问题讨论】:
-
@dur 尝试过
.formLogin().and().httpBasic()。通过浏览器访问时,我得到了预期的登录表单。但是在通过其他客户端访问时,将 application/json 作为 Accept 标头字段,如果未通过身份验证,我可以访问内容。 -
@dur 虽然您删除了您的评论,但您是对的:客户端工具是一个浏览器插件,因此它会发送浏览器 cookie。当没有发送 cookie 时,
.formLogin().and().httpBasic()在通过浏览器访问端点时使用表单登录身份验证和 http 基本身份验证非常有效,同时像 REST API 一样使用端点。问题解决了!谢谢!
标签: java spring rest spring-mvc spring-security