Execute arbitrary processing after Basic authentication with Spring boot.

Implementing the authentication function with spring boot is a daily routine. However, in spite of Basic authentication, processing after successful authentication, lock processing after authentication failure, resetting the number of failures, or log output may be performed.

If it is a general formLogin or oauth2Login, The solution is to implement it in successHandler or failureHandler. .. ..

I will post it because there was not much information in Japanese.

dependency spring boot 2.0.4.RELEASE lombok using.

Implementation

Implement Basic authentication in the security settings. Also, register a class that implements the RememberMeServices interface in SharedObject.

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    MyRememberMeServices myRememberMeServices;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //By replacing Remembe MeServise here, processing can be executed before and after Basic authentication.
        http.setSharedObject(RememberMeServices.class,myRememberMeServices);
        http.httpBasic()
                .and()
                    .authorizeRequests()
                    .anyRequest()
                    .authenticated()
                .and()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); //No need to manage sessions with cookies;
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .passwordEncoder(NoOpPasswordEncoder.getInstance()) //Required from spring5?
                .withUser("LLENN")
                .password("p-chan")
                .roles("GGO_USER");
    }

}

The RememberMeServices interface can implement Success or Fail processing.

@Slf4j
@Service
public class MyRememberMeServices implements RememberMeServices {

	@Override
	public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) {
		return null;
	}
	@Override
	public void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
		log.info("login:{}",successfulAuthentication.getName());
	}

	@Override
	public void loginFail(HttpServletRequest request, HttpServletResponse response) {
		//Get the user used for authentication.
		String base64Credentials = request.getHeader("authorization").substring("Basic".length()).trim();
		String credentialSting = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
		String username = credentialSting.split(":")[0];

		log.error("login fail:{}",username);
	}
}

In the above implementation, only log is output, but since the class is `` `@ Service```, you can DI your favorite component.

However, be aware that ** loginSuccess and loginFail are called after the Basic authentication process **.

If you fail to log in, you will not have your credentials. Therefore, at the time of loginFial, the user name used for authentication cannot be obtained from Authentication :: getName, but it must be obtained from the header information of HttpServletRequest.

that's all.

I uploaded the source to github. I would appreciate it if you could refer to it. https://github.com/amanoese/spring-basic-auth-example

Digression

It's good to replace the process of RememberMe Services of Basic authentication, but what if the original implementation does a great job? .. When I looked at the source, I found the following code.

NullRememberMeServices


package org.springframework.security.web.authentication;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;

public class NullRememberMeServices implements RememberMeServices {
    public NullRememberMeServices() {
    }

    public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) {
        return null;
    }

    public void loginFail(HttpServletRequest request, HttpServletResponse response) {
    }

    public void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
    }
}

It looks like a class prepared for rewriting. As far as I followed the implementation, I was confused because I couldn't find the place where autoLogin was called. .. ..

spring is difficult.

Recommended Posts

Execute arbitrary processing after Basic authentication with Spring boot.
Use Basic Authentication with Spring Boot
Achieve BASIC authentication with Spring Boot + Spring Security
Processing at application startup with Spring Boot
Asynchronous processing with Spring Boot using @Async
Asynchronous processing with regular execution in Spring Boot
Try LDAP authentication with Spring Security (Spring Boot) + OpenLDAP
[Introduction to Spring Boot] Authentication function with Spring Security
Download with Spring Boot
Generate barcode with Spring Boot
Hello World with Spring Boot
Basic Authentication with Java 11 HttpClient
Implement GraphQL with Spring Boot
Get started with Spring boot
Hello World with Spring Boot!
Spring with Kotorin --6 Asynchronous processing
Run LIFF with Spring Boot
SNS login with Spring Boot
[Java] Thymeleaf Basic (Spring Boot)
File upload with Spring Boot
Spring Boot starting with copy
Spring Boot starting with Docker
Hello World with Spring Boot
Set cookies with Spring Boot
Use Spring JDBC with Spring Boot
Add module with Spring Boot
Getting Started with Spring Boot
Create microservices with Spring Boot
Send email with spring boot
Implemented authentication function with Spring Security ②
gRPC on Spring Boot with grpc-spring-boot-starter
Implemented authentication function with Spring Security ③
Create an app with Spring Boot 2
Hot deploy with Spring Boot development
Database linkage with doma2 (Spring boot)
Spring Boot Tutorial Using Spring Security Authentication
Spring Boot programming with VS Code
Until "Hello World" with Spring Boot
Inquiry application creation with Spring Boot
Implemented authentication function with Spring Security ①
Get validation results with Spring Boot
Learn Spring Security authentication processing architecture
Oauth2 authentication with Spring Cloud Gateway
(Intellij) Hello World with Spring Boot
Create an app with Spring Boot
Google Cloud Platform with Spring Boot 2.0.0
Check date correlation with Spring Boot
I tried GraphQL with Spring Boot
[Java] LINE integration with Spring Boot
Beginning with Spring Boot 0. Use Spring CLI
I tried Flyway with Spring Boot
Authentication / authorization with Spring Security & Thymeleaf
Message cooperation started with Spring Boot
Spring Boot gradle build with Docker
Introducing Basic Authentication on Heroku [Spring Framework]
Hello World with Eclipse + Spring Boot + Maven
Send regular notifications with LineNotify + Spring Boot
Perform transaction confirmation test with Spring Boot
DB authentication with Spring Security & hashing with BCrypt
HTTPS with Spring Boot and Let's Encrypt
Try using Spring Boot with VS Code