springboot-thymeleaf-security权限控制

引入thymeleaf-extras-springsecurity5依赖

注意springboot2.x版本要引入springsecurity5

 <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

编写security配置类

定义认证规则的注意事项

  • spring security 5.X开始(springboot2.x), 需要使用密码编码器,也就是需要对你的明文密码进行加密, 而不使用NoAppasswordEncoder(无密码编码器); 因此,使用要对用户名、密码加密
  • passwordEncoder(参数取值如下)
  • 方法1、new BCryptPasswordEncoder()
  • 方法2、new Pbkdf2PasswordEncoder()
  • 方法3、new SCryptPasswordEncoder()
  • 或实现passwordEncoder接口
package com.demo.webdemo.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @EnableWebSecurity 启动webSecurity,
 */
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    
    


    /**
     * 定制请求的授权规则
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
    

        /**
         * antMatchers方法 可定义多个pattern,以"/"开头
         * permitAll方法 允许所有Pattern访问
         *hasRole方法 授予权限
         */
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        /**
         * formLogin方法开启自动配置的登陆功能,
         * 若没登陆,自动来到(自动生成的)登陆页面
         * 若登陆失败,则重定向到login?error页面(自动生成的)
         *
         * userxx.passxx.loginPage("/xxx")方法
         * 携带用户名密码(input的name)跳转定制登录页面
         *
         */

        http.formLogin().usernameParameter("usn").passwordParameter("pwd").loginPage("/seclogin");

        /**
         * 开启注销功能(清除session),注销成功后跳转到login?logout页面
         * logoutSuccessUrl方法 logout方法执行成功后跳转到哪个页面
         */
        http.logout().logoutSuccessUrl("/");

        /**
         * 开启"记住我"功能,登录成功后,将cookies保存到浏览器
         * 注销后cookies将被删除
         * rememberMeParameter方法,参数为(input的name),定制"记住我"功能
         */
        http.rememberMe().rememberMeParameter("remember");

    }

    /**
     *定义认证规则,给用户赋予权限
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    
        auth.inMemoryAuthentication()
                        .passwordEncoder(new BCryptPasswordEncoder())
                        .withUser("1")
                        .password(new BCryptPasswordEncoder().encode("1")).roles("vip1","vip2")
                        .and()  // 用and方法认证多个用户
                        .passwordEncoder(new BCryptPasswordEncoder())
                        .withUser("2")
                        .password(new BCryptPasswordEncoder().encode("2")).roles("vip3");


    }
}

controller层

package com.demo.webdemo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Controller
public class SecurityController {
    
    

    @GetMapping("/")
    public String index() {
    
    
        return "welcome";
    }
    /**
     * 登陆页
     * @return
     */
    @GetMapping("/seclogin")
    public String loginPage() {
    
    
        return "sec_login";
    }


    /**
     * level1页面映射
     * @param path
     * @return
     */
    @GetMapping("/level1/{path}")
    public String level1(@PathVariable("path")String path) {
    
    
        return "level1/"+path;
    }

    /**
     * level2页面映射
     * @param path
     * @return
     */
    @GetMapping("/level2/{path}")
    public String level2(@PathVariable("path")String path) {
    
    
        return "level2/"+path;
    }

    /**
     * level3页面映射
     * @param path
     * @return
     */
    @GetMapping("/level3/{path}")
    public String level3(@PathVariable("path")String path) {
    
    
        return "level3/"+path;
    }
}

login页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<center>
    <h1>欢迎登录</h1>
        <!--  注意使用thymeleaf语法。请求提交方式为post,但@GetMapping("/seclogin")能接收   -->
    <form  th:action="@{/seclogin}" method="post">
<input type="text" id="inputEmail" name="usn" class="form-control" th:placeholder="#{login.username}" placeholder="账号" required="" autofocus="">
<br>
<input type="password" id="inputPassword" name="pwd" class="form-control" th:placeholder="#{login.password}"  placeholder="密码" required="">
    <br> <br>
        <input type="checkbox" name="remember">记住我
        <br>
    <input type="submit" value="sumit">
    </form>
</center>
</body>
</html>

其他前端页面代码 略。。。。。

猜你喜欢

转载自blog.csdn.net/m0_46267375/article/details/108596613