Rest 如何避免在spring security中为非安全URL运行自定义筛选器
我正在构建一个基于REST的web应用程序,我已经成功地将spring安全性应用于它,但我担心的是我已经添加了一个自定义过滤器Rest 如何避免在spring security中为非安全URL运行自定义筛选器,rest,spring-security,spring-boot,Rest,Spring Security,Spring Boot,我正在构建一个基于REST的web应用程序,我已经成功地将spring安全性应用于它,但我担心的是我已经添加了一个自定义过滤器 http .authorizeRequests() .antMatchers("/mypro/userCont/signup").permitAll() .and() .addFilterBefore(new CustomFilter(), UsernamePasswordAuthenticationFil
http
.authorizeRequests()
.antMatchers("/mypro/userCont/signup").permitAll()
.and()
.addFilterBefore(new CustomFilter(), UsernamePasswordAuthenticationFilter.class)
.httpBasic();
我希望这个过滤器应该只为安全的url运行,而不是为不安全的url运行。如果它为非安全的url运行,那么它不应该打断我获取非安全url上的资源。
我的场景是,如果用户未登录安全url,则应运行自定义筛选器,使用以下代码检查主体
:
Authentication auth = (Authentication) SecurityContextHolder.getContext().getAuthentication();
如果auth
为null
用户将看到默认的spring安全登录弹出窗口
如果我点击了不安全的url,我应该可以访问资源。
有人能帮我吗。通过配置
WebSecurity
,您可以完全跳过特定资源的安全性。在这种情况下,Spring security将完全忽略该URL模式:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity webSecurity) throws Exception
{
webSecurity
.ignoring()
.antMatchers("/resources/**"); //skip security entirely
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.addFilter(mycustomFilter)
.authorizeRequests().anyRequest()
.and()
.httpBasic();
}
}
或者,您只需使用permitAll()
方法排除您需要的匿名访问
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.addFilter(mycustomFilter)
.authorizeRequests()
.antMatchers("/not-secured/**").permitAll()
.and()
.httpBasic();
}
}