Remember Me trong Spring Security

Người dịch : Nguyễn Minh Tuấn
Email liên hệ : tuann.nm241@gmail.com
Bài viết gốc : https://www.baeldung.com/spring-security-remember-me

1. Tổng quan

Trong bài viết này, chúng ta sẽ cùng tìm hiểu cách kích hoạt và cấu hình chức năng Remember Me với Spring Security.
Chức năng Remember Me có thể xác định người dùng qua nhiều phiên (sessions) , vì thế Remember Me chỉ kích hoạt sau khi phiên (session) hết thời gian.

2. Cấu hình Security

Cùng xem cách thiết lập cấu hình security dưới đây:

@Configuration
@EnableWebSecurity
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean("authenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user1").password("{noop}user1Pass").roles("USER")
            .and()
            .withUser("admin1").password("{noop}admin1Pass").roles("ADMIN");
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/anonymous*").anonymous()
            .antMatchers("/login*").permitAll()
            .anyRequest().authenticated()
            
            .and()
            .formLogin()
            .loginPage("/login.html")
            .loginProcessingUrl("/login")
            .failureUrl("/login.html?error=true")
            
            .and()
            .logout().deleteCookies("JSESSIONID")
            
            .and()
            .rememberMe().key("uniqueAndSecret")
            ;
    }
}

Như bạn có thể thấy cấu hình method rememberMe() rất đơn giản trong khi vẫn rất linh hoạt thông qua các lựa chọn bổ sung ( additional options ).
key’ rất quan trọng, nó được sử dụng khi tạo ra nội dụng của token.
Ngoài ra , thời gian hiệu lực của token mặc định là 2 tuần. Ví dụ , muốn set thời gian hiệu lực 1 ngày thì có thể làm như sau :

rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400)

Chúng ta cũng có thể tham khảo cấu hình XML tương tự:

<http use-expressions="true">
    <intercept-url pattern="/anonymous*" access="isAnonymous()" />
    <intercept-url pattern="/login*" access="permitAll" />
    <intercept-url pattern="/**" access="isAuthenticated()" />

    <form-login login-page='/login.html' 
      authentication-failure-url="/login.html?error=true" />
    <logout delete-cookies="JSESSIONID" />

    <remember-me key="uniqueAndSecret"/>
</http>

<authentication-manager id="authenticationManager">
    <authentication-provider>
        <user-service>
            <user name="user1" password="{noop}user1Pass" authorities="ROLE_USER" />
            <user name="admin1" password="{noop}admin1Pass" authorities="ROLE_ADMIN" />
        </user-service>
    </authentication-provider>
</authentication-manager>

3. Form đăng nhập

<html>
<head></head>

<body>
    <h1>Login</h1>

    <form name='f' action="login" method='POST'>
        <table>
            <tr>
                <td>User:</td>
                <td><input type='text' name='username' value=''></td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type='password' name='password' /></td>
            </tr>
            <tr>
                <td>Remember Me:</td>
                <td><input type="checkbox" name="remember-me" /></td>
            </tr>
            <tr>
                <td><input name="submit" type="submit" value="submit" /></td>
            </tr>
        </table>
    </form>

</body>
</html>

Chú ý rằng để kích hoạt remember me thì input check box cần có thuộc tính ‘name’ là ‘remember-me’ .

4. Cookie

Khi sử dụng chức năng remember me thì sẽ bổ sung thêm cookie - đó là ‘remember me’ cookie khi chúng ta đăng nhập.
Remember Me cookie bao gồm những thông tin:

  • username: xác định principal đã đăng nhập.
  • expirationTime: thời gian cookie hết hạn ( mặc định là 2 tuần ).
  • MD5 hash : hashing dựa trên 2 giá trị username và expirationTime cộng thêm password và key đã được xác định trước.

Điều cần chú ý ở đây là cả username và password đều là một phần của cookie , vì thế chỉ cần một trong hai giá trị thay đổi thì cookie sẽ không còn hợp lệ.

5. Thực hiện

Để kiểm chứng remeber me hoạt động, bạn có thể:

  • Đăng nhập cùng với chức năng remember me.
  • Đợi cookie hết hạn ( hoặc xoá cookie ).
  • Refresh lại trang.

Nếu không sử dụng remember me khi cookie hết hạn người dùng sẽ cần đăng nhập lại.

6. Tổng kết

Trong bài viết này, chúng ta đã tìm hiểu về cách cài đặt và cấu hình chức năng Remember Me.
Hy vọng bài viết sẽ giúp ích các bạn trong quá trình học tập.