Introduction
JWT 全称 Json Web Token。是符合某一种标准,规范的token。也就是说JWT是token,但是不是所有token都是JWT。 传播格式:Json Object。 其特点是存储在客户端,服务器在接收到token并验证其身份的过程中不需要访问数据库或者第三方服务去验证它。token自带的信息就已经足够进行验证了。
JWT结构
Overview
上面的algorithm部分指定了签名的加密算法,为HS256,这是一个对称加密算法。左边的base64算法和加密算法计算后的字符串,三个部分由 “.” 分开,分别对应右边的header, payload, signture。
Header
header 部分包含了token类型,和用于签名的算法。
Payload
Payload 里包含的信息也叫claim信息,也就是声明信息。 我们首选注册过的: registered claims。 www.iana.org/assignments…
其中JWT保留了7个默认的registered claims Payload里面一般包含了claim信息,结构为 key : value
例如:
{ "sub": "1234567890",
"name": "John Doe",
"iat": 1516239022 }
Signature
通过header部分的签名算法,可以对header和payload这两部分的信息进行签名。 这里的签名算法属于加密算法。
对于对称加密来说,有密钥。这个密钥能同时进行加密和解密。
对于非对称加密来说,有公钥和私钥。用私钥加密的话,只能用公钥解密。反之亦然。
HTTP Authentication
HTTP 为权限控制和验证提供了一个总体的框架。 在这个框架下面。server能质疑一个客户端请请求,要求客户端提供验证信息。
基于这个总框架,有多个Authentication Scheme:
Spring Security 结合 JWT 实现
spring security introduction
spring security 是什么?
Spring Security is really just a bunch of servlet filters that help you add authentication and authorization to your web application.
Architecture docs.spring.io/spring-secu…
Authentication
验证用户是自己所声称的那个人。
Authorization
Authenticate之后确认用户是否有权限访问他想访问的资源。
Servlet filter
以前
http requests -> dispatcher servlet -> controller/restcontroller
现在
http requests -> servlet filters -> dispatcher servlet -> controller/restcontroller
401 vs 403
401 Unauthorizedis the status code to return when the client provides no credentials or invalid credentials.403 Forbiddenis the status code to return when a client has valid credentials but not enough privileges to perform an action on a resource
token expired vs token revoked
revoke主动行为 some people/orgnization revoke credentialexpired被动行为 credential expired
access token vs refresh token
- access & expire
- short time vs long time
bearer token vs basic token
swagger.io/docs/specif… swagger.io/docs/specif…
Implementation key elements table
| Class | Type | provider | Note |
|---|---|---|---|
| UserDetailsService | Interface | Spring Security | Help to retrieve UserDetails from db |
| UserDetails | Interface | Spring Security | need to be implemented by dev via Entity class |
| UserDetailDao | Interface | Developer | created by dev to get UserDetailsEntity |
| AuthenticationProvider | Interface | Spring Security | Responsible for doing actual authentication |
| OncePerRequestFilter | Interface | Spring security | Authentication level filter for each request |
| SecurityFilterChain | Interface | Spring security | Overall filter configuration |
| AuthenticationManager | Interface | Spring security | Authenticate username and password |
| UsernamePasswordAuthenticationToken | Class | Spring security | store user information |