来一起学SpringSecurity:②Business is too complicated,Show me the demo
先跑一个简单的demo,初步认识SpringSecurity
。
第一步、新建SpringBoot工程(伪第一步)
启动项目时选择导入springweb
和springsecurity
这两个依赖,在项目启动成功后,SpringSecurity因为SpringBoot的自动配置,已经为项目的所有接口都提供了访问保护。
第二步、写个controller接口测试url是否被保护
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello() {
return "hello";
}
}
第三步、启动项目,测试接口
- 启动项目时,可以看到控制台输出了默认的登录密码,其实就是一串uuid
- 浏览器访问测试接口
http://localhost:8080/hello
你可以明确地看到url自动跳转到了http://localhost:8080/login
并提示输入账号密码。 - 输入账号:user
- 密码:控制台输出的uuid
就可以正常显示接口的返回值 -> hello
第四步、小朋友,你是不是有很多问号
为什么是user和uuid呢?又为什么会跳转到一个login的表单登录页面呢?
1.首先通过全局搜索
Using generated security password
找到了SecurityProperties
中关于Springsecurity的默认配置@ConfigurationProperties(prefix = "spring.security") public class SecurityProperties { ... public static class User { /** * Default user name. */ private String name = "user"; /** * Password for the default user name. */ private String password = UUID.randomUUID().toString(); ... } ... }
很明显了,这是SpringBoot的自动配置帮我们设定的默认值。那自然就可以在
application.yml
中修改默认配置spring: security: user: name: shafish password: 123456
ok,现在使用修改后的账号密码就可以登录了。
- 2.至于第一次访问hello时跳转到登录页面,这就开始有点安全的味道了。
简单类似请求拦截,输入账号密码登录成功后,服务端会返回一个Authorization
的授权值给发起者。Authorization
对应的值是一个经过base64加密的用户名:密码
串
所以说如果是第一次登录,那肯定是没有Authorization
这个东西的,就会跳转到登录页面。当你登录后再重新访问一遍http://localhost:8080/hello
,打开控制台就可以看到request请求头中包含了Authorization
这就是SpringSecurity
中关于认证和授权的基本使用流程介绍,在SpringBoot
整合SpringSecurity
中,默认只有认证,授权是对所有url都可以登录访问的。如何完善认证使用
和开放更细粒度的授权
就是我们学习SpringSecurity
的最终目的。
可能有同学好奇,跳转的login登录页面在哪?
看org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.generateLoginPageHtml()就知道了。
现在已经算正式入门了,下一章就开始学习SpringSecurity
相关配置,要继续坚持哟。