SoFunction
Updated on 2025-04-12

SpringSecurity implements multiple authentication methods

1. Form-based Authentication

1. Principle

This is the most common authentication method. When a user accesses a protected resource through the browser, he will be redirected to a login page. The user enters the username and password on the login page and submits the form. Spring Security will intercept the form submission request, obtain the username and password, encapsulate it into an Authentication object, and pass it to the AuthenticationManager for verification.

2. Configuration example

In Spring Security's configuration class (usually inherited from WebSecurityConfigurerAdapter), form-based authentication can be configured in the following ways.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
           .authorizeRequests()
               .antMatchers("/admin/**").hasRole("ADMIN")
               .antMatchers("/user/**").hasRole("USER")
               .anyRequest().authenticated()
           .and()
           .formLogin()
               .loginPage("/login")
               .permitAll()
               .defaultSuccessUrl("/home")
               .failureUrl("/login?error");
    }
}

In the above code,formLogin()Methods are used to configure form-based authentication.loginPage("/login")The custom login page path is specified as/loginpermitAll()It means that this login page can be accessed by all users.defaultSuccessUrl("/home")It means that after login is successful, it will jump to/homepage,failureUrl("/login?error")It means that the login failed and jumps to/loginPage and add oneerrorparameter.

2. HTTP Basic Authentication

1. Principle

This authentication method is based on the HTTP protocol specification. When a client (such as a browser or other HTTP client) requests a protected resource, the server returns a401 UnauthorizedRespond and inWWW - AuthenticateSpecified in the header informationBasicAuthentication method. After the client receives this response, a username and password input box will pop up (browser behavior). After the user enters the username and password, the client will simply encode the username and password and add it to theAuthorizationIn the header information, the format isBasic base64(username:password), and then resend the request. Spring Security intercepts this request, decodes and verifies the username and password.

2. Configuration example

HTTP Basic Authentication can be enabled in Spring Security configuration in the following ways.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
           .authorizeRequests()
               .anyRequest().authenticated()
           .and()
           .httpBasic();
    }
}

In the above codehttpBasic()Method Enable HTTP Basic Authentication. All requests require authentication, and when an unauthenticated request arrives, the basic HTTP authentication process will be triggered.

3. HTTP Digest Authentication

1. Principle

HTTP digest authenticationCompareBasic HTTP AuthenticationMore safe. It also interacts between the client and the server, but not simply sends.Base64The encoded username and password, but send a message digest. This message digest is passed through username, password, requested URI, random number (nonce generated by the server) and other information.MD5or calculated by other hashing algorithms. After receiving the request, the server will recalculate the message digest using the stored user password and the same algorithm, and then compare it with the message digest sent by the client to verify the user's identity.

2. Configuration example

To enable HTTP digest authentication, add the following code in the Spring Security configuration. However, it should be noted that in practical applications, HTTP digest authentication is used relatively little because it also has some security vulnerabilities and may not be convenient in some complex scenarios.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
           .authorizeRequests()
               .anyRequest().authenticated()
           .and()
           .httpDigest();
    }
}

4. Certificate-based Authentication

1. Principle

This authentication method depends on digital certificates. Both the client and the server need to have a digital certificate. When the client requests the server, it will send its own certificate to the server. The server will verify the validity of the client certificate, including whether the certificate is issued by a trusted certificate authority (CA), whether the certificate expires, etc. At the same time, the server can also use its own certificate to prove its identity to the client (two-way authentication). In Spring Security, it can implement certificate-based authentication by configuring SSL (Secure Sockets Layer) or TLS (Transport Layer Security).

2. Configuration example

Configuring certificate-based authentication is relatively complex, involving steps such as generating and configuring certificates, configuring SSL/TLS. Here is a simple example for configuring SSL in a Spring Boot application.

