我正在构建一个 Web 应用程序,它将在单个应用程序中包含一个 API 和一个管理界面。因此,我需要两种类型的身份验证,API 的基于 token 的身份验证和管理界面的基于表单的身份验证。
我几乎已经通过应用过滤器来验证 API token 来实现它,但是过滤器正在为每个请求执行,我只希望它在匹配“/api/**”的路径上执行。
希望从我的安全配置中可以清楚地看出我要做什么,但遗憾的是它没有按预期工作。
所有 API 请求将以“/api/”开头,而所有管理界面请求将以“/admin/”开头。所以我希望对每个应用不同的安全规则。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/api/account/login").permitAll();
http.addFilterBefore(webServiceAuthenticationFilter, UsernamePasswordAuthenticationFilter.class).authorizeRequests().antMatchers("/api/**").hasAuthority("APIUSER");
http.authorizeRequests().antMatchers("/admin/**").authenticated().and()
.formLogin()
.loginPage("/admin/account/login").permitAll()
.passwordParameter("password")
.usernameParameter("username")
.failureUrl("/admin/account/login?error").permitAll()
.defaultSuccessUrl("/admin/dashboard")
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/admin/account/logout"))
.logoutSuccessUrl("/admin/account/login");
http.exceptionHandling().accessDeniedPage("/admin/account/forbidden");
}
最佳答案
有一种方法可以配置几个HttpSecurity
s 依赖于使用 antMatcher
的 url (或者在更高级的情况下 requestMatchers
)直接在 HttpSecurity 上(而不是在 authorizeRequests
上!)。见:https://docs.spring.io/spring-security/site/docs/current/apidocs/org/springframework/security/config/annotation/web/builders/HttpSecurity.html#antMatcher-java.lang.String-
这需要定义几个 WebSecurityConfigurerAdapter
s 已定义 @Order
s 以便 Spring 根据给定的 url 和配置的顺序使用第一个适当的配置。有关更多详细信息,请查看文档 http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity
关于Spring Boot 安全性,仅对某些路由应用身份验证过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38876558/