> 文档中心 > SpringSecurity——HttpSecurity常用方法

SpringSecurity——HttpSecurity常用方法

文章目录

  • HttpSecurity 常用方法及说明
  • HttpSecurity常用方法详解
    • antMatcher与antMatchers的区别以及使用场景
    • requestMatchers()
    • authorizeRequests()
    • 匹配规则
      • URL匹配
      • 保护URL
      • 登录login
      • 登出logout
      • 多个antMatchers在Spring

HttpSecurity 常用方法及说明

通常我们在使用Spring Securty的时候会继 WebSecurityConfigurerAdapter,通过以下方法可配置拦截什么URL、设置什么权限等安全控制。

   /**     * 复写这个方法来配置 {@link HttpSecurity}.      * 通常,子类不能通过调用 super 来调用此方法,因为它可能会覆盖其配置。 默认配置为:     *      * http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();     *     */protected void configure(HttpSecurity http) throws Exception { http     .authorizeRequests()     .anyRequest().authenticated()     .and()     .formLogin().and()     .httpBasic();    }
方法 说明
openidLogin() 用于基于 OpenId 的验证
headers() 将安全标头添加到响应
cors() 配置跨域资源共享( CORS )
sessionManagement() 允许配置会话管理
portMapper() 允许配置一个PortMapper(HttpSecurity#(getSharedObject(class))),其他提供SecurityConfigurer的对象使用 PortMapper 从 HTTP 重定向到 HTTPS 或者从 HTTPS 重定向到 HTTP。默认情况下,Spring Security使用一个PortMapperImpl映射 HTTP 端口8080到 HTTPS 端口8443,HTTP 端口80到 HTTPS 端口443
jee() 配置基于容器的预认证。 在这种情况下,认证由Servlet容器管理
x509() 配置基于x509的认证
rememberMe 允许配置“记住我”的验证
authorizeRequests() 允许基于使用HttpServletRequest限制访问
requestCache() 允许配置请求缓存
exceptionHandling() 允许配置错误处理
securityContext() 在HttpServletRequests之间的SecurityContextHolder上设置SecurityContext的管理。 当使用WebSecurityConfigurerAdapter时,这将自动应用
servletApi() 将HttpServletRequest方法与在其上找到的值集成到SecurityContext中。 当使用WebSecurityConfigurerAdapter时,这将自动应用
csrf() 添加 CSRF 支持,使用WebSecurityConfigurerAdapter时,默认启用
logout() 添加退出登录支持。当使用WebSecurityConfigurerAdapter时,这将自动应用。默认情况是,访问URL”/ logout”,使HTTP Session无效来清除用户,清除已配置的任何#rememberMe()身份验证,清除SecurityContextHolder,然后重定向到”/login?success”
anonymous() 允许配置匿名用户的表示方法。 当与WebSecurityConfigurerAdapter结合使用时,这将自动应用。 默认情况下,匿名用户将使用org.springframework.security.authentication.AnonymousAuthenticationToken表示,并包含角色 “ROLE_ANONYMOUS”
formLogin() 指定支持基于表单的身份验证。如果未指定FormLoginConfigurer#loginPage(String),则将生成默认登录页面
oauth2Login() 根据外部OAuth 2.0或OpenID Connect 1.0提供程序配置身份验证
requiresChannel() 配置通道安全。为了使该配置有用,必须提供至少一个到所需信道的映射
httpBasic() 配置 Http Basic 验证
addFilterAt() 在指定的Filter类的位置添加过滤器

HttpSecurity常用方法详解

antMatcher与antMatchers的区别以及使用场景

@EnableWebSecuritypublic class MultiHttpSecurityConfig {  @Autowired  public void configureGlobal(AuthenticationManagerBuilder auth) { 1      auth   .inMemoryAuthentication()   .withUser("user").password("password").roles("USER").and()   .withUser("admin").password("password").roles("USER", "ADMIN");  }  @Configuration  @Order(1)2  public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {      protected void configure(HttpSecurity http) throws Exception {//这种情况下有两个HttpSecurity,未定义@Order就默认最后,多个未定义或者相同Order就按照定义顺序。需要/api/开头的url匹配Role为 Admin的User。//.antMatcher("/api/**") 过滤掉非/api/开头的请求,如果不用antMatcher,所有请求都会进入,进入的请求只有两条路,允许通过(permitall)//或者导向login(authenticated),但我们并不想处理   http.antMatcher("/api/**")   3.authorizeRequests().anyRequest().hasRole("ADMIN").and().httpBasic();      }  }    /*https://stackoverflow.com/questions/30819337/multiple-antmatchers-in-spring-security.antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/admin/login").permitAll()范围小的放在前面,范围大的放在后面,想法的话范围小的就不会匹配,按照范围大的处理。比如上面,/admin/login按照hasRole("ADMIN")处理。*/  @Configuration  4  public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {      @Override      protected void configure(HttpSecurity http) throws Exception {   http.authorizeRequests().anyRequest().authenticated().and().formLogin();      }  }}

requestMatchers()

取得RequestMatcherConfigurer对象并配置允许过滤的路由;
如requestMatchers().anyRequest()等同于http.authorizeRequests().anyRequest().access(“permitAll”);

如下面两个例子:

@Overridepublic void configure(HttpSecurity http) throws Exception { //只允许路由由test开头的需要进行权限认证,其他的接口不需要权限认证;requestMatchers().anyRequest()即所有接口可以不进行认证;http    .requestMatchers().anyRequest()     .and().authorizeRequests().antMatchers("/test/*").authenticated();}
@Overridepublic void configure(HttpSecurity http) throws Exception {//只有以/test 开头的路由需要进行权限认证;其他路由不需要权限认证http    .requestMatchers().antMatchers("/test/**")    .and().authorizeRequests().antMatchers("/**").authenticated();}
//springsecurity源码  如下 : pattern = "/**";  this.matcher = null;  说明 /** 就不需要进行请求匹配。public AntPathRequestMatcher(String pattern, String httpMethod, boolean caseSensitive, UrlPathHelper urlPathHelper) { Assert.hasText(pattern, "Pattern cannot be null or empty"); this.caseSensitive = caseSensitive; if (!pattern.equals("/**") && !pattern.equals("**")) {     if (pattern.endsWith("/**") && pattern.indexOf(63) == -1 && pattern.indexOf(123) == -1 && pattern.indexOf(125) == -1 && pattern.indexOf("*") == pattern.length() - 2) {  this.matcher = new AntPathRequestMatcher.SubpathMatcher(pattern.substring(0, pattern.length() - 3), caseSensitive);     } else {  this.matcher = new AntPathRequestMatcher.SpringAntMatcher(pattern, caseSensitive);     } } else {     pattern = "/**";     this.matcher = null; } this.pattern = pattern; this.httpMethod = StringUtils.hasText(httpMethod) ? HttpMethod.valueOf(httpMethod) : null; this.urlPathHelper = urlPathHelper;    }

authorizeRequests()

授权管理控制的方法(),这个方法返回一个ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry对象。Security所有的权限控制都基于这个类进行控制。
如:http.authorizeRequests().anyRequest().authenticated();要求所有接口都需要进行权限认证,这个类中的anyRequest()即所有接口,等同于 http.authorizeRequests().antMatchers("/").authenticated() ;

//所有接口都不需要权限认证http.authorizeRequests().antMatchers("/**").permitAll();//所有接口都不需要进行权限认证http.authorizeRequests().antMatchers("/**").authenticated();//只有以test开头的接口需要进行权限认证http.authorizeRequests().antMatchers("/test/**").authenticated();

http.authorizeRequests().antMatchers("/test/").hasRole(“user”).antMatchers("/").authenticated();在这个代码中要求以/test开头的路由需要进行角色认证(这里要求user角色),而其他接口只要登录即可访问。当我们需要配置多个角色时可以通过hasAnyRole方法配置多个角色的访问权限,如:

// 在这个代码中要求以/test开头的路由需要进行角色认证(这里要求user角色),而其他接口只要登录即可访问http.authorizeRequests().antMatchers("/test/**").hasAnyRole("user","admin").antMatchers("/**").authenticated();

匹配规则

URL匹配

  • requestMatchers() 配置一个request Mather数组,参数为RequestMatcher 对象,其match 规则自定义,需要的时候放在最前面,对需要匹配的的规则进行自定义与过滤
  • authorizeRequests() URL权限配置
  • antMatchers() 配置一个request Mather 的 string数组,参数为 ant 路径格式, 直接匹配url
  • anyRequest 匹配任意url,无参 ,最好放在最后面

保护URL

  • authenticated() 保护UrL,需要用户登录
  • permitAll() 指定URL无需保护,一般应用与静态资源文件
  • hasRole(String role) 限制单个角色访问,角色将被增加 “ROLE_” .所以”ADMIN” 将和 “ROLE_ADMIN”进行比较. 另一个方法是hasAuthority(String authority)
  • hasAnyRole(String… roles) 允许多个角色访问. 另一个方法是hasAnyAuthority(String… authorities)
  • access(String attribute) 该方法使用 SPEL, 所以可以创建复杂的限制 例如如access(“permitAll”), access(“hasRole(‘ADMIN’) and hasIpAddress(‘123.123.123.123’)”)
  • hasIpAddress(String ipaddressExpression) 限制IP地址或子网

登录login

  • formLogin() 基于表单登录
  • loginPage() 登录页
  • defaultSuccessUrl 登录成功后的默认处理页
  • failuerHandler登录失败之后的处理器
  • successHandler登录成功之后的处理器
  • failuerUrl登录失败之后系统转向的url,默认是this.loginPage + “?error”

登出logout

  • logoutUrl 登出url , 默认是/logout, 它可以是一个ant path url
  • logoutSuccessUrl 登出成功后跳转的 url 默认是"/login?logout"
  • logoutSuccessHandler 登出成功处理器,设置后会把logoutSuccessUrl 置为null

多个antMatchers在Spring

在这里插入图片描述