SpringSecurity入门

SpringBoot基础环境

  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>
        <version>2.6.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.spyu</groupId>
    <artifactId>auth</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>auth</name>
    <description>auth</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 
        <!--自己开发的第三方工具类项目-->
        <dependency>
            <groupId>com.spyu</groupId>
            <artifactId>common-spring-boot-starter</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>
  1. 配置yml文件
点击查看代码
server:
  port: 8090
  servlet:
    encoding:
      charset: UTF-8
spring:
  application:
    name: auth
  1. controller测试
点击查看代码
@RequestMapping("/test")
@RestController
public class TestController {
 
    @GetMapping("/boot")
    public ResultModel<String> testBoot(HttpServletRequest request) {
        ResultModel<String> resultModel = new ResultModel<>();
        resultModel.setCode(200);
        resultModel.setStatus(true);
        resultModel.setRequestPath(request.getRequestURI());
        resultModel.setResponseTime(DateUtils.getCurrentDateTime());
        resultModel.setMessage("请求testBoot路径成功!");
        return resultModel;
    }
}
  1. 请求路径 http://localhost:8090/test/boot

image

引入SpringSecurity

<!--spring security整合spring boot-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>

启动springboot项目

启动tomcat生成登录的密码,用户为user
image

登录界面

image

登录成功

image

退出登录

image


上面就完成了一个简单的springsecurity功能,只能在登录之后,才可以访问我们的测试接口。但是整个密码和用户是我们security默认的,我们需要连接数据库访问。


posted @ 2023-07-10 21:47  sunpeiyu  阅读(4)  评论(0编辑  收藏  举报