新建一个SpringBoot项目
选择依赖包
项目目录
pom.xml依赖
<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>
<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>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
在application.yml文件中加入:修改端口
写一个controller
有一个login,返回“Hello ! Spring Boot ,Spring Security!”+登录的用户名
package com.example.spring_security.controller;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoginController {
@GetMapping("/")
@ResponseBody
public String showHome(){
//当前登录名
String name = SecurityContextHolder.getContext().getAuthentication().getName();
return "Hello ! Spring Boot ,Spring Security!"+name;
}
}
启动项目,注意控制台日志输出:
比往常多一个password。
然后打开浏览器,输入http:localhost:8082/login
并不会像之前一样输出:Hello ! Spring Boot ,Spring Security!
,Spring Security默认有一个user账号,密码就是控制台输出的密码。
我们登录一下
账号:user
密码:b4206af6-007e-422f-9f92-9185c5ab038f
密码每一个人不一样的,看自己的控制台
说明我们的方法进去了。
注意:
只要POM依赖中有Security就会有权限管理。 测试的时候,没有登录会默认取/login路劲。 测试用“/”就好。
通过这个测试用例,可以简单对Spring Boot Security的认识。但是还是推荐使用Apache Shiro。因为简单。该有的功能都有。