入门案例

  1. 创建SpringBoot项目

  2. 在pom中加入web、security的依赖

    1. <dependency>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter-web</artifactId>
    4. </dependency>
    5. <dependency>
    6. <groupId>org.springframework.boot</groupId>
    7. <artifactId>spring-boot-starter-security</artifactId>
    8. </dependency>
  1. 编写一个测试的Controller

    1. @RestController
    2. public class TestController {
    3. @GetMapping("/add")
    4. public String add() {
    5. return "hello security";
    6. }
    7. }

启动该项目,在启动时会在控制台打印一句话:

  1. Using generated security password: 9042005d-094d-45a1-87ef-a840378f5e76

此时直接在浏览器访问:http://localhost:8080/add ,并不会直接返回预期的字符串,而是跳转到了一个登录页面。

spring security登录页面的默认用户名为 user,密码为控制台打印出来的那句UUID。

登录之后即可看到 hello security