2.1 Generate a certificate

  • Generate a self-signed certificate using Keytool (Java's own tool)

Open the command line terminal and use the following command to generate a keystore and self-signed certificate. For example, generate a name calledkeystore.p12ofPKCS12The keystore in format, the password of the keystore ispassword, valid for 365 days.

keytool -genkeypair -alias myalias -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 365 -storepass password

This command will prompt you to enter some information, such as name, organizational unit, city, etc., which will be included in the certificate.

  • Obtain CA signature certificate (optional)

If you do not want to use a self-signed certificate, you can obtain the certificate from the Certificate Authority (CA). This usually involves submitting a certificate signing request (CSR) to the CA, which verifies your identity and issues a certificate to you. This process varies from CA to CA and may require a certain fee.

2.2 Add the following configuration in the file

-store-type=PKCS12
-store=classpath:keystore.p12
-store-password=password
  • keystore.p12It's a certificate file
  • passwordIt is the password of the certificate file.
  • classpath:keystore.p12Indicates that the keystore file is under the classpath. If the keystore file is located elsewhere in the file system, an absolute path can be used, such asfile:/path/to/keystore.p12

2.3 Configuring certificate-based authentication details in Spring Security (for two-way authentication)

  • Configure client certificate authentication

Can be configuredX509AuthenticationFilterTo implement client certificate authentication. Here is a simple example of adding code in the Spring Security configuration class (usually inherited from WebSecurityConfigurerAdapter).

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
          .authorizeRequests()
              .anyRequest().authenticated()
          .and()
          .x509()
              .subjectPrincipalRegex("CN=(.*?)(?:,|$)")
              .userDetailsService(userDetailsService())
              .authenticationEntryPoint(authenticationEntryPoint());
    }
    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return new Http403ForbiddenEntryPoint();
    }
    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                // Load user details according to the subject information in the certificate, which can be obtained from the database or other places here                return new User(username, "", AuthorityUtils.NO_AUTHORITIES);
            }
        };
    }
}

In the above code:

  • x509()Method is used to configure X509 certificate authentication.
  • subjectPrincipalRegex("CN=(.*?)(?:,|$)")Used to extract username from the subject of the certificate. The regular expression here is extracted toCN=The beginning part is used as the username, and you can modify this regular expression according to the format of the actual certificate.
  • userDetailsService(userDetailsService())Used to specify aUserDetailsServiceImplementation, used to load user details based on the username extracted by the certificate. This is just a simple example. In actual applications, it may be necessary to obtain user roles, permissions and other information from storage media such as databases.
  • authenticationEntryPoint(authenticationEntryPoint())Used to specify an authentication entry point. When authentication fails, this entry point will be called for processing, and here is aHttp403ForbiddenEntryPoint, can be modified to other suitable entry points according to actual needs.

2.4 Considerations of one-way authentication and two-way authentication

One-way certification

  • If the server only needs to prove its identity to the client (through the server certificate), the above configuration can basically meet the needs. When the client connects to the server, it will verify the validity of the server certificate, such as checking whether the certificate is issued by a trusted CA, whether the certificate expires, etc.

Two-way certification

  • If the client needs to prove its identity to the server (through the client certificate), in addition to the above configuration, it is also necessary to ensure that the client provides a valid certificate when sending the request. In a web browser environment, this may require the user to install and configure the client certificate in the browser. Used in other HTTP clients (such as Java programsHttpURLConnectionorRestTemplateIn the client certificate-related parameters need to be set correctly, such asRestTemplateIn, can be passedClientHttpRequestFactoryTo configure the client certificate. Here is a simple example usingRestTemplateConfigure client certificates for two-way authentication.
KeyStore keyStore = ("PKCS12");
(new FileInputStream("client-keystore.p12"), "client-password".toCharArray());
KeyManagerFactory keyManagerFactory = (());
(keyStore, "client-password".toCharArray());
SSLContext sslContext = ("TLS");
((), null, null);
CloseableHttpClient httpClient = ().setSSLContext(sslContext).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);

In the above example, first load the client keystore (client-keystore.p12), then initializeKeyManagerFactory, rebuildSSLContextand set it toCloseableHttpClientIn, finally passedHttpComponentsClientHttpRequestFactoryWillCloseableHttpClientandRestTemplateRelated, thisRestTemplateTwo-way authentication can be performed using client certificates when sending a request.

5. Authentication based on OpenID Connect or OAuth 2.0 (OpenID Connect/OAuth 2.0 - based Authentication)

1. Principle

OAuth 2.0 is an authorization framework that allows users to authenticate through third-party identity providers (such as Google, Facebook, etc.). OpenID Connect is an authentication layer based on OAuth 2.0. When a user chooses to log in with a third party, the application redirects the user to the login page of the third party identity provider. After the user logs in to the third-party page, the third party will return a token containing the user's identity information (such as an ID token). Spring Security can be configured to receive and verify this token, thus completing user authentication.

2. Configuration example

