JMT 组成
Header(头) 作用:记录令牌类型、签名算法等 例如:{“alg":"HS256","type","JWT}
经过Base64Url编码
Payload(有效载荷)作用:携带一些用户信息 例如{"userId":"1","username":"mayikt"}
经过Base64Url编码
Payload 推荐使用声明
iss: jwt签发者
sub: jwt所面向的用户
aud: 接收jwt的一方
exp: jwt的过期时间,这个过期时间必须要大于签发时间
nbf: 定义在什么时间之前,该jwt都是不可用的.
iat: jwt的签发时间
jti: jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击.
Signature(签名)作用:防止Token被篡改、确保安全性 例如 计算出来的签名,一个字符串,
创建签名需要使用编码后的header和payload以及一个秘钥,使用header中指定签名算法进行签名
JWT优缺点
1:无需在服务器存放用户的数据,减轻服务器端压力
2:轻量级、json风格比较简单
3:跨语言
1:jwt一旦生成后期无法修改:
2:无法更新jwt有效期
3:无法销毁一个jwt
jwt和token最大的区别
- token:在用户登录后会返回一个tokenid,key:tokenid,value:username,依赖于redis查询数据信息,token存放value数据比较安全
- jwt不需要依赖于服务器端,将数据信息内容直接存放在客户端(浏览器)
accesstoken 获取
api:http://localhost:8080/oauth/token
Code:授权码
grant_type:authorization_code 所选模式
redirect_uri:回调地址
Scope: 作用域
TokenStore

@Bean
public RedisTokenStore redisTokenStore(){
RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
redisTokenStore.setPrefix("AG:OAUTH:");
return redisTokenStore;
}
ResourceServerConfigurerAdapter && WebSecurityConfigurerAdapter
public void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers("/login", "/oauth/authorize")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.authorizeRequests().antMatchers("/static/**", "/favicon.ico", "/webjars/**","/client/**")
.permitAll()
.and()
.formLogin().loginPage("/login").permitAll();
}
方法说明
方法 | 说明 |
---|
openidLogin() | 用于基于 OpenId 的验证 |
headers() | 将安全标头添加到响应 |
cors() | 配置跨域资源共享( CORS ) |
sessionManagement() | 允许配置会话管理 |
portMapper() | 允许配置一个PortMapper(HttpSecurity#(getSharedObject(class))),其他提供SecurityConfigurer的对象使用 PortMapper 从 HTTP 重定向到 HTTPS 或者从 HTTPS 重定向到 HTTP。默认情况下,Spring Security使用一个PortMapperImpl映射 HTTP 端口8080到 HTTPS 端口8443,HTTP 端口80到 HTTPS 端口443 |
jee() | 配置基于容器的预认证。 在这种情况下,认证由Servlet容器管理 |
x509() | 配置基于x509的认证 |
rememberMe | 允许配置“记住我”的验证 |
authorizeRequests() | 允许基于使用HttpServletRequest限制访问 |
requestCache() | 允许配置请求缓存 |
exceptionHandling() | 允许配置错误处理 |
securityContext() | 在HttpServletRequests之间的SecurityContextHolder上设置SecurityContext的管理。 当使用WebSecurityConfigurerAdapter时,这将自动应用 |
servletApi() | 将HttpServletRequest方法与在其上找到的值集成到SecurityContext中。 当使用WebSecurityConfigurerAdapter时,这将自动应用 |
csrf() | 添加 CSRF 支持,使用WebSecurityConfigurerAdapter时,默认启用 |
logout() | 添加退出登录支持。当使用WebSecurityConfigurerAdapter时,这将自动应用。默认情况是,访问URL”/ logout”,使HTTP Session无效来清除用户,清除已配置的任何#rememberMe()身份验证,清除SecurityContextHolder,然后重定向到”/login?success” |
anonymous() | 允许配置匿名用户的表示方法。 当与WebSecurityConfigurerAdapter结合使用时,这将自动应用。 默认情况下,匿名用户将使用org.springframework.security.authentication.AnonymousAuthenticationToken表示,并包含角色 “ROLE_ANONYMOUS” |
formLogin() | 指定支持基于表单的身份验证。如果未指定FormLoginConfigurer#loginPage(String),则将生成默认登录页面 |
oauth2Login() | 根据外部OAuth 2.0或OpenID Connect 1.0提供程序配置身份验证 |
requiresChannel() | 配置通道安全。为了使该配置有用,必须提供至少一个到所需信道的映射 |
httpBasic() | 配置 Http Basic 验证 |
addFilterAt() | 在指定的Filter类的位置添加过滤器 |
UAA
- User Account and Authentication
Oauth2