Spring Security combat (seven) - cross-domain request forgery protection and single sign-on

1. CSRF

        CSRF (Cross-Site Request Forgery, cross-site request forgery) is a common network attack method that uses users to forge requests (such as in pictures or links on another website) when they are already logged in to the website, Send malicious requests to the website to perform certain operations without the user's knowledge, such as changing passwords, sending private messages, etc.

To prevent CSRF attacks, you can take the following measures:

  1. Verify the source of the request: Verify the source of the request on the server side. If the source of the request is inconsistent with expectations, the request can be rejected. For example, in Spring Security it is possible to automatically verify the origin of requests by enabling CSRF protection.

  2. Use a random CSRF token: Include a random CSRF token in each form or request, the server side validates the token, and rejects the request if the token is not as expected. For example, in Spring Security, you can use CSRF Token to achieve this functionality.

  3. Restrict access to sensitive operations: For some sensitive operations, such as changing passwords and sending private messages, you can restrict only logged-in users from performing operations, or perform secondary verification on the operations, such as requiring users to enter passwords or SMS verification codes.

  4. Avoid using GET requests for sensitive operations: GET requests are usually used to obtain resources, while POST requests are usually used to submit data. If a GET request is used for sensitive operations, the browser or proxy server may cache the request result, allowing an attacker to forge the request through the preloaded cache.

2. Use Spring Security to defend against CSRF attacks

        CSRF attacks are completely based on the browser. If the front end of our system is not operating in the browser, CSRF should be turned off.

(1) Add CSRF Token: Spring Security can automatically generate CSRF Token and add it to all form requests and non-GET requests. Validation is performed on the server side, and if the tokens do not match, the request is rejected. It can be configured by the following code:

protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}

(2) SameSite Cookie: SameSite Cookie is a technology that can limit Cookie cross-site access, and can effectively prevent CSRF attacks. Spring Security supports the configuration of SameSite Cookie, which can be configured by the following code:

protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            .requireCsrfProtectionMatcher(new RequestMatcher() {
                private final Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
                private final RegexRequestMatcher unprotectedMatcher = new RegexRequestMatcher("/unprotected", null);

                @Override
                public boolean matches(HttpServletRequest request) {
                    if (allowedMethods.matcher(request.getMethod()).matches()) {
                        return false;
                    }

                    if (unprotectedMatcher.matches(request)) {
                        return false;
                    }

                    return true;
                }
            });
    http
        .headers()
            .httpStrictTransportSecurity()
                .includeSubDomains(true)
                .maxAgeInSeconds(31536000)
                .and()
            .xssProtection()
                .block(true)
                .and()
            .contentTypeOptions()
                .nosniff()
                .and()
            .cacheControl()
                .disable();
    http
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http
        .authorizeRequests()
            .antMatchers("/unprotected")
                .permitAll()
            .anyRequest()
                .authenticated();
    http
        .exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPoint());
}

(3) Verify the source of the request: Spring Security provides CsrfFiltera filter that can verify whether the source of the request is the same as the source of the current page. If the origin of the request is different than the origin of the current page, it may be a CSRF attack and the request should be rejected. It can be enabled with the following code CsrfFilter:

protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            .requireCsrfProtectionMatcher(new RequestMatcher() {
                private final Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
                private final RegexRequestMatcher unprotectedMatcher = new RegexRequestMatcher("/unprotected", null);

                @Override
                public boolean matches(HttpServletRequest request) {
                    if (allowedMethods.matcher(request.getMethod()).matches()) {
                        return false;
                    }

                    if (unprotectedMatcher.matches(request)) {
                        return false;
                    }

                    return true;
                }
            });
}

(4) Add verification code

This is done by adding a captcha field to the form that requires the user to enter a captcha before submitting the form. This prevents CSRF attacks because the attacker has no way of knowing the correct captcha. This can be achieved through custom filters. For example:

public class CaptchaFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 如果是登录请求,需要检查验证码
        if ("/login".equals(request.getRequestURI()) && "POST".equalsIgnoreCase(request.getMethod())) {
            String code = request.getParameter("code"); // 获取用户输入的验证码
            String sessionCode = (String) request.getSession().getAttribute("code"); // 获取正确的验证码
            if (!StringUtils.isEmpty(code) && code.equals(sessionCode)) {
                filterChain.doFilter(request, response); // 验证码正确,继续处理请求
                return;
            } else {
                response.sendRedirect("/login?error=invalidCode"); // 验证码不正确,跳转回登录页
                return;
            }
        }

        filterChain.doFilter(request, response); // 不是登录请求,直接继续处理
    }
}

Then add to the configuration of spring security:

http.addFilterBefore(new CaptchaFilter(), UsernamePasswordAuthenticationFilter.class);

 3. Single sign-on 

        Single sign-on (Single Sign-On, SSO for short) is an authentication mechanism that allows users to log in to multiple applications or systems using a set of credentials (such as username and password) without having to enter the credentials multiple times.

        In traditional authentication mechanisms, each application or system requires the user to enter a user name and password once. However, for users who work with multiple applications or systems, such a process is cumbersome and unnecessary. Using single sign-on allows users to log in once and use it in multiple applications or systems, improving user experience and work efficiency.

        Single sign-on is usually implemented by an authentication center (Authentication Server). The user authenticates at the authentication center and gets a token (Token). When a user accesses another application or system, the token is sent to that application or system for authentication. If the token is valid, the user is authorized to access the application or system, otherwise the user needs to log in again.

        Using single sign-on can improve security because users only need to enter credentials once, reducing the risk of credential leaks; it can also reduce development and maintenance costs because multiple applications or systems can share authentication mechanisms and user information.