Take the example of integrating OAuth 2.0 with Spring Security, assuming you want to integrate Google Login. First, you need to register the application in the Google Developer Console to obtain itclient_idandclient_secret. Then add the following code in the Spring Security configuration:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
           .authorizeRequests()
               .antMatchers("/").permitAll()
               .anyRequest().authenticated()
           .and()
           .oauth2Login()
               .clientRegistrationRepository(clientRegistrationRepository())
               .authorizedClientRepository(authorizedClientRepository());
    }
    @Bean
    public ClientRegistrationRepository clientRegistrationRepository() {
        List<ClientRegistration> registrations = new ArrayList<>();
        (
            ("google")
               .clientId("YOUR_CLIENT_ID")
               .clientSecret("YOUR_CLIENT_SECRET")
               .clientName("Google")
               .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
               .redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}")
               .scope("openid", "profile", "email")
               .authorizationUri("/o/oauth2/v2/auth")
               .tokenUri("/oauth2/v4/token")
               .userInfoUri("/oauth2/v3/userinfo")
               .jwkSetUri("/oauth2/v3/certs")
               .build()
        );
        return new InMemoryClientRegistrationRepository(registrations);
    }
    @Bean
    public AuthorizedClientRepository authorizedClientRepository() {
        return new InMemoryAuthorizedClientRepository();
    }
}

In the above code,oauth2Login()Method is used to configure OAuth 2.0 login.clientRegistrationRepository()Methods are used to configure client registration information, including obtained from Googleclient_idandclient_secretwait.authorizedClientRepository()Used to store information about authorized clients.

6. Remember-Me function

1. Principle

This is an authentication extension function that is convenient for users. When the user checks the "Remember me" option and logs in, Spring Security sets a persistent login token (usually an encrypted cookie) in the user's browser. In subsequent access, as long as the token is valid, the user does not need to enter the user name and password again, and the system will automatically authenticate the user based on the information in the token. This token contains the user's identity information and some information used to verify security, such as expiration time, signature, etc.

2. Configuration example

The "Remember Me" feature can be added in the Spring Security configuration in the following ways.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
           .authorizeRequests()
               .anyRequest().authenticated()
           .and()
           .formLogin()
               .loginPage("/login")
               .permitAll()
               .defaultSuccessUrl("/home")
               .failureUrl("/login?error")
           .and()
           .rememberMe()
               .rememberMeParameter("remember-me")
               .tokenValiditySeconds(86400);
    }
}

In the above code,rememberMe()Methods are used to configure the Remember Me feature.rememberMeParameter("remember-me")Specifies the parameter name corresponding to the "Remember Me" option in the front-end form.tokenValiditySeconds(86400)Specified Remember that the validity period of my token is one day (86400 seconds).

7. LDAP certification

The full name of LDAP is Lightweight Directory Access Protocol, which is the lightweight directory access protocol. LDAP is a protocol used to access and maintain distributed directory information services. In terms of identity authentication, user identity information (such as username, password, etc.) is stored in the LDAP server. When a user tries to log in to the application, Spring Security sends the user-provided credentials to the LDAP server for verification. The LDAP server determines whether the username and password provided by the user are correct based on the user information and authentication policies it stores (such as simple binding authentication).

1. Background and Origin

LDAP evolved from the X.500 directory access protocol. The X.500 protocol is powerful but complex, and it seems too bulky in actual Internet application scenarios. LDAP simplifies the X.500 model on the basis of maintaining basic operational support for directory services, removing some complex functions, making it more suitable for use in TCP/IP network environments. It first began to appear around 1993. With the development of network applications, it gradually became a directory service agreement widely used in enterprise internal networks and Internet services.

2. Protocol function

  • Information storage and queryLDAP is mainly used to store and retrieve various types of directory information, such as user information (including name, contact information, position, etc.), organizational structure information (department division, superior-level relationship, etc.), resource information (such as location and configuration information of printers, servers and other devices). This information is stored in the LDAP server in a tree structure (directory tree), and the LDAP protocol can be easily queried and updated.
  • Certification and authorization support:LDAP provides the basis for authentication. Many applications use LDAP servers to store user's identity credentials (such as username and password) to verify that the login information provided by the user is correct through the LDAP protocol. At the same time, LDAP can also be used for authorization, for example, to determine user access to resources by group information to which the user belongs (organized in some way in the LDAP directory tree).
  • Distributed architecture support: It can support a distributed directory service environment. In large enterprises or complex network environments, there may be multiple LDAP servers, which can cooperate with each other through referral mechanisms and provide complete directory services. For example, a multinational company can set up LDAP servers in different regions, each server is responsible for the management of local users and resource information, and can access relevant information on servers in other regions through a referral mechanism.

