Spring security 系列博客目录
- Spring Security 入门 - 01 将 Spring security 引入到工程
- Spring security 入门 - 02 自定义用户登录页面和登录处理逻辑
- Spring security 入门 - 03 自定义登录成功后的处理逻辑
- Spring security 入门 - 04整合 jwt
对应源代码
- Spring Security 01- 将 Spring security 引入到工程
- Spring security 02-自定义用户登录页面和登录处理逻辑
- Spring security 03-自定义登录成功后的处理逻辑
- Spring security 04-整合 jwt
开篇
最近一段时间学习了 Spring Security,并成功整合到了项目中(基于Sping-boot2.x)。在此准备将踩坑过程记录一下,顺便讲述下如何一步一步应用到项目中的。
创建一个 Springboot 工程(springboot2.x)
https://github.com/nimo10050/spring-security-sample.git
引入 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</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</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
正常情况下浏览器会打印出来 “hello world” 字符串。但是我们因为我们引入了 Spring Security 依赖。浏览器会自动跳转到 http://localhost:8080/login 。如下图:
如何才能得到我们想要的页面
用户名默认是 user,源码中可以查到。密码在项目启动时已经在控制台打印出来了。
输入用户名和密码