springboot中整合SpringSecurity

it2025-10-20  6

1.项目的构成

2.application.yml的配置

spring.thymeleaf.cache=false

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.3.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.jiangk</groupId> <artifactId>testspringsecurity</artifactId> <version>0.0.1-SNAPSHOT</version> <name>testspringsecurity</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity5 --> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity4</artifactId> <version>3.0.4.RELEASE</version> </dependency> <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.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> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

4.前台页面的构成

主页:First.html

<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"> <head> <meta charset="UTF-8" > <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>FrameDraftWeb</title> <link rel="stylesheet" href="../../css/bdwd.css"> <link rel="stylesheet" href="../../css/llf.css"> <link rel="stylesheet" href="../../../../../../java_project/server/WebContent/jkBigDataWeb/jkBigDataWeb/jkBigDataWeb/layui/css/layui.css"> </head> <body > <h1> <a href="#">这是首页</a></h1> <a th:href="@{/view1/1}">VIp1</a> <p></p> <a th:href="@{/view2/1}">VIp2</a> <p></p> <a th:href="@{/view3/1}">VIp3</a> <p></p> <!--如果没有登录显示登录按钮--> <div sec:authorize="!isAuthenticated()"> <a th:href="@{/login}">登录</a> </div> <!--登录了就是用户名和注销--> <div> <div sec:authorize="!isAuthenticated()"> <a th:href="@{/logout}">注销</a> <div> <a class="layui-colla-item"> 用户名:<span sec:authentication="name"></span> 角色:<span sec:authentication="principal.authorities"></span> </a> </div> </div> </div> </body> </html>

登陆页面:login.html

<!doctype html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Login</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="../assets/vendor/bootstrap/css/bootstrap.min.css"> <link href="../assets/vendor/fonts/circular-std/style.css" rel="stylesheet"> <link rel="stylesheet" href="../assets/libs/css/style.css"> <link rel="stylesheet" href="../assets/vendor/fonts/fontawesome/css/fontawesome-all.css"> <style> html, body { height: 100%; } body { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; padding-top: 40px; padding-bottom: 40px; } </style> </head> <body> <!-- ============================================================== --> <!-- login page --> <!-- ============================================================== --> <div class="splash-container"> <div class="card "> <div class="card-header text-center"><a href="../index.html"><img class="logo-img" src="../assets/images/logo.png" alt="logo"></a> <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p> <span class="splash-description">Please enter your user information.</span> </div> <div class="card-body"> <form th:action="@{/login}" method="post"> <div class="form-group"> <input class="form-control form-control-lg" name="username" type="text" placeholder="Username" autocomplete="off"> </div> <div class="form-group"> <input class="form-control form-control-lg" name="password" type="password" placeholder="Password"> </div> <div class="form-group"> <label class="custom-control custom-checkbox"> <input type="checkbox" name="rem" >记住我<br/> </label> </div> <button type="submit" class="btn btn-primary btn-lg btn-block">Sign in</button> </form> </div> <div class="card-footer bg-white p-0 "> <div class="card-footer-item card-footer-item-bordered"> <a href="#" class="footer-link">Create An Account</a></div> <div class="card-footer-item card-footer-item-bordered"> <a href="#" class="footer-link">Forgot Password</a> </div> </div> </div> </div> <!-- ============================================================== --> <!-- end login page --> <!-- ============================================================== --> <!-- Optional JavaScript --> <script src="../assets/vendor/jquery/jquery-3.3.1.min.js"></script> <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.js"></script> </body> </html>

内容页面view/view1/1.html

<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>FrameDraftWeb</title> <link rel="stylesheet" href="../../css/llf.css"> <link rel="stylesheet" href="../../css/bdwd.css"> <link rel="stylesheet" href="../../../../../../../../java_project/server/WebContent/jkBigDataWeb/jkBigDataWeb/jkBigDataWeb/layui/css/layui.css"> </head> <body > <h1>VIP1</h1> <a th:href="@{/}">回到首页</a> <a th:href="@{/logout}">注销</a> </body> </html>

5.config中springSecurity的配置

package com.jiangk.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; //AOP:面向切面编程 @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { //请求授权的规则 http.authorizeRequests().antMatchers("/").permitAll() .antMatchers("/view1/**").hasRole("vip1") .antMatchers("/view2/**").hasRole("vip2") .antMatchers("/view3/**").hasRole("vip3"); //没有权限跳转登录页面 /* * ,另外action="/authentication/form"要与.loginProcessingUrl("/authentication/form")相对应,原因为: * 由于security是由UsernamePasswordAuthenticationFilter这个类定义登录的, * 里面默认是/login路径,我们要让他用我们的/authentication/form路径, * 就需要配置.loginProcessingUrl("/authentication/form") * * */ http.formLogin().loginPage("/login"); //防止网站攻击: //开启注销功能 http.logout().logoutSuccessUrl("/"); //开启记住我功能,cookies有效期2周 http.rememberMe().rememberMeParameter("rem"); } //认证 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //应该来自数据库 auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("jiangk").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip3") .and() .withUser("test").password(new BCryptPasswordEncoder().encode("123")).roles("vip2"); } }

6.controller类的编写


package com.jiangk.Controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @Controller public class routerController { @RequestMapping({"/","/index","/main"}) public String index(){ return "First"; } @RequestMapping("/login") public String login(){ return "view/login"; } @RequestMapping("/view1/{id}") public String toContent1(@PathVariable int id){ return "view/view1/"+id; } @RequestMapping("/view2/{id}") public String toContent2(@PathVariable int id){ return "view/view2/"+id; } @RequestMapping("/view3/{id}") public String toContent3(@PathVariable int id){ return "view/view3/"+id; } }

补充:springSecurity的工作流程如下 具体内容参见博客

https://blog.csdn.net/u012702547/article/details/89629415

最新回复(0)