3. Application scenarios

  • Internal enterprise user management: Within the enterprise, LDAP is often used to centrally manage user accounts. All employee information, including basic personal information, job information, department, etc., are stored in the LDAP server. When employees use various systems within the enterprise (such as mail systems, office automation systems, etc.), these systems can be authenticated and authorized through LDAP to ensure that only legitimate users can access the corresponding resources and that users can only access resources within their permissions.
  • Single Sign-On (SSO) system:LDAP plays an important role in single sign-on solutions. Single sign-on means that users can access multiple different application systems using a single username and password. The LDAP server serves as a centralized repository of user information, providing unified authentication services for each application system. When the user logs into one of the application systems and passes LDAP authentication, other integrated application systems can trust the authentication result, thereby achieving seamless access to the user.
  • Resource Directory Service: In a network environment, LDAP can be used to maintain and query directory information of various resources. For example, in a campus network, information such as location, status, and usage permissions of all resources such as computer equipment, network printers, etc. is stored and managed through LDAP. Users can use simple LDAP queries to find nearby available printers or computers with specific configurations.

4. Configuration steps and examples

Add dependencies

In the Maven project, you need to add Spring Security LDAP-related dependencies. For example:

<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-ldap</artifactId>
</dependency>

Configure LDAP server information

In Spring Configuration Files (or) , configure the address, port, username and password of the LDAP server (if required). For example,middle:

=ldap://your-ldap-server:389
=cn=admin,dc=example,dc=com
=adminpassword

Configure Spring Security for LDAP Authentication

In the Spring Security configuration class (usually inherited from WebSecurityConfigurerAdapter), configure LDAP authentication-related content. Here is a simple example:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
          .ldapAuthentication()
              .userDnPatterns("uid={0},ou=people")
              .groupSearchBase("ou=groups")
              .contextSource()
              .url("ldap://your - ldap - server:389/dc=example,dc=com")
              .and()
              .passwordCompare()
              .passwordEncoder(new BCryptPasswordEncoder())
              .passwordAttribute("userPassword");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
          .authorizeRequests()
              .anyRequest().authenticated()
          .and()
          .formLogin();
    }
}

In the aboveconfigure(AuthenticationManagerBuilder auth)In the method:

  • ldapAuthentication()Indicates that LDAP authentication is enabled.
  • userDnPatterns("uid={0},ou=people")Used to specify the user's DN (Distinguished Name) mode in the LDAP directory. in{0}is a placeholder that will be replaced with the username when authenticated.
  • groupSearchBase("ou=groups")Used to specify the basic path for group search, to obtain the group information to which the user belongs (for authorization and other purposes).
  • contextSource().url("ldap://your-ldap-server:389/dc=example,dc=com")Configure the URL of the LDAP context, including the address and underlying DN of the LDAP server.
  • passwordCompare().passwordEncoder(new BCryptPasswordEncoder()).passwordAttribute("userPassword")Some of them are used to configure password comparison methods. Here, BCrypt password encoder is used, and the attributes that store passwords in LDAP are specified asuserPassword

5. Combined with other authentication methods

Spring Security can flexibly use LDAP authentication with other authentication methods (such as form-based authentication, database authentication, etc.). For example, it can beconfigure(AuthenticationManagerBuilder auth)In the method, multiple authentication providers are configured, such as configuring a database authentication provider and an LDAP authentication provider at the same time. In this way, the system can decide which authentication method to use to authenticate the user based on the user's choice or configuration priority.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   @Override
   protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       auth
          .jdbcAuthentication()
               // Configure database authentication related content              .dataSource(dataSource)
              .passwordEncoder(passwordEncoder())
              .usersByUsernameQuery("select username,password,enabled from users where username =?")
              .authoritiesByUsernameQuery("select username,authority from authorities where username =?")
          .and()
          .ldapAuthentication()
               // Configuring LDAP authentication related content              .userDnPatterns("uid={0},ou=people")
              .groupSearchBase("ou=groups")
              .contextSource()
              .url("ldap://your-ldap-server:389/dc=example,dc=com")
              .and()
              .passwordCompare()
              .passwordEncoder(new BCryptPasswordEncoder())
              .passwordAttribute("userPassword");
   }
   // Other configuration contents, such as HttpSecurity configuration, etc.}

In the above example, thejdbcAuthentication()andldapAuthentication(), the system can use different authentication methods according to specific needs. For example, it can be determined whether to use database authentication or LDAP authentication based on the organization to which the user belongs or different modules of the application.

This is the end of this article about SpringSecurity implementing multiple authentication methods. For more related SpringSecurity authentication, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!