JWT 详解 & 结合Spring Security的登陆全流程实现

309 阅读2分钟

Introduction

JWT 全称 Json Web Token。是符合某一种标准,规范的token。也就是说JWT是token,但是不是所有token都是JWT。 传播格式:Json Object。 其特点是存储在客户端,服务器在接收到token并验证其身份的过程中不需要访问数据库或者第三方服务去验证它。token自带的信息就已经足够进行验证了。

JWT结构

Overview

jwt.io/

image.png

上面的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能质疑一个客户端请请求,要求客户端提供验证信息。

image.png

基于这个总框架,有多个Authentication Scheme:

www.iana.org/assignments…

en.wikipedia.org/wiki/List_o…

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

验证用户是自己所声称的那个人。

docs.spring.io/spring-secu…

Authorization

Authenticate之后确认用户是否有权限访问他想访问的资源。

docs.spring.io/spring-secu…

Servlet filter

以前

http requests -> dispatcher servlet -> controller/restcontroller

现在

http requests -> servlet filters -> dispatcher servlet -> controller/restcontroller

401 vs 403

  • 401 Unauthorized is the status code to return when the client provides no credentials or invalid credentials.
  • 403 Forbidden is 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 credential
  • expired 被动行为 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

ClassTypeproviderNote
UserDetailsServiceInterfaceSpring SecurityHelp to retrieve UserDetails from db
UserDetailsInterfaceSpring Securityneed to be implemented by dev via Entity class
UserDetailDaoInterfaceDevelopercreated by dev to get UserDetailsEntity
AuthenticationProviderInterfaceSpring SecurityResponsible for doing actual authentication
OncePerRequestFilterInterfaceSpring securityAuthentication level filter for each request
SecurityFilterChainInterfaceSpring securityOverall filter configuration
AuthenticationManagerInterfaceSpring securityAuthenticate username and password
UsernamePasswordAuthenticationTokenClassSpring securitystore user information