1.JWT的简介
Json web token (JWT), 是为了在⽹络应⽤环境间传递声明⽽执⾏的⼀种基于JSON的开放标准((RFC 7519).定义了⼀种简洁的,⾃包含的⽅法⽤于通信双⽅之间以JSON对象的形式安全的传递信息。因为数字签名的存在,这些信息是可信的,JWT可以使⽤HMAC算法或者是RSA的公私秘钥对进⾏签名。
2.JWT的组成
-
Header 头部 属于JWT的第一部分。头部包含两部分,token的类型和采用的加密算法,使用Base64编码,也就是说,它可以被翻译回来原来的样子。
{ "alg": "HS256", "typ": "JWT" } -
Payload负载 存放信息的地方,常⽤的有 iss(签发者),exp(过期时间),sub(⾯向的⽤户),aud(接收⽅),iat(签发时间)。也是由Base64加密的,所以可以被翻译回原来的样子,所以这里要注意不要把密码放在这部分
-
Signature签名
签名部分,需要使用密钥加上header中的签名算法一起解密才能解开,签名的作用是保证jwt没有被篡改过。如果有⼈对头部以及负载的内容解码之后进⾏修改,再进⾏编码,最后加上之前的签名组合形成新的JWT的话,那么服务器端会判断出新的头部和负载形成的签名和JWT附带上的签名是不⼀样的。如果要对新的头部和负载进⾏签名,在不知道服务器加密时⽤的密钥的话,得出来的签名也是不⼀样的。
3.使用JWT的好处
传统的OAuth2在校验token的时候还需要去授权中心去检验token的正确性,从性能上来说会多一步调用,导致性能低下。而使用JWT后,因为JWT由公钥和私钥,我们在授权中心用私钥加密,在资源端用公钥解密,如果能解出来,说明token是有效的。这样就可以减少一部分性能的损耗,而且由于可以在payload端放一些资源信息,在解密成功后也可以直接从jwt中获取一部分信息,减少重复查询的消耗。
4.公钥私钥的生成
使用keytool⼯具⽣成公钥私钥证书
1. 生成密钥证书
使用下面的命令生成密钥证书,采用RSA算法来生成公钥和私钥
keytool -genkeypair -alias kaikeba -keyalg RSA -keypass kaikeba -keystore kaikeba.jks -storepass kaikeba
keytool工具是一个java提供的证书管理工具,它的各命令的解释:
- alias:密钥的别名
- keyalg:使⽤的hash算法
- keypass:密钥的访问密码
- keystore:密钥库⽂件名
- storepass:密钥库的访问密码
2.导出公钥
使用openSsl来导出公钥信息,下载地址
- 配置环境变量
2. 解密公钥
进入xx.jks 文件所在的文件夹,然后执行下面的命令
keytool -list -rfc --keystore kaikeba.jks | openssl x509 -inform pem - pubkey
就可以得到公钥信息:
然后将公钥信息复制到一个
public.key的文件夹中。后续放到资源服务器的resources下即可。
5.实际使用
需要使用的依赖
<!-- OAuth2 鉴权 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
授权中心的配置
- 授权中心需要配置一个
AuthorizationServerConfiguration继承AuthorizationServerConfigurerAdapter
package com.study.auth.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import javax.sql.DataSource;
import java.util.concurrent.TimeUnit;
/**
* 授权信息配置
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
private static final Logger logger = LoggerFactory.getLogger(AuthorizationServerConfiguration.class);
@Autowired
@Qualifier("authenticationManagerBean")
AuthenticationManager authenticationManager;
@Autowired
private DataSource dataSource;
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
//证书路径和密钥库密码
KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("t31.jks"), "123456".toCharArray());
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
//密码别名
converter.setKeyPair(keyStoreKeyFactory.getKeyPair("t31"));
return converter;
}
@Bean
public ClientDetailsService clientDetailsService() {
return new JdbcClientDetailsService(dataSource);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//配置通过表oauth_client_details,读取客户端数据
clients.withClientDetails(clientDetailsService());
}
/**
* 配置token service和令牌存储⽅式(tokenStore
* @param endpoints
* @throws Exception
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
//tokenStore
endpoints.tokenStore(tokenStore()).tokenEnhancer(jwtAccessTokenConverter(
)).authenticationManager(authenticationManager);
//tokenService
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(endpoints.getTokenStore());
tokenServices.setSupportRefreshToken(false);
tokenServices.setClientDetailsService(endpoints.getClientDetailsService()
);
tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
// 过期时间30天
tokenServices.setAccessTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(30));
endpoints.tokenServices(tokenServices);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
// 允许表单认证
security.allowFormAuthenticationForClients()
//放⾏oauth/token_key(获得公钥)
.tokenKeyAccess("permitAll()")
//放⾏ oauth/check_token(验证令牌)
// .checkTokenAccess("isAuthenticated()");
.checkTokenAccess("permitAll()");
}
}
- 授权中心需要配置一个
SecurityConfiguration继承WebSecurityConfigurerAdapter
package com.study.auth.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* security 配置
*/
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
/**
* 注⼊⾃定义UserDetailService,读取rbac数据
*/
@Autowired
private UserDetailsService userDetailsService;
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers().anyRequest()
//开放/oauth/开头的所有请求
.and().authorizeRequests().antMatchers("/oauth/**").permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//注⼊⾃定义的UserDetailsService,采⽤BCrypt加密
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
}
资源中心的配置
注:资源中心配置后,在启动的时候会拿公钥去访问一次授权中心,判断公钥是否是正确的。访问的地址为授权中心服务的地址:http://localhost:9098/oauth/token_key 其中 oauth/token_key 是授权框架的接口。
- application.yml需要配置如下配置
security:
oauth2:
client:
access-token-uri: http://localhost:9098/oauth/token #令牌端
user-authorization-uri: http://localhost:9098/oauth/authorize #授权端点
client-id: admin-service # 客户端的id 授权会进行客户端的校验,如果客户端不通过,则会提示启动失败
client-secret: 123456 # 客户端的密钥
grant-type: password
scope: read,write
resource:
jwt:
key-uri: http://localhost:9098/oauth/token_key #如果使用JWT,可以获取公钥用于 token 的验签
- JWTConfig的配置 用来做token的解密配置
package com.study.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.util.FileCopyUtils;
import java.io.IOException;
@Configuration
public class JWTConfig {
public static final String public_cert = "public.key";
@Autowired
private JwtAccessTokenConverter jwtAccessTokenConverter;
@Bean
@Qualifier("tokenStore")
public TokenStore tokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter);
}
@Bean
protected JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
Resource resource = new ClassPathResource(public_cert);
String publicKey;
try {
publicKey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
}catch (IOException e) {
throw new RuntimeException(e);
}
// 设置校验公钥
converter.setVerifierKey(publicKey);
// 设置证书签名密码,否则报错
converter.setSigningKey("123456");
return converter;
}
}
ResourceServerConfiguration配置 用来做拦截的资源配置package com.study.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.TokenStore; @Configuration @EnableResourceServer @EnableGlobalMethodSecurity(prePostEnabled = true) public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { @Autowired private TokenStore tokenStore; @Override public void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/user/**").permitAll() //⽤于测试 .antMatchers("/book/**").hasRole("ADMIN") .antMatchers("/**").authenticated(); } @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.tokenStore(tokenStore); }
}