@File
2019-10-19T07:30:02.000000Z
字数 15404
阅读 177
java
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</artifactId><version>2.3.6.RELEASE</version></dependency><dependency><groupId>org.springframework.security.oauth.boot</groupId><artifactId>spring-security-oauth2-autoconfigure</artifactId><version>2.1.9.RELEASE</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.17</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>
spring:datasource:url: jdbc:mysql://mysql:3306/oauth2?useSSL=false&serverTimezone=UTCusername: rootpassword:driver-class-name: com.mysql.cj.jdbc.Driverdruid:initial-size: 20max-active: 50min-idle: 15validation-query: 'select 1'test-on-borrow: falsetest-on-return: falsetest-while-idle: true# psCache, 缓存preparedStatement, 对支持游标的数据库性能有巨大的提升,oracle开启,mysql建议关闭pool-prepared-statements: false# psCache开启的时候有效max-open-prepared-statements: 100# 一个连接在被驱逐出连接池的时候,在连接池中最小的空闲时间,单位为毫秒min-evictable-idle-time-millis: 30000# 距离上次释放空闲连接的时间间隔time-between-eviction-runs-millis: 30000
create table oauth_client_details (client_id VARCHAR(256) PRIMARY KEY,resource_ids VARCHAR(256),client_secret VARCHAR(256),scope VARCHAR(256),authorized_grant_types VARCHAR(256),web_server_redirect_uri VARCHAR(256),authorities VARCHAR(256),access_token_validity INTEGER,refresh_token_validity INTEGER,additional_information VARCHAR(4096),autoapprove VARCHAR(256));create table oauth_client_token (token_id VARCHAR(256),token blob,authentication_id VARCHAR(256) PRIMARY KEY,user_name VARCHAR(256),client_id VARCHAR(256));create table oauth_access_token (token_id VARCHAR(256),token blob,authentication_id VARCHAR(256) PRIMARY KEY,user_name VARCHAR(256),client_id VARCHAR(256),authentication blob,refresh_token VARCHAR(256));create table oauth_refresh_token (token_id VARCHAR(256),token blob,authentication blob);create table oauth_code (code VARCHAR(256), authentication blob);create table oauth_approvals (userId VARCHAR(256),clientId VARCHAR(256),scope VARCHAR(256),status VARCHAR(10),expiresAt TIMESTAMP,lastModifiedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP);
说明:数据库表是依据spring-security的官网,地址为:https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-oauth2/src/test/resources/schema.sql,但是在创建的时候将所有的字段类型LONGVARBINARY改为BLOB类型。
数据库的说明参考:http://andaily.com/spring-oauth-server/db_table_description.html
@Componentpublic class UserSecurityService implements UserDetailsService {private static Logger logger = LoggerFactory.getLogger(UserSecurityService.class);@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {logger.info("用户名:" + username);return new User(username, "$2a$10$TWf8wOKvyAeuJiL/gj8AfeWOrW9vr6g4Q6kJ.PZ1bt53ISRXTTcga",Arrays.asList(new SimpleGrantedAuthority("ROLE_admin")));}}
@Configurationpublic class WebAuthorizationConfig extends WebSecurityConfigurerAdapter {// 密码的加解密@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin().loginPage("/login.html").loginProcessingUrl("/authentication/form").and().authorizeRequests().antMatchers("/login.html").permitAll().anyRequest().authenticated().and().csrf().disable();}}
@Configuration@EnableAuthorizationServerpublic class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {@Autowiredprivate LoginAuthencation loginAuthencation;@Autowiredprivate PasswordEncoder passwordEncoder;@Resourceprivate DataSource dataSource;// 根据用户的client_id查询用户的授权信息@Beanpublic ClientDetailsService clientDetails() {return new JdbcClientDetailsService(dataSource);}//用于将token信息存放在数据库中@Beanpublic TokenStore tokenStore() {return new JdbcTokenStore(dataSource);}// authentication_code放入到数据中@Beanpublic AuthorizationCodeServices authorizationCodeServices() {return new JdbcAuthorizationCodeServices(dataSource);}@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {// 采用数据库的方式查询用户的授权信息clients.withClientDetails(clientDetails());/** 供学习使用clients.inMemory()// client_id.withClient("client")// client_secret.secret("secret")// 该client允许的授权类型,不同的类型,则获得token的方式不一样。.authorizedGrantTypes("authorization_code").scopes("all")//回调uri,在authorization_code与implicit授权方式时,用以接收服务器的返回信息.redirectUris("http://localhost:9090/login");*/}@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {// 存数据库endpoints.tokenStore(tokenStore()).authorizationCodeServices(authorizationCodeServices()).allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);// 配置tokenServices参数DefaultTokenServices tokenServices = new DefaultTokenServices();tokenServices.setTokenStore(endpoints.getTokenStore());tokenServices.setSupportRefreshToken(false);tokenServices.setClientDetailsService(endpoints.getClientDetailsService());tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());// token的过期时间为1天tokenServices.setAccessTokenValiditySeconds((int)TimeUnit.DAYS.toSeconds(1));endpoints.tokenServices(tokenServices);}@Overridepublic void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {/*** 作用是使用client_id和client_secret来做登录认证,如果是在浏览器的情况下,会让用户* 输入用户名和密码*/oauthServer.allowFormAuthenticationForClients();oauthServer.checkTokenAccess("isAuthenticated()");oauthServer.passwordEncoder(passwordEncoder);}}
@Controller@SessionAttributes("authorizationRequest") // 必须配置public class AuthController {/*** org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint默认的授权页面*/@RequestMapping("/oauth/confirm_access")public String getAccessConfirmation(Map<String, Object> model, HttpServletRequest request) throws Exception {AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get("authorizationRequest");System.out.println(authorizationRequest.getScope());return "/oauth.html";}}
在浏览器地址栏的重定向地址上可以看到 code值。
根据上一步获取到的code值获取acccess_token, 请求的地址为:
其中code的值为上一步请求获取到的code的数据,返回内容如下:
Oauth2在获取用户额外信息的时候,内部实现上并没有去做,所以需要我们自己去实现,实现的方式就是去重写其代码,思路是从数据库查询到的信息封装到 ClientDetails中,但是内部却没有开放出来,所以需要去找到是在何处查询数据库,根据源代码的追踪,发现查询数据库的操作是在ApprovalStoreUserApprovalHandler这个类中,所以我们需要手动的去修改其源代码,修改的内容如下:
资源服务器就是用户想要真正获取资源的服务器,我们必须要通过2.9节中获取到的access_token来获取。
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.9.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</artifactId><version>2.3.6.RELEASE</version></dependency><dependency><groupId>org.springframework.security.oauth.boot</groupId><artifactId>spring-security-oauth2-autoconfigure</artifactId><version>2.1.9.RELEASE</version></dependency></dependencies>
security:oauth2:resource:# access_token的验证地址token-info-uri: http://localhost:8080/oauth/check_tokenclient:client-id: resources_clientclient-secret: 1
我们需要在授权服务器上创建client_id和client_secret,当资源服务器拿到第三方的access_token后需要到授权服务器上验证access_token的来源是否合法。
@Configuration@EnableResourceServerpublic class ResourceServerConfig extends ResourceServerConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests() //.antMatchers("/user").access("#oauth2.hasAnyScope('all','read')");}}
通过调用如下接口去获取资源服务器的资源:
http://localhost:8081/user?access_token=92de29ea-df7d-4d35-b585-c740322f9028
这种模式最大的问题是,没有分布式架构,无法支持横向扩展。如果使用一个服务器,该模式完全没有问题。但是,如果它是服务器群集或面向服务的跨域体系结构的话,则需要一个统一的session数据库库来保存会话数据实现共享,这样负载均衡下的每个服务器才可以正确的验证用户身份。
但是在实际中常见的单点登陆的需求:站点A和站点B提供统一公司的相关服务。现在要求用户只需要登录其中一个网站,然后它就会自动登录到另一个网站。怎么做?
一种解决方案是听过持久化session数据,写入数据库或文件持久层等。收到请求后,验证服务从持久层请求数据。该解决方案的优点在于架构清晰,而缺点是架构修改比较费劲,整个服务的验证逻辑层都需要重写,工作量相对较大。而且由于依赖于持久层的数据库或者问题系统,会有单点风险,如果持久层失败,整个认证体系都会挂掉。
针对如上的问题,另外一种解决方案就是JWT(Json Web Token),其原则是在服务器验证之后,将生产的一个Json对象返回给用户,格式如下:
{"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzEyNDE2NTksInVzZXJfbmFtZSI6ImFhIiwiYXV0aG9yaXRpZXMiOlsiUk9MRV9hZG1pbiJdLCJqdGkiOiJlZTczOTI4OC0zNDMwLTQxMjUtODBhOC1lMDU0Njg5OWQ2ODIiLCJjbGllbnRfaWQiOiJteV9jbGllbnQiLCJzY29wZSI6WyJhbGwiXX0.Ji4xYQJuJRrZeCTTMOb1e2GiOESAyiI9NzbWffKzcJ0","token_type": "bearer","expires_in": 43198,"scope": "all","jti": "ee739288-3430-4125-80a8-e0546899d682"}
如上代码返回的access_token为一个字符串,之间用 . 分隔为为三段,其中第一段为 header(头),第二段为 payload (负载),第三段为signature(签名),如下图所示:
我们可以在 <https://jwt.io/> 在线解析这个JWT token, 如下图所示
header
| 字段名 | 描述 |
|---|---|
| alg | 算法 |
| typ | 令牌类型 |
payload
| 字段名 | 描述 |
|---|---|
| exp | 超时时间 |
| jti | JWT ID |
signature
签名,为了验证发送过来的access_token是否有效,通过如下算法得到:
客户端接收服务器返回的JWT,将其存储在Cookie或localStorage中。此后,客户端将在与服务器交互中都会带JWT。如果将它存储在Cookie中,就可以自动发送,因此一般是将它放入HTTP请求的Header Authorization字段中。当跨域时,也可以将JWT被放置于POST请求的数据主体中。
但是JWT也面临着诸多的问题,如下所示:
依赖:
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.9.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</artifactId><version>2.3.6.RELEASE</version></dependency><dependency><groupId>org.springframework.security.oauth.boot</groupId><artifactId>spring-security-oauth2-autoconfigure</artifactId><version>2.1.9.RELEASE</version></dependency></dependencies>
jwt授权服务器
@Configuration@EnableAuthorizationServerpublic class OauthAuthenticationServer extends AuthorizationServerConfigurerAdapter {@Autowiredprivate PasswordEncoder passwordEncoder;@Beanpublic TokenStore tokenStore() {return new JwtTokenStore(jwtAccessTokenConverter());}@Beanpublic JwtAccessTokenConverter jwtAccessTokenConverter() {JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();jwtAccessTokenConverter.setSigningKey("123"); //设置签名return jwtAccessTokenConverter;}// 基于内存的授权码@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory() //.withClient("my_client") //.secret("$2a$10$TWf8wOKvyAeuJiL/gj8AfeWOrW9vr6g4Q6kJ.PZ1bt53ISRXTTcga") //.scopes("all") //.authorizedGrantTypes("authorization_code").redirectUris("http://localhost:9090/login");}@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints.accessTokenConverter(jwtAccessTokenConverter()).allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);}@Overridepublic void configure(AuthorizationServerSecurityConfigurer security) throws Exception {security.allowFormAuthenticationForClients().passwordEncoder(passwordEncoder);}}
@Configuration@EnableResourceServerpublic class ReourceServerConfig extends ResourceServerConfigurerAdapter {@Beanpublic TokenStore jwtTokenStore() {return new JwtTokenStore(jwtAccessTokenConverter());}@Beanpublic DefaultTokenServices defaultTokenServices() {DefaultTokenServices defaultTokenServices = new DefaultTokenServices();defaultTokenServices.setTokenStore(jwtTokenStore());return defaultTokenServices;}@Beanpublic JwtAccessTokenConverter jwtAccessTokenConverter() {JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();jwtAccessTokenConverter.setSigningKey("123");return jwtAccessTokenConverter;}@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests() //.anyRequest() //.authenticated() //.and() //.csrf().disable();}@Overridepublic void configure(ResourceServerSecurityConfigurer resources) throws Exception {resources.tokenServices(defaultTokenServices());}}
单点登录(Singal Sign On)是很多企业经常使用的一种登录方式,那么何为单点登录呢?为了解决什么样的问题呢?举个例子,在淘宝公司内部,有天猫、淘宝、阿里云、聚划算等众多的产品线,这些产品线是不同的服务器来支撑运行,但是作为用户的我们却可以使用同一套账户名和密码进行登录他几乎所有的产品,登录服务器只有一个,根据登录服务器返回的特定的信息,可以去访问它所有的产品线。着就是所谓的单点登录。
在具体的实现的时候,我们使用JWT的方式来实现单点登录。他的处理流程如下:
依赖
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</artifactId><version>2.3.6.RELEASE</version></dependency><dependency><groupId>org.springframework.security.oauth.boot</groupId><artifactId>spring-security-oauth2-autoconfigure</artifactId><version>2.1.9.RELEASE</version></dependency></dependencies>
授权服务
@Configuration@EnableAuthorizationServerpublic class SsoAuthorizationConfigServer extends AuthorizationServerConfigurerAdapter {@Beanpublic JwtAccessTokenConverter jwtAccessTokenConverter() {JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();jwtAccessTokenConverter.setSigningKey("abcxyz");return jwtAccessTokenConverter;}@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory() //.withClient("client-a") //.secret("$2a$10$TWf8wOKvyAeuJiL/gj8AfeWOrW9vr6g4Q6kJ.PZ1bt53ISRXTTcga") //.authorizedGrantTypes("authorization_code", "refresh_token").scopes("all").redirectUris("http://localhost:8081/clientA/login").autoApprove(true).and().withClient("client-b") //.secret("$2a$10$TWf8wOKvyAeuJiL/gj8AfeWOrW9vr6g4Q6kJ.PZ1bt53ISRXTTcga") //.authorizedGrantTypes("authorization_code").scopes("all").redirectUris("http://localhost:8082/clientB/login").autoApprove(true);}@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints//.tokenStore(jwtTokenStore()).accessTokenConverter(jwtAccessTokenConverter());}}
依赖
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</artifactId><version>2.3.6.RELEASE</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.security.oauth.boot</groupId><artifactId>spring-security-oauth2-autoconfigure</artifactId><version>2.1.9.RELEASE</version></dependency></dependencies>
配置
server:port: 8081servlet:context-path: /clientAsecurity:oauth2:client:client-id: client-aclient-secret: 1access-token-uri: http://localhost:7070/auth/oauth/tokenuser-authorization-uri: http://localhost:7070/auth/oauth/authorizeresource:jwt:key-value: abcxyz
启动类配置
@SpringBootApplication@EnableOAuth2Ssopublic class SsoClientApplicationA {public static void main( String[] args ) {SpringApplication.run(SsoClientApplicationA.class, args);}}