SpringBoot 整合security、thymeleaf

源代码boot-security.zip

1、pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <!--thymeleaf只能支持到这个版本-->
        <version>2.0.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.k</groupId>
    <artifactId>boot-security</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>boot-security</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!--thymeleaf 和 springsecurity4 整合-->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2、SecurityConfig

package com.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
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().loginPage("/toLogin").loginProcessingUrl("/login").
                usernameParameter("username").passwordParameter("password");
        //开启注销功能
        http.logout().logoutSuccessUrl("/");
        //关闭csrf功能
        http.csrf().disable();
        //记住我 cookies默认保存2周
        http.rememberMe().rememberMeParameter("remember");
    }

    /**
     * 认证
     * springboot 2.1.x可以直接使用
     * 密码编码 PasswordEncoder
     * 在spring security 5.0+ 新增了很多的加密方法
     */

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //正常要从数据库读
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("kikyo").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div style="width: 200px;height: 50px;">
    <form action="/login" method="post">
        <label>用户名:</label>
        <input type="text" name="username" value=""> <br>
        <label>密码:</label>
        <input type="password" name="password" value=""> <br>
        <input type="submit" name="" value="提交"> <br>
        <input type="checkbox" name="remember">记住我 <br>
    </form>
</div>
</body>
</html>

3、RouteController

package com.controller;

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

@Controller
public class RouteController {

    @RequestMapping({"/", "/index"})
    public String index() {
        return "index";
    }

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

    @RequestMapping("/level1/{id}")
    public String level1(@PathVariable("id") int id) {
        return "views/level1/" + id;
    }

    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable("id") int id) {
        return "views/level2/" + id;
    }

    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id") int id) {
        return "views/level3/" + id;
    }
}

4、index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>

<!--目前不能用,待以后解决-->
<!--<a href="/" target="_blank">首页</a><br>-->
<!--<div sec:authentication="!isAuthenticated()">-->
<!--    <a href="/login" target="_blank">登录</a><br>-->
<!--</div>-->
<!--<div sec:authentication="isAuthenticated()">-->
<!--    <a href="#" target="_blank">-->
<!--        账户:<span sec:authentication="name"></span><br>-->
<!--        角色:<span sec:authentication="principal.authorities"></span><br>-->
<!--    </a><br>-->
<!--</div>-->
<!--<div sec:authentication="isAuthenticated()">-->
<!--    <a href="/logout" target="_blank">注销</a><br>-->
<!--</div>-->

<hr>

<!--菜单根据用户的权限动态实现-->
<div sec:authorize="hasRole('vip1')">
    <a href="/level1/1" target="_blank">/level1/1</a>
    <a href="/level1/2" target="_blank">/level1/2</a>
    <a href="/level1/3" target="_blank">/level1/3</a>
</div>

<hr>

<div sec:authorize="hasRole('vip2')">>
    <a href="/level2/1" target="_blank">/level2/1</a>
    <a href="/level2/2" target="_blank">/level2/2</a>
    <a href="/level2/3" target="_blank">/level2/3</a>
</div>

<hr>

<div sec:authorize="hasRole('vip3')">>
    <a href="/level3/1" target="_blank">/level3/1</a>
    <a href="/level3/2" target="_blank">/level3/2</a>
    <a href="/level3/3" target="_blank">/level3/3</a>
</div>

<hr>

</body>
</html>

5、html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div style="width: 200px;height: 50px;">
    <input type="text" name="userName" value=""> <br>
    <input type="password" name="password" value=""> <br>
    <input type="button" name="userName" value="提交"> <br>
</div>
</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>level1  1</h1>
</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>level1  2</h1>
</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>level1  3</h1>
</body>
</html>
posted @ 2021-03-05 22:35  一只桔子2233  阅读(236)  评论(0编辑  收藏  举报