4. CAS

        CAS (Central Authentication Service) is an open source single sign-on protocol and implementation, as well as a common single sign-on solution. Developed by Yale University, CAS is a centralized identity authentication system based on the HTTP protocol.

        CAS manages user identity authentication information through a unified authentication center (CAS Server). When a user accesses an application requiring authentication for the first time, he will be redirected to the CAS Server for authentication. If the identity authentication is successful, CAS Server will issue a ticket (Ticket) to the user, save a Session locally at the same time, and return the ticket to the user's browser. When the user accesses other applications that require identity authentication, he will use the ticket saved in the browser to authenticate to the CAS Server. If the ticket is valid, the user is authorized to access the application.

1. The characteristics of CAS include:

  • Open source: CAS is an open source single sign-on solution that is free to download, modify and use.
  • Security: CAS uses encryption algorithms to ensure the security of user credentials, and supports multiple authentication methods, such as username and password, LDAP, Active Directory, OAuth, etc.
  • Extensible: CAS supports multiple authentication protocols, such as CAS, OAuth, OpenID, etc., and can be integrated with different applications and systems.
  • Easy to deploy: CAS can be integrated with different web containers and applications, and provides a variety of client libraries to facilitate developers to integrate CAS.
  • Reliability: CAS supports multiple load balancing and failover mechanisms to ensure high availability and reliability.

In conclusion, CAS is a mature, stable, secure, scalable, easy-to-deploy and integrate single sign-on solution.

        CAS consists of two parts, CAS Server and CAS Client. CAS Server is a single-point authentication service, and CAS Client is a client that shares the login state of CAS Server. For example: Taobao and Tmall under Alibaba belong to the client in the CAS structure.

2. Three terms: TGT, TGC, ST.

  • TGT (Ticket Granting Ticket) is a ticket used to represent the identity of the user, and is used to represent the identity authentication information of the user in the CAS Server. It is the only ticket in the CAS Server. After the user successfully authenticates, the CAS Server will issue a TGT to the user's browser, and save a copy on the server side for subsequent ticket issuance and verification.
  • TGC (Ticket Granting Cookie) is a cookie used to save the TGT. When the user successfully authenticates in the CAS Server, the CAS Server will return the TGT to the user's browser and set a TGC in the browser. The role of TGC is to establish a session between the browser and the CAS Server, and associate the TGT with the browser, thus avoiding the need to re-authenticate each time a request is made.
  • ST (Service Ticket) is a ticket used to represent the user's access rights to an application. It is used to indicate that the user has been authenticated and authorized to access an application. When a user accesses an application that requires authentication, the CAS Server will issue an ST to the user, and the user can use the ST to authenticate the application. After the user is authenticated, the application will verify the ST with the CAS Server to confirm the user's identity and authorization information.

3. The complete steps of CAS single sign-on are as follows:

  1. A user accesses an application that requires authentication.
  2. If the application judges that the user is not logged in, it will jump to the login page of the CAS Server, and the CAS Server will display the login form to the user and require the user to enter the user name and password for identity authentication.
  3. The user enters the user name and password for identity authentication.
  4. CAS Server verifies whether the user's identity information is correct. If the verification is passed, a TGT is generated on the server side, and the TGT is returned to the user's browser, and a TGC (Ticket Granting Cookie) is set in the browser for browsing It establishes a session between the browser and the CAS Server, and associates the TGT with the browser, thereby avoiding the need to re-authenticate each time a request is made.
  5. A user accesses another application that requires authentication.
  6. If the application judges that the user is not logged in, it jumps to the login page of the CAS Server. The CAS Server checks whether there is a valid TGC in the browser. If it exists, it means that the user has been authenticated by the CAS Server and has a TGT. At this time, CAS Server will issue a ST (Service Ticket) to the user, and return the ST to the user's browser.
  7. The user authenticates to the application using ST.
  8. The application program authenticates the ST with the CAS Server to confirm the user's identity and authorization information. If the verification passes, the user is considered to have logged into the application program.

It should be noted that when the user successfully authenticates in the CAS Server, the CAS Server will issue a TGT to the user and save a copy on the server side for subsequent ticket issuance and verification. When the user accesses another application that requires authentication, the CAS Server will issue a ST to the user, and the user can use the ST to authenticate the application. After the user is authenticated, the application will verify the ST with the CAS Server to confirm the user's identity and authorization information. In addition, in order to improve security, CAS also supports the single sign-out function, that is, after the user logs out in one application, it can automatically log out all the applications that have established a trust relationship with the CAS Server, preventing the user from repeatedly logging out in multiple applications. log out.

Guess you like

Origin blog.csdn.net/weixin_49561506/article/details/130350349