【发布时间】:2019-09-18 05:21:50
【问题描述】:
在为此苦苦挣扎了几天(搜索类似问题,反复试验)后,我很想放弃......
所以问题是我有一个基于 Spring Boot 的 REST 服务,使用 Spring Security 和 JWT 进行身份验证。现在我想确保某些方法只能由使用@PreAuthorize-annotation 的授权人员调用。
这似乎有效,部分原因是 Spring 没有调用方法,而是返回 404。我本来期望 403。
我已阅读此SO-question 并尝试了那里给出的答案,但没有帮助。我已按照其他地方的建议将 @EnableGlobalMethodSecurity(prePostEnabled = true)-Annotation 从我的 SecurityConfiguration 移动到 Application 类,但它仍然不起作用。
我的安全配置如下所示:
@Configuration
@Profile("production")
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Value("${adDomain}")
private String adDomain;
@Value("${adUrl}")
private String adUrl;
@Value("${rootDn}")
private String rootDn;
@Value("${searchFilter}")
private String searchFilter;
private final AuthenticationManagerBuilder auth;
private final SessionRepository sessionRepository;
@Autowired
public SecurityConfiguration(AuthenticationManagerBuilder auth, SessionRepository sessionRepository) {
this.auth = auth;
this.sessionRepository = sessionRepository;
}
@Override
public void configure(WebSecurity webSecurity) throws Exception
{
webSecurity
.ignoring()
// All of Spring Security will ignore the requests
.antMatchers("/static/**", "/api/web/logout")
.antMatchers(HttpMethod.POST, "/api/web/login");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable() // Using JWT there is no need for CSRF-protection!
.authorizeRequests()
.anyRequest().authenticated()
.and()
.addFilter(new JwtAuthorizationFilter(authenticationManagerBean(), sessionRepository));
}
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
ActiveDirectoryLdapAuthenticationProvider adProvider =
new ActiveDirectoryLdapAuthenticationProvider(adDomain, adUrl, rootDn);
adProvider.setConvertSubErrorCodesToExceptions(true);
adProvider.setUseAuthenticationRequestCredentials(true);
adProvider.setSearchFilter(searchFilter);
adProvider.setUserDetailsContextMapper(new InetOrgPersonContextMapper());
auth.authenticationProvider(adProvider);
return super.authenticationManagerBean();
}
}
控制器方法如下所示
@RequestMapping(path = "/licenses", method = RequestMethod.GET)
@PreAuthorize("hasRole('ADMIN')")
public ResponseEntity<?> getAllLicenses(@RequestParam("after") int pagenumber, @RequestParam("size") int pagesize
, @RequestParam("searchText") String searchText) {
List<LicenseDTO> result = ...
return new ResponseEntity<Object>(result, HttpStatus.OK);
}
我很确定我遗漏了一些非常简单的东西,但我就是不知道是什么。
顺便说一句:如果请求许可证的用户具有 ADMIN 角色,那么一切都按预期工作,所以问题不是真正的 404。
【问题讨论】:
-
确切的 Spring Security 响应是什么?
-
响应正文中没有任何内容。只是标题中的 404 状态。在进行更多调试时,我发现一开始有 403。它只是在过滤器链的上游更改为 404。
标签: java spring-boot spring-security