springboot中整合SpringSecurity

本文介绍了如何在SpringBoot项目中整合SpringSecurity,包括项目的构成、application.yml与pom.xml的配置、页面设计以及SpringSecurity的配置和Controller的编写。详细步骤及SpringSecurity的工作流程见原文链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.youkuaiyun.com/u012702547/article/details/89629415

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值