SpringSecurity

 controller中登录请求配置

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "views/login";
    }

.新建配置类SecurityConfig,配置用户登录,实现不同用户不同访问权限

//AOP实现,不更改其他代码,安全框架代替拦截器
//Enable注解表示开启功能
@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter{ //授权 @Override protected void configure(HttpSecurity http) throws Exception { //首页所有人可以访问,功能页指定权限访问 //请求授权规则 http.authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/level1/**").hasRole("vip1") .antMatchers("/level2/**").hasRole("vip2") .antMatchers("/level3/**").hasRole("vip3"); //没有权限默认跳转至登录页 http.formLogin(); } //认证 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //此处手动添加用户名密码,一般从DB中取出 //密码编码:passwordEncoder //springsecurity中新增很多加密方法 auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("alan").password(new BCryptPasswordEncoder().encode("123")).roles("vip1") .and() .withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3"); } }

配置注销功能,引入springsecurity-thymeleaf的整合包,启用页面中sec的标签功能,同时加入申明,

显示登录或注销按钮的判断逻辑,已经登录则只显示注销,没有登录则只显示登录

<!-- 可能存在版本兼容问题,可尝试使用springsecurity5-->
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>
//认证中开启注销功能
http.logout().logoutSuccessUrl("/");

 注销可能存在报错,原因是需要关闭csrf功能,CSRF跨站点请求伪造

页面上配置sec,指定权限显示指定内容

自定义登录页面,将默认的login指向tologin,开启记住用户名密码功能

此处注意前后端传参的参数名不一致问题

默认的login页面,自带参数username和password,如果我们在前端的用户名和密码参数名和默认不一致,

则必须在自定义登录页的时候配置自定义的参数名

原文地址:https://www.cnblogs.com/alanchenjh/p/12341131.html