New version of Spring Security6.2 case - Basic HTTP Authentication

Foreword:

Continuing from the above, translate the official websiteAuthentication's Username/Password page, and then continue to translate basicThis page, because the official website talks about principles, here is a small case about basic http authentication.

Basic Authentication

This section describes how HTTP Basic Authentication works in Spring Security. First, we see the WWW-Authenticate header being sent back to the unauthenticated client

The above diagram is built on the SecurityFilterChain diagram.

1. First, the user makes an unauthenticated request to an unauthorized resource /private.

2.Spring Security's AuthorizationFilter throws AccessDeniedException to indicate that unauthenticated requests are denied.

3. Since the user is not authenticated, the ExceptionTranslationFilter will initiate "Start Authentication". The configured AuthenticationEntryPoint is an instance of BasicAuthenticationEntryPoint and is used to send the WWW-Authenticate header. The RequestCache is typically a NullRequestCache that does not save requests because the client is able to replay the request it originally requested.

When the client receives the WWW-Authenticate header, it knows that it should try again using the username and password. The image below shows the flow of usernames and passwords being processed:

1. When a user submits their username and password, BasicAuthenticationFilter creates a UsernamePasswordAuthenticationToken, which is authentication by extracting the username and password from the HttpServletRequest.

2. Next, pass the UsernamePasswordAuthenticationToken into the AuthenticationManager for authentication. The details of the AuthenticationManager's appearance depend on how the user information is stored.

3. If authentication fails, define it as "failed" and do the following:

(1) SecurityContextHolder is cleared.

(2) Call RememberMeServices.loginFail. This is a no-op if Remember Me is not configured. See the RememberMeServices interface in the Javadoc.

(3) Call AuthenticationEntryPoint to trigger sending WWW-Authenticate again. See the AuthenticationEntryPoint interface in the Javadoc.

4. If the authentication is successful, define it as "success" and do the following:

(1) Authentication authentication information is set on SecurityContextHolder.

(2) Call RememberMeServices.loginSuccess. This is a no-op if Remember Me is not configured. See the RememberMeServices interface in the Javadoc.

(3) BasicAuthenticationFilter calls FilterChain.doFilter(request, response) to continue executing the rest of the application logic. See BasicAuthenticationFilter class in Javadoc

Spring Security's HTTP basic authentication support is enabled by default. However, once any servlet-based configuration is provided, HTTP Basic must be provided explicitly.

The following example shows a minimal explicit configuration:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
	http
		// ...
		.httpBasic(withDefaults());
	return http.build();
}

Basic Authentication example

The project structure is very simple. Maven only contains 3.2 spring boot and checks web and security:

The code is as follows. First comment out the default form login:

@Configuration
@EnableWebSecurity
public class MySecurity {


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
        http.authorizeHttpRequests((authorize) -> authorize
                .anyRequest().authenticated()
        )
                .httpBasic(Customizer.withDefaults());
//                .formLogin(Customizer.withDefaults());

        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails userDetails = User.withDefaultPasswordEncoder()
                .username("user")
                .password("password")
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(userDetails);
    }

}
@RestController
public class Login {

    @GetMapping("/private")
    public String doLogin1() {

        return "private";
    }
}

访问localhost:8080/private

A dialog box that requires authentication will pop up. The behavior of this browser is because there is a return in the header of the server's response.

Www-Authenticate: Basic realm=“Realm”

After entering the username and password, the page will be private. This is because there is

Authorization: Basic dXNlcjpwYXNzd29yZA==

The format of this request header is to base64 encode the username and password, separated by colons. You can

​​

As an additional note, this is the access credential generated by the browser. Generally speaking, it will exist until the browser is closed. Credentials are stored inside the browser instead of using cookies, localstorage, etc. Therefore, deleting cookies from the application in the browser toolbar does not work, but I have tried clearing cookies in the privacy settings and it works.

references: 

"Spring boot official website"

Guess you like

Origin blog.csdn.net/u012895183/article/details/134983179