继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Spring Security 配置 Remember Me

NoOneNoOne
关注TA
已关注
手记 17
粉丝 0
获赞 0

1。概述

本教程将展示如何使用 Spring Security 在 Web 应用程序中启用和配置 Remember Me。之前已经讨论过设置安全和简单表单登录的 MVC 应用程序

该机制将能够跨多个会话识别用户——首先要了解的是,Remember Me 仅在会话超时后才会启动。默认情况下,用户在 30 分钟不活跃后会超时,但在 web.xml可以配置超时时间

注意:本教程重点介绍基于标准 cookie 的方法。对于持久化方法,请查看 Spring Security – Persistent Remember Me 指南。

2。安全配置

让我们看看如何使用 Java 设置安全配置:

@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")
            ;
    }
}

如您所见,使用 rememberMe() 的基本配置非常简单,同时通过附加选项保证可扩展性。 key 在这里很重要——它是整个应用程序的私有秘钥,将在生成令牌的内容时使用。

此外,可以使用 tokenValiditySeconds() 将 ** 令牌有效时间从默认的 2 周配置为** - 例如 - 一天:

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

我们还可以看看等价的 XML 配置:

<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。登录表格

登录表单类似于我们用于表单登录的那个

<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>

注意新添加的 checkbox 输入会映射到 remember-me。这个添加的输入足以在Remember Me激活的情况下登录。

此默认路径也可以更改为:

.rememberMe().rememberMeParameter("remember-me-new")

4。Cookie

该机制将在用户登录时创建一个额外的 cookie——“remember-me” cookie。

Remember Me cookie 包含以下数据:

  • 用户名 – 标识登录的主体
  • expirationTime – 使 cookie 过期;默认为 2 周
  • MD5 hash – 前 2 个值的 – usernameexpirationTime ,加上 password 和预定义的 key

这里首先要注意的是 usernamepassword 都是 cookie 的一部分——这意味着,如果其中任何一个被更改,cookie 将不再有效。此外,可以从 cookie 中读取 username

此外,如果 Remember Me 的 cookie 被捕获,此机制可能会受到攻击。 cookie 将是有效且可用的,直到它过期或更改凭据。

5。实际使用

要查看 Remember Me 机制的工作情况,您需要:

  • 登录时记得我活跃
  • 等待会话过期(或删除浏览器中的 JSESSIONID cookie)
  • 刷新页面

如果 Remember Me 已经失效,cookie 过期后用户应该被 redirected back to the login page 。登录以后用户会在在新令牌/cookie 的帮助下保持登录状态

6。结论

本教程展示了如何在安全配置中设置和配置 Remember Me,并简要描述了记录在 cookie 的数据类型。

具体实现可以在Github – 这是一个基于 Eclipse 的项目,所以它应该很容易导入和运行。

当项目在本地运行时,可以在 [localhost] 上访问 login.htmlhttp://localhost:8080/spring-security-mvc-custom/login.html “Access the project on localhost”)。

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP