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>

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

Spring BootThymeleaf结合使用可以很容易地创建一个基本的权限管理系统。下面是一个简单的步骤: 1. 创建Spring Boot项目 首先,创建一个新的Spring Boot项目。你可以使用Spring Initializr或者在IDE中创建。 2. 添加依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 这些依赖将引入Spring SecurityThymeleaf。 3. 配置SecuritySpring Security中,你可以使用注释或Java Config来配置安全性。这里我们将使用Java Config。 首先,创建一个名为SecurityConfig的类,继承WebSecurityConfigurerAdapter。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login").permitAll() .antMatchers("/**").hasRole("USER") .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/") .permitAll() .and() .logout() .logoutSuccessUrl("/login") .permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("{noop}password").roles("USER"); } } ``` 这个配置文件将允许所有用户访问/login页面,但只有具有USER角色的用户才能访问其他页面。默认情况下,Spring Security将使用HTTP Basic身份验证来验证用户,但是我们将使用内存身份验证来添加一个用户。 4. 创建登录页面 在resources/templates目录下创建一个名为login.html的文件,用于登录页面。以下是一个简单的示例: ```html <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <title>Login</title> </head> <body> <h1>Login</h1> <form th:action="@{login}" method="post"> <label for="username">Username:</label> <input type="text" id="username" name="username" /><br /> <label for="password">Password:</label> <input type="password" id="password" name="password" /><br /> <input type="submit" value="Login" /> </form> </body> </html> ``` 在这个页面中,我们使用了Thymeleaf表达式来生成表单。 5. 创建受保护的页面 在resources/templates目录下创建一个名为index.html的文件,用于显示受保护的页面。以下是一个简单的示例: ```html <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <title>Protected Page</title> </head> <body> <h1>Protected Page</h1> <p>Welcome, <span th:text="${#authentication.name}"></span>!</p> <a th:href="@{/logout}">Logout</a> </body> </html> ``` 在这个页面中,我们使用了Thymeleaf表达式来显示当前用户的名称,并使用链接注销用户。 6. 运行应用程序 现在,启动应用程序并访问http://localhost:8080/login,你将会看到登录页面。输入用户名user和密码password,你将被重定向到受保护的页面。 以上就是一个简单的Spring BootThymeleaf结合使用的权限管理系统的实现步骤。你可以根据自己的需求对其进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值