一、项目结构

项目结构

二、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>
        <version>2.4.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>site.kexing</groupId>
    <artifactId>springboot-security</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-security</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>

        <!-- thymeleaf-extras-springsecurity5 -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>
        <!--        security-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
<!--        thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
<!--        web-->
        <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>
    </dependencies>

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

</project>

三、编写SecurityConfig继承WebSecurityConfigurerAdapter

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//    授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //请求授权规则
        http.authorizeRequests()
                //首页所有人可以访问
                //vip每种等级对应不同的角色
                .antMatchers("/").permitAll()
                .antMatchers("/vip1/**").hasRole("vip1")
                .antMatchers("/vip2/**").hasRole("vip2")
                .antMatchers("/vip3/**").hasRole("vip3");

        //没有权限默认到登录页面
        http.formLogin().loginPage("/tologin").usernameParameter("username").passwordParameter("pwd").loginProcessingUrl("/login");
        //开启注销功能,注销成功跳到首页
        http.csrf().disable();
        http.logout().logoutSuccessUrl("/");
        //记住我
        http.rememberMe().rememberMeParameter("remember");
    }

//    认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //这里从内存中读取用户
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("kexing").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");
    }
}

这里总共设置了三种角色对应不同的访问权限,首页允许所有人访问,这里更改了springsecurity自带的登录页面:
http.formLogin():没有权限默认到登录页面
loginPage():用户未登录时,访问任何资源都转跳到该路径,即登录页面
loginProcessingUrl():登录表单formaction的地址,也就是处理认证请求的路径
usernameParameter():登录表单form中用户名输入框inputname名,不修改的话默认是username
passwordParameter():登录表单form中用户名输入框inputname名,不修改的话默认是password

springsecurity中需要对传输的明文密码加密,这里选用的BCrypt加密方法,重新对password进行编码
因为没有连数据库,所以这里我模拟的是从内存中认证用户

四、首页

首页中当用户未登录时,显示登陆按钮;当用户登录时,显示用户名,权限,注销按钮
因为不同用户拥有不同的角色,也就是不同的权限,所以首页需要展示给用户的则是该用户拥有的权限对应的版块,也就是实现动态菜单

引入sec命名空间xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
                xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>首页</title>
    <!--semantic-ui-->
    <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
    <link th:href="@{/qinjiang/css/qinstyle.css}" rel="stylesheet">
</head>
<body>

<!--主容器-->
<div class="ui container">

    <div class="ui segment" id="index-header-nav" th:fragment="nav-menu">
        <div class="ui secondary menu">
            <a class="item"  th:href="@{/index}">首页</a>

            <!--登录注销-->
            <div class="right menu">

                <!--如果未登录 显示登陆页面-->
                <div sec:authorize="!isAuthenticated()">
                    <a class="item" th:href="@{/tologin}">
                        <i class="address card icon"></i> 登录
                    </a>
                </div>

                <!--如果已经登陆 显示用户名+注销-->
                <div sec:authorize="isAuthenticated()">
                    <a class="item">
                       用户名:<span sec:authentication="name"></span>
                        &nbsp;&nbsp;权限:<span sec:authentication="principal.authorities"></span>
                    </a>
                    <a class="item" th:href="@{/logout}">
                        <i class="address card icon"></i> 注销
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="ui segment" style="text-align: center">
        <h3>Spring Security Study by kexing</h3>
    </div>

    <div>
        <br>
        <div class="ui three column stackable grid">
            <div class="column" sec:authorize="hasRole('vip1')">
                <div class="ui raised segment">
                    <div class="ui">
                        <div class="content">
                            <h5 class="content">Vip 1</h5>
                            <hr>
                            <div><a th:href="@{/vip1/1}"><i class="bullhorn icon"></i> vip1-1</a></div>
                            <div><a th:href="@{/vip1/2}"><i class="bullhorn icon"></i> vip1-2</a></div>
                            <div><a th:href="@{/vip1/3}"><i class="bullhorn icon"></i> vip1-3</a></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="column" sec:authorize="hasRole('vip2')">
                <div class="ui raised segment">
                    <div class="ui">
                        <div class="content">
                            <h5 class="content">Vip 2</h5>
                            <hr>
                            <div><a th:href="@{/vip2/1}"><i class="bullhorn icon"></i> vip2-1</a></div>
                            <div><a th:href="@{/vip2/2}"><i class="bullhorn icon"></i> vip2-2</a></div>
                            <div><a th:href="@{/vip2/3}"><i class="bullhorn icon"></i> vip2-3</a></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="column" sec:authorize="hasRole('vip3')">
                <div class="ui raised segment">
                    <div class="ui">
                        <div class="content">
                            <h5 class="content">Vip 3</h5>
                            <hr>
                            <div><a th:href="@{/vip3/1}"><i class="bullhorn icon"></i> vip3-1</a></div>
                            <div><a th:href="@{/vip3/2}"><i class="bullhorn icon"></i> vip3-2</a></div>
                            <div><a th:href="@{/vip3/3}"><i class="bullhorn icon"></i> vip3-3</a></div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
    
</div>


<script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/qinjiang/js/semantic.min.js}"></script>

</body>
</html>

sec:authorize="isAuthenticated()" 用于判断该用户是否被认证,也就是是否登录
sec:authorize="hasRole('vip1')" 只允许对应角色访问

因为前面的config类中已经对用户进行了角色认证,用户kexing的权限只能访问vip1,用户root的权限可以访问vip1,vip2,vip3所有权限

未登录时:
未登录
登录用户一 kexing
登录用户一 kexing
登录成功,kexing只有vip1权限,只能访问vip1
登录成功
注销kexing后使用root登录
root登录
记住我
记住我
会生成一个cookie,默认的过期时间是14天
cookie

最后修改:2021 年 11 月 15 日 05 : 17 PM
如果觉得我的文章对你有用,请随意赞赏