springboot安全之整合spring security实现(只有登录才有权限、不同用户显示不同内容、记住我)

时间:2022-07-23
本文章向大家介绍springboot安全之整合spring security实现(只有登录才有权限、不同用户显示不同内容、记住我),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1、新建一个springboot项目,选择web、thymeleaf、spring security

2、创建好当前文件和目录结构

3、首先是一些相关的界面

pom.xml

<?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.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ging</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>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>
        <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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-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>

welcome.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
        xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">欢迎光临武林秘籍管理系统</h1>
<div sec:authorize="!isAuthenticated()">
    <h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/userlogin}">请登录</a></h2>
</div>
<div sec:authorize="isAuthenticated()">
    <h2 align="center">
        <span sec:authentication="name"></span>,您好,您的角色有:
        <span sec:authentication="principal.authorities"></span>
        <form th:action="@{/logout}" method="post">
            <input type="submit" value="注销"/>
        </form>
    <h2>
</div>
<hr>

<div sec:authorize="hasRole('VIP1')">
    <h3>普通武功秘籍</h3>
    <ul>
        <li><a th:href="@{/level1/1}">罗汉拳</a></li>
        <li><a th:href="@{/level1/2}">武当长拳</a></li>
        <li><a th:href="@{/level1/3}">全真剑法</a></li>
    </ul>
</div>
<div sec:authorize="hasRole('VIP2')">
    <h3>高级武功秘籍</h3>
    <ul>
        <li><a th:href="@{/level2/1}">太极拳</a></li>
        <li><a th:href="@{/level2/2}">七伤拳</a></li>
        <li><a th:href="@{/level2/3}">梯云纵</a></li>
    </ul>
</div>
<div sec:authorize="hasRole('VIP3')">
    <h3>绝世武功秘籍</h3>
    <ul>
        <li><a th:href="@{/level3/1}">葵花宝典</a></li>
        <li><a th:href="@{/level3/2}">龟派气功</a></li>
        <li><a th:href="@{/level3/3}">独孤九剑</a></li>
    </ul>
</div>
</body>
</html>

说明:重要的地方已经加粗放大了。

login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1 align="center">欢迎登陆武林秘籍管理系统</h1>
    <hr>
    <div align="center">
        <form th:action="@{/userlogin}" method="post">
            用户名:<input name="username"/><br>
            密码:<input name="password"><br/>
            <input type="checkbox" name="remember">记住我<br/>
            <input type="submit" value="登陆">
        </form>
    </div>
</body>
</html>

这里只展示其中一个1.html,它们大致相同:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <a th:href="@{/}">返回</a>
    <h1>罗汉拳</h1>
    <p>罗汉拳站当央,打起来不要慌</p>
</body>
</html>

KungfuController.java

package com.ging.springbootsecurity.controller;

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

@Controller
public class KungfuController {
    private final String PREFIX = "pages/";
    /**
     * 欢迎页
     * @return
     */
    @GetMapping("/")
    public String index() {
        return "welcome";
    }
    
    /**
     * 登陆页
     * @return
     */
    @GetMapping("/userlogin")
    public String loginPage() {
        return PREFIX+"login";
    }
    
    
    /**
     * level1页面映射
     * @param path
     * @return
     */
    @GetMapping("/level1/{path}")
    public String level1(@PathVariable("path")String path) {
        return PREFIX+"level1/"+path;
    }
    
    /**
     * level2页面映射
     * @param path
     * @return
     */
    @GetMapping("/level2/{path}")
    public String level2(@PathVariable("path")String path) {
        return PREFIX+"level2/"+path;
    }
    
    /**
     * level3页面映射
     * @param path
     * @return
     */
    @GetMapping("/level3/{path}")
    public String level3(@PathVariable("path")String path) {
        return PREFIX+"level3/"+path;
    }


}

MySecurityConfig.java

package com.ging.springbootsecurity.config;

import org.springframework.context.annotation.Configuration;
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;

@Configuration
@EnableWebSecurity
public class MySecurityConfig 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");
        //开启自动配置的登录功能
        //1、login请求来到登录页面
        //2、重定向/login?Error表示登录失败
        //3、设置转到我们自己的登录界面
        //4、自定义的登录界面要发送post请求,action需要为/login,字段要匹配这里的
        http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/userlogin");//.loginProcessingUrl("/login")
        //开启自动配置的注销功能
        //1、访问logout表示用户注销,清空session
        //2、默认注销成功会返回login?logout页面
        //3、设置注销成功来到首页
        http.logout().logoutSuccessUrl("/");
        //开启记住我功能
        http.rememberMe().rememberMeParameter("remember");
    }

    //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456"))
                .roles("VIP1","VIP2")
                .and()
                .withUser("lisi").password(new BCryptPasswordEncoder().encode("123456"))
                .roles("VIP2","VIP3");
    }
}

接下来跟着实际的操作一步步探索。

启动服务器:

首先输入localhost:8080,会自动跳转到welcome.html,由于我们配置了authorizeRequests()和formLogin(),并且设置了/level?/**的权限,所以我们在浏览器输入localhost:8080/level/1等请求时,由于没有登录,即不是哪一个用户,所以会跳转到springboot自定义的login界面。

如果我们不定义自己的登录页面的话,系统确实会跳转到springboot自己的界面,但是我们若想要跳转到自己的界面呢?

 http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/userlogin");//.loginProcessingUrl("/login")

这里需要设置用户名和密码的名称,以及自动跳转的页面,即发送/userlogin请求,而/userlogin请求则会返回我们真正的登录界面:login.html。在login.html中输入框里面的name要和这里的分别对应,同时我们还要发送post请求,对应的action要与发送的请求相同,即为@{/userlogin}。我们设置记住我时,同样要置http.rememberMe().rememberMeParameter("remember");对应的名称。然后我们输入:

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456"))
                .roles("VIP1","VIP2")
                .and()
                .withUser("lisi").password(new BCryptPasswordEncoder().encode("123456"))
                .roles("VIP2","VIP3");
    }

这里定义好的角色,一般这里是从数据库中获取,这里就只进行模拟。比如输入:zhangsan,密码:123456,我们就会进入到:

在welcome.html界面可以通过sec属性来获取相关的值。通过isAuthenticated来判断当前的用户是否具有权限,有的化我们的欢迎界面就变化了,显名称以及角色。然后在不同的代码块中我们有<div sec:authorize="hasRole('VIP1')">标识。zhangsan拥有“VIP1”和“VIP2”角色,因此可以看到普通武功秘籍和高级武功秘籍。我们点击注销,就可以退出登录。在配置文件中定义了注销后返回到主界面。由于此时没有了权限,则会显示欢迎您,游客。。。

接下来我们再试一下登录:lisi 123456,并勾选记住我。

点进去看一本:

它是VIP2和VIP3,因此可以看到高级武功秘籍和绝世武功秘籍。由于我们勾选了记住我,所以我们关闭这个界面,在访问localhost:8080,此时就不需要我们再进行登陆了。

总结:基本上实现了普通游客只有在登录了之后才能够访问到level?/**下的内容,强行访问会被拦截到登录界面。用户登陆之后根据不同角色显示不同内容。勾选记住我后会保存一个cookie,再次访问不需要再登录,点击注销之后删除cookie,退出登录。