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的区别以及使用场景


@EnableWebSecurity
public 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”);


如下面两个例子:

@Override
public void configure(HttpSecurity http) throws Exception { 
        //只允许路由由test开头的需要进行权限认证,其他的接口不需要权限认证;requestMatchers().anyRequest()即所有接口可以不进行认证;  
  http
      .requestMatchers().anyRequest()
       .and().authorizeRequests().antMatchers("/test/*").authenticated();
}
@Override
public 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


1.png


相关文章
|
Java Spring 容器
解决Spring的UnsatisfiedDependencyException异常的方法
在Spring开发中,UnsatisfiedDependencyException异常意味着依赖注入失败,影响应用稳定性。该异常由Spring容器在无法满足bean依赖时抛出,常见原因包括bean定义错误、循环依赖、多个候选bean等。解决方法包括:检查bean定义和注入的正确性、解决循环依赖、确认依赖包的兼容性、使用@Qualifier或@Primary注解。通过日志、调试工具和异常对比来定位问题。持续学习Spring框架有助于更好地解决此类异常。
8826 1
最新jsonwebtoken-jjwt 0.12.3 基本使用
最新jsonwebtoken-jjwt 0.12.3 基本使用
2697 1
|
SQL JSON 安全
Spring Authorization Server OAuth2授权服务器配置详解
Spring Authorization Server OAuth2授权服务器配置详解
3795 0
|
安全 搜索推荐 Java
|
9月前
|
缓存 安全 Java
Spring Boot 3 集成 Spring Security + JWT
本文详细介绍了如何使用Spring Boot 3和Spring Security集成JWT,实现前后端分离的安全认证概述了从入门到引入数据库,再到使用JWT的完整流程。列举了项目中用到的关键依赖,如MyBatis-Plus、Hutool等。简要提及了系统配置表、部门表、字典表等表结构。使用Hutool-jwt工具类进行JWT校验。配置忽略路径、禁用CSRF、添加JWT校验过滤器等。实现登录接口,返回token等信息。
4046 13
Spring Boot 3 集成 Spring Security + JWT
|
SQL 安全 Java
揭秘Spring Boot安全防线:如何巧妙抵御XSS与SQL注入的双重威胁?
【8月更文挑战第29天】随着互联网技术的发展,Web应用已成为社会不可或缺的一部分。Spring Boot作为高效构建Web应用的框架备受青睐,但同时也面临安全挑战,如XSS攻击和SQL注入。本文介绍如何在Spring Boot应用中防范这两种常见安全漏洞。针对XSS攻击,可通过输入验证、输出编码及使用安全API来加强防护;对于SQL注入,则应利用预编译语句、参数化查询及最小权限原则来确保数据库安全。示例代码展示了具体实现方法,帮助开发者提升应用安全性。
980 2
|
安全 前端开发 Java
Spring Security 6.x 过滤器链SecurityFilterChain是如何工作的
上一篇主要介绍了Spring Secuirty中的过滤器链SecurityFilterChain是如何配置的,那么在配置完成之后,SecurityFilterChain是如何在应用程序中调用各个Filter,从而起到安全防护的作用,本文主要围绕SecurityFilterChain的工作原理做详细的介绍。
1109 0
Spring Security 6.x 过滤器链SecurityFilterChain是如何工作的
|
存储 安全 前端开发
SpringBoot整合Spring Security + JWT实现用户认证
SpringBoot整合Spring Security + JWT实现用户认证的实现
7011 2
SpringBoot整合Spring Security + JWT实现用户认证
|
关系型数据库 MySQL Java
异常:no transaction is in progress
异常:no transaction is in progress
366 0
|
前端开发 Java Spring
为什么会出现Request method ‘GET‘ not supported`
为什么会出现Request method ‘GET‘ not supported`
3564 1