SpringSecurity——HttpSecurity常用方法

SpringSecurity——HttpSecurity常用方法,第1张

SpringSecurity——HttpSecurity常用方法

文章目录

HttpSecurity 常用方法及说明HttpSecurity常用方法详解

antMatcher与antMatchers的区别以及使用场景requestMatchers()authorizeRequests()匹配规则

URL匹配保护URL登录login登出logout多个antMatchers在Spring

HttpSecurity 常用方法及说明

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

   
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 端口443jee()配置基于容器的预认证。 在这种情况下,认证由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
  @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 路径格式, 直接匹配urlanyRequest 匹配任意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 urllogoutSuccessUrl 登出成功后跳转的 url 默认是"/login?logout"logoutSuccessHandler 登出成功处理器,设置后会把logoutSuccessUrl 置为null 多个antMatchers在Spring

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5719775.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存