使用java代码配置 Spring Boot 中的 Spring Security 和 Rember me, Cookie记住密码

前言

Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。 [ 百度百科 ]

开始

1 .使用maven 引用spring security 等相关jar包

2 .在配置文件中编写如下代码,其中csrf表示提交方式,禁用后logout用get即可访问

            http
                    .authenticationProvider(formAuthenticationProvider)
                    .authorizeRequests()
                    .antMatchers("/error", "/favicon.ico", "/content/**", "/login", "/user/login", "/user/register").permitAll()
                    .anyRequest().hasRole("USER")
                    .and().formLogin().loginPage("/user/login").loginProcessingUrl("/user/login").failureHandler(formAuthenticationFailureHandler)
                    .and().logout().logoutUrl("/user/logout").logoutSuccessUrl("/user/login").invalidateHttpSession(true)
                    .and().rememberMe().key("demo").tokenValiditySeconds(30 * 24 * 60 * 60).userDetailsService(formDetailsService)
                    .and().csrf().disable();

3 .然后新建如下类,来自定义处理用户登录结果,其中FormAuthenticationProvider是登录的时候,验证用户名、密码用的。FormDetailsServiceImpl是用户关闭浏览器,再次打开会调用此方法,来获取当前用户,切身份已经验证通过的。FormAuthenticationFailureHandler是登录失败,来处理不同的返回消息

        private final FormAuthenticationProvider formAuthenticationProvider;
        private final FormDetailsServiceImpl formDetailsService;
        private final FormAuthenticationFailureHandler formAuthenticationFailureHandler;

4 .具体三个类实现,请看GitHub,FormAuthenticationProviderFormAuthenticationFailureHandlerFormDetailsServiceImpl


结束

附上成功图片:
这里写图片描述

posted @ 2018-05-07 17:04  alvis_u  阅读(169)  评论(0编辑  收藏  举报