开篇
最近一段时间学习了 Spring Security
,并成功整合到了项目中(基于 Sping-boot2.x
)。
在这里, 准备将学习(踩坑)过程记录一下,同时讲述下如何一步一步应用到项目中的。
创建一个 Springboot 工程(springboot2.x)
本文以及后面的系列文章涉及到的源代码都会上传到如下地址.
引入 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 http://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.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo-01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo-01</name>
<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-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
复制代码
新建一个 Controller 类
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class IndexController {
@GetMapping("/hello")
public Object sayHello(){
return "hello world";
}
}
复制代码
启动项目
项目启动成功后,用浏览器访问接口 http://localhost:8080/hello, 如果项目中没有引入Spring Security
依赖, 接口返回值就是 “hello world” 字符串。
但是因为我们这里的实际效果是, 浏览器会自动跳转到 http://localhost:8080/login 登陆页面。
如下图所示:
为何会出现这张情况
简单理解就是, 当我们引入 Spring Secutiry
依赖后, 不做任何配置, 其实已经有一个过滤器是生效了, 默认所有接口都需要登陆才能访问.
因为我们现在是以实战为主, 所以我们不过多讨论里面的原理, 后面会专门写文章去讲解.
如何才能得到我们想要的结果
Spring Secutiry
默认提供了一个用户名, 默认值是 user
,源码中可以查到.
密码在项目启动时已经在控制台打印出来了。
当我们在登陆页, 输入用户名和密码后, 就会得到我们期望的接口返回值.
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END