随笔 - 323  文章 - 0  评论 - 4  阅读 - 17万

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   dreamstar  阅读(71)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示