我有使用REST API的Spring应用程序。
在我的WebSecurityConfig中,我有配置访问路径。
这些是我的主要路线:
我最后有两个问题。根据我的代码的变化,我有“/ api / admin / **”路由可供所有人或任何人(甚至ADMIN)访问。是否有可能实现或者我应该将最后的路线更改为“/ api / common / **”(然后它工作正常)?
这是我的代码的一部分:
@Override
protected void configure(HttpSecurity http) throws Exception {
AjaxLoginFilter ajaxLoginFilter = ajaxLoginFilter();
http
.cors()
.and()
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(this.authenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/auth/login").permitAll()
.and()
.authorizeRequests()
.antMatchers("/api/**")
.authenticated()
.and()
.addFilterBefore(ajaxLoginFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(jwtTokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/api/admin/**")
.hasRole("ADMIN")
.and()
.addFilterBefore(ajaxLoginFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(jwtTokenAuthenticationFilterAdmin(), UsernamePasswordAuthenticationFilter.class);
}
protected JwtTokenAuthenticationFilter jwtTokenAuthenticationFilter() throws Exception {
List<String> pathsToSkip = Arrays.asList("/api/auth/login", "/api/admin/**");
SkipPathRequestMatcher matcher = new SkipPathRequestMatcher(pathsToSkip, "/api/**");
JwtTokenAuthenticationFilter filter
= new JwtTokenAuthenticationFilter(failureHandler, tokenExtractor, matcher);
filter.setAuthenticationManager(this.authenticationManager);
return filter;
}
protected JwtTokenAuthenticationFilter jwtTokenAuthenticationFilterAdmin() throws Exception {
List<String> pathsToSkip = Arrays.asList("/api/auth/login", "/api/**");
SkipPathRequestMatcher matcher = new SkipPathRequestMatcher(pathsToSkip, "/api/admin/**");
JwtTokenAuthenticationFilter filter
= new JwtTokenAuthenticationFilter(failureHandler, tokenExtractor, matcher);
filter.setAuthenticationManager(this.authenticationManager);
return filter;
}
在上面的代码中,任何人都无法访问“/ api / admin / **”。如果我从方法 jwtTokenAuthenticationFilterAdmin()中的 pathsToSkip 列表中删除“/ api / **”,并将过滤器移至admin,则每个人都可以访问它。
所以问题是 - 我可以解决这个问题,或者我应该将任何经过身份验证的用户可以访问的路径从“/ api / **”更改为“/ api / common / ** “
答案 0 :(得分:1)
请勿重复致电authorizeRequests()
,即:
...
.authorizeRequests()
.antMatchers("/api/auth/login").permitAll()
.antMatchers("/api/admin/**").hasRole("ADMIN")
.antMatchers("/api/**").authenticated()
.and()
.addFilterBefore(ajaxLoginFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(jwtTokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
...