Spring security -- a common method of HttpSecurity

Posted by mirana on Fri, 28 Jan 2022 13:07:15 +0100

Common methods and descriptions of HttpSecurity

Usually, when using spring security, we will follow the WebSecurityConfigurerAdapter to configure security controls such as what URL to intercept and what permissions to set through the following methods.

   /**
     * Copy this method to configure {@ link HttpSecurity} 
     * Typically, a subclass cannot call this method by calling super because it may override its configuration. The default configuration is:
     * 
     * http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();
     *
     */
protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .formLogin().and()
            .httpBasic();
    }
methodexplain
openidLogin()For OpenId based authentication
headers()Add security header to response
cors()Configure cross domain resource sharing (CORS)
sessionManagement()Allows you to configure session management
portMapper()It is allowed to configure a PortMapper (httpsecurity # (getsharedobject (class)), and other objects that provide SecurityConfigurer can use PortMapper to redirect from HTTP to HTTPS or from HTTPS to http. By default, Spring Security uses a PortMapperImpl to map HTTP port 8080 to HTTPS port 8443 and HTTP port 80 to HTTPS port 443
jee()Configure container based pre authentication. In this case, authentication is managed by the Servlet container
x509()Configure x509 based authentication
rememberMeAllow configuration of "remember me" validation
authorizeRequests()Allow access restrictions based on using HttpServletRequest
requestCache()Allow configuration of request cache
exceptionHandling()Allow configuration error handling
securityContext()Set the management of SecurityContext on the SecurityContextHolder between HttpServletRequests. This applies automatically when using the WebSecurityConfigurerAdapter
servletApi()Integrate the HttpServletRequest method with the value found on it into the SecurityContext. This applies automatically when using the WebSecurityConfigurerAdapter
csrf()Add CSRF support. When using WebSecurityConfigurerAdapter, it is enabled by default
logout()Add logout support. This applies automatically when using the WebSecurityConfigurerAdapter. By default, access the URL "/ logout" to invalidate the HTTP Session, clear the user, clear any #rememberMe() authentication that has been configured, clear the SecurityContextHolder, and then redirect to "/ login?success”
anonymous()Allows you to configure the presentation of anonymous users. This applies automatically when used in conjunction with the WebSecurityConfigurerAdapter. By default, anonymous users will use org. Org springframework. security. authentication. Anonymousauthenticationtoken indicates and contains the role "ROLE_ANONYMOUS"
formLogin()Specifies that form based authentication is supported. If FormLoginConfigurer#loginPage(String) is not specified, a default login page is generated
oauth2Login()Configure authentication according to an external OAuth 2.0 or OpenID Connect 1.0 provider
requiresChannel()Configure channel security. For this configuration to be useful, at least one mapping to the desired channel must be provided
httpBasic()Configure Http Basic authentication
addFilterAt()Adds a Filter at the location of the specified Filter class

Detailed explanation of common methods of HttpSecurity

The difference between ant matcher and ant matchers and their usage scenarios

@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 {
//In this case, there are two HttpSecurity. If @ Order is not defined, it defaults. Finally, multiple undefined or identical orders are defined in Order. The url starting with / api / is required to match the User whose Role is Admin.
//. antMatcher("/api / * *") filters out requests that do not start with / api /. If antMatcher is not used, all requests will enter. There are only two ways to enter the request, which is allowed to pass (permitall)
//Or directed to login(authenticated), but we don't want to deal with it
          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()
Those with a small range are placed in the front and those with a large range are placed in the back. If you think about it, those with a small range will not match. Deal with them according to the large range.
For example, / admin/login is processed according to 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()

Obtain the RequestMatcherConfigurer object and configure the routes that can be filtered;
Such as requestmatchers() Anyrequest() is equivalent to http authorizeRequests(). anyRequest(). access(“permitAll”);

As shown in the following two examples:

@Override
public void configure(HttpSecurity http) throws Exception {	
        //Permission authentication is only allowed for routes starting with test, and permission authentication is not required for other interfaces; requestMatchers().anyRequest(), that is, all interfaces can not be authenticated;	
	http
	    .requestMatchers().anyRequest()
	     .and().authorizeRequests().antMatchers("/test/*").authenticated();
}

@Override
public void configure(HttpSecurity http) throws Exception {
	//Only routes starting with / test need permission authentication; Other routes do not require permission authentication
	http
	    .requestMatchers().antMatchers("/test/**")
	    .and().authorizeRequests().antMatchers("/**").authenticated();
}

//The source code of springsecurity is as follows: pattern = "/ * *"; this. matcher = null;   Note / * * there is no need for request matching.
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()

Authorization management control method (), which returns an expressionurlauthorizationconfigurator Expressionintercepturlregistry object. All Security permissions are controlled based on this class.
For example: http authorizeRequests(). anyRequest(). authenticated(); All interfaces are required to be authenticated. Anyrequest () in this class means all interfaces, which is equivalent to http authorizeRequests(). antMatchers("/"). authenticated() ;

//All interfaces do not require authority authentication
http.authorizeRequests().antMatchers("/**").permitAll();
//All interfaces do not need permission authentication
http.authorizeRequests().antMatchers("/**").authenticated();
//Only interfaces starting with test need permission authentication
http.authorizeRequests().antMatchers("/test/**").authenticated();

http.authorizeRequests().antMatchers("/test/").hasRole(“user”). antMatchers("/").authenticated(); In this code, the route starting with / test requires role authentication (user role is required here), and other interfaces can be accessed as long as you log in. When we need to configure multiple roles, we can configure the access permissions of multiple roles through hasAnyRole method, such as:

// In this code, the route starting with / test requires role authentication (user role is required here), and other interfaces can be accessed as long as you log in
http.authorizeRequests().antMatchers("/test/**").hasAnyRole("user","admin").antMatchers("/**").authenticated();

Matching rules

URL match

  • requestMatchers() configures a request matcher array with the parameter RequestMatcher object. Its match rules are customized and placed in the front when necessary to customize and filter the rules to be matched
  • authorizeRequests() URL permission configuration
  • antMatchers() configures a string array of request Mather, and the parameter is in ant path format, which directly matches the url
  • anyRequest matches any url and has no parameters. It's best to put it at the end

Protect URL

  • authenticated() protects URLs and requires user login
  • permitAll() specifies that the URL does not need to be protected. It is generally applied to static resource files
  • hasRole(String role) restricts the access of a single ROLE, and the ROLE will be added "ROLE_" So "ADMIN" will be compared with "ROLE_ADMIN" Another method is hasAuthority(String authority)
  • hasAnyRole(String... roles) allows multiple roles to access Another method is hasAnyAuthority(String... authorities)
  • access(String attribute) this method uses SPEL, so you can create complex restrictions, such as access("permitAll"), access("hasRole('ADMIN ') and hasIpAddress('123.123.123')")
  • hasIpAddress(String ipaddressExpression) restricts the IP address or subnet

Login login

  • formLogin() login based on form
  • Login page
  • defaultSuccessUrl is the default processing page after successful login
  • Processor after failuerHandler login failure
  • The processor after successHandler successfully logs in
  • failuerUrl the url the system turns to after login failure. The default is this loginPage + “?error”

logout

  • logoutUrl logout url. The default is / logout. It can be an ant path url
  • logoutSuccessUrl the url to jump after successful logout is "/ login?logout" by default
  • logoutSuccessHandler logs out of the processor successfully. After setting, it will set logoutSuccessUrl to null

Multiple antMatchers in Spring

Topics: Java Spring Boot