简介
Spring Security 是一个强大的和高度可定制的身
份验证和访问控制框架,Spring security Oauth2协议,
oAuth参考
授权码认证
步骤:
客户端请求第三方授权,
资源拥有者同意给客户端授权,
客户端获取到授权码,请求认证服务器申请令牌
认证服务器向客户端响应令牌
客户端请求资源服务器的资源
资源服务器校验令牌的合法性,如果合法则向用户响应资源信息内容。
代码实现
1.搭建认证工程,导入数据库表
2.主要用户认证坐标
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
3.启动项目,地址栏输入
http://localhost:40400/auth/oauth/authorize?client_id=XcWebApp&response_type=code&scop=app&redirect_uri=http://www.xuecheng.com
4.授权通过,得到授权码code=Jy4Ehv
5.拿着授权码申请令牌
localhost:40400/auth/oauth/token?grant_type=authorization_code&code=Jy4Ehv&redirect_uri=http://www.xuecheng.com
6.请求资源时,请求头携带参数Authorization=Bearer+空格+令牌
7.在需要接入认证的服务加上坐标,添加公钥到resource下,编写配置类
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
8.配置类
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)//激活方法上的PreAuthorize注解
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
//公钥
private static final String PUBLIC_KEY = "publickey.txt";
//定义JwtTokenStore,使用jwt令牌
@Bean
public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
return new JwtTokenStore(jwtAccessTokenConverter);
}
//定义JJwtAccessTokenConverter,使用jwt令牌
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setVerifierKey(getPubKey());
return converter;
}
/**
* 获取非对称加密公钥 Key
* @return 公钥 Key
*/
private String getPubKey() {
Resource resource = new ClassPathResource(PUBLIC_KEY);
try {
InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
BufferedReader br = new BufferedReader(inputStreamReader);
return br.lines().collect(Collectors.joining("\n"));
} catch (IOException ioe) {
return null;
}
}
//Http安全配置,对每个到达系统的http请求链接进行校验
@Override
public void configure(HttpSecurity http) throws Exception {
//所有请求必须认证通过
http.authorizeRequests()
//对于下边的路径放行
.antMatchers("/v2/api-docs", "/swagger-resources/configuration/ui",
"/swagger-resources","/swagger-resources/configuration/security","/swagger-ui.html","/webjars/**").permitAll()
.anyRequest().authenticated();
}
}
密码模式
简介
直接通过用户名和密码即可申请令牌。
代码实现
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ULkelhrV-1596074549499)(https://i.loli.net/2020/05/04/qsxKrRHYCiPTeIB.png)]
客户端id: XcWebApp
客户端密码: XcWebApp
用户名: ******
密码: XcWebApp
校验令牌
Spring Security Oauth2提供校验令牌的端点,如下:
Get: http://localhost:40400/auth/oauth/check_token?token=令牌内容
刷新令牌
JWT令牌
简介
JSON Web Token(JWT)是一个开放的行业标准(RFC7519),它定义了一种简介的、自包含的协议格式,用于在通信双方传递json对象,传递的信息经过数字签名可以被验证和信任。JWT可以使用HMAC算法或使用RSA的公钥/私钥对来签名,防止被篡改。
特点
优点:
1、jwt基于json,非常方便解析。
2、可以在令牌中自定义丰富的内容,易扩展。
3、通过非对称加密算法及数字签名技术,JWT防止篡改,安全性高。
4、资源服务使用JWT可不依赖认证服务即可完成授权。
缺点:
1.JWT令牌较长,占存储空间比较大。
令牌结构
JWT令牌由三部分组成,每部分中间使用点(.)分隔
1.Header(头部)包括令牌的类型(即JWT)及使用的哈希算法(如HMAC SHA256或RSA)
下边是Header部分的内容
{
"alg": "HS256",
"typ": "JWT"
}
将上边的内容使用Base64Url编码,得到一个字符串就是JWT令牌的第一部分。
2.Payload(负载)
内容也是一个json对象,它是存放有效信息的地方,它可以存放jwt提供的现成字段,比如:iss(签发者),exp(过期时间戳),sub(面向的用户)等,也可自定义字段。
此部分不建议存放敏感信息,因为此部分可以解码还原原始内容。
最后将第二部分负载使用Base64Url编码,得到一个字符串就是JWT令牌的第二部分。
{
"phone": "18800000000",
"name": "smilefyou",
"admin": true
}
3.Signature(签名)
此部分用于防止jwt内容被篡改。这个部分使用base64url将前两部分进行编码,编码后使用点(.)连接组成字符串,最后使用header中声明签名算法进行签名。
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)
生成私钥和公钥
1.生成密钥证书命令(采用RSA 算法每个证书包含公钥和私钥)
keytool -genkeypair -alias xckey -keyalg RSA -keypass xuecheng -keystore xc.keystore -storepass xuechengkeystore
Keytool 是一个java提供的证书管理工具
-alias:密钥的别名
-keyalg:使用的hash算法
-keypass:密钥的访问密码
-keystore:密钥库文件名,xc.keystore保存了生成的证书
-storepass:密钥库的访问密码
(秘钥所在目录下)查询证书信息(隐藏式输入秘钥库密码)
keytool -list -keystore xc.keystore
删除别名
keytool -delete -alias xckey -keystore xc.keystore
2.导出公钥
1.[安装OpenSSL](:http://slproweb.com/products/Win32OpenSSL.html),配置环境变量
2.私钥所在目录下执行
keytool -list -rfc --keystore xc.keystore | openssl x509 -inform pem -pubkey
3.jwt令牌的生成与校验(代码略)