E
E
Eugenue Cesarevich2021-03-30 12:23:18
Java
Eugenue Cesarevich, 2021-03-30 12:23:18

How to implement "Remember me" with custom auth controller in Spring Boot?

In the application, sessions are stored in Redis, cookie-based authorization. I have implemented a custom controller to authenticate and receive a cookie:

@PostMapping(value = "/login", consumes = MediaType.APPLICATION_JSON_VALUE)
public String login(@RequestBody LoginDataTo loginData) {
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
            loginData.getEmail(),
            loginData.getPassword());
    Authentication authentication = this.authenticationManager.authenticate(token);

    SecurityContextHolder
            .getContext()
            .setAuthentication(authentication);

    return "OK";
}


Here is LoginDataTo:

@Value
public class LoginDataTo {
    String email;
    String password;
    boolean rememberMe;
}


Configuration:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .rememberMe().tokenValiditySeconds(REMEMBERED_SESSION_TIMEOUT).and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);

        http
                .httpBasic().disable()
                .formLogin().disable()
                .csrf().disable()
                .cors().disable();

        http
                .authorizeRequests()
                .antMatchers("/login").anonymous()
                .antMatchers("/api/v1/profile").authenticated()
                .antMatchers("/api/v1/students/**").hasRole(Role.STUDENT.name())
                .anyRequest().authenticated();
    }


Now I'm trying to implement the remember-me logic. I don't really understand how to do this using a custom auth controller. It turns out that I have to pull out rememberMe in it from the received LoginDataTo and ... And then I have absolutely no idea where to put it. How can I implement the rememberMe functionality in this case?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question