Spring security登录授权用户有效期简单例子

x33g5p2x  于2022-02-07 转载在 Spring  
字(2.3k)|赞(0)|评价(0)|浏览(339)

在上一个例子基础上:

https://zhangphil.blog.csdn.net/article/details/122489213

https://zhangphil.blog.csdn.net/article/details/122489213加入一些简单改造,任何登录授权用户会给一个登录后的有效期,超时后,当前用户需要重新登录认证。这种场景就是常见的网页和app的“记住我”(记住用户名和密码)功能,“记住我”的时间可以通过spring的rememberMe()完成。

修改的代码:

@Autowired
    private UserDetailsService mUserDetailServiceImpl; // 用户服务

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        return new InMemoryTokenRepositoryImpl();
    }
    
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .formLogin() //登录
                //.failureUrl("/error") //成功登陆后跳转页面
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out = null;
                        try {
                            out = resp.getWriter();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        out.write("登录失败");
                        out.flush();
                        out.close();
                    }
                })
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        System.out.println(authentication.getName() + " 登录成功");

                        //重定向
                        response.sendRedirect("/index");
                    }
                })
                .and().rememberMe()
                .userDetailsService(mUserDetailServiceImpl)
                .tokenRepository(persistentTokenRepository()) // 设置数据访问
                .tokenValiditySeconds(5); // 记住我,有效期(秒)

        http
                .authorizeRequests() // 配置认证与授权
                .antMatchers("/user/**").hasRole(USER) //基于角色
                //.antMatchers("/user/**").hasAuthority("p1") 基于权限
                .antMatchers("/admin/**").hasRole(ADMIN) //基于角色
                //.antMatchers("/admin", "/admin/**").hasAuthority("p2") 基于权限
                //.hasAnyAuthority("admin,manager") 只要有任意一个权限就可访问, 多个权限逗号分隔
                //.anyRequest().authenticated()  //需授权才能访问。
                .and();

        //注销登录,退出当前用户
        http.logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                        resp.sendRedirect("/login");
                    }
                })
                .logoutSuccessUrl("/login")
                //.permitAll()
                .and();
    }

启用rememberMe()后,spring默认的login页面自动出现“记住我”的选择框。勾选后,在代码里面启动计时功能,超时后,用户登录失效。

简单期间,本例使用的token实现是基于内存的,常规做法是通过Jdbc那样的数据库存储“记住我”的token。

相关文章

微信公众号

最新文章

更多