Spring Security 认证,登陆拦截体验

使用Spring Security框架之前,我们的应用api是谁都可以访问的

引入Spring Security之前 的 Spring Boot应用

1.创建一个Spring boot application, 有如下api

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
   
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
}
View Code

2.启动应用 

3.测试

访问http://localhost:8080/hello,即可得到hello api 的返回

 

使用Spring Boot + Spring Security

1.引入Spring Security 依赖,加入Spring Security 依赖后,项目的所有接口都会被自动保护起来,需要登录认证才能访问接口API。

它还会生成一个用户,其密码是随机生成的,并记录在控制台中,可用于使用表单或基本认证(basic authentication)进行认证

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
View Code

2.启动应用

应用启动时,控制台会打印出随机生成的密码, 默认情况下登录的用户名是 user

3.测试

当用户访问接口http://localhost:8080/hello, 会跳转到登录页面,输入用户名 user, 和 如上password 后,才会得到hello api的正常返回。

posted on 2024-01-23 14:33  dreamstar  阅读(40)  评论(0编辑  收藏  举报