授权得客户端信息、授权码信息全都存在数据库

1.建表

  官方给了个sql文件:https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-oauth2/src/test/resources/schema.sql

 create table oauth_client_details (
client_id VARCHAR(128) PRIMARY KEY,
resource_ids VARCHAR(128),
client_secret VARCHAR(128),
scope VARCHAR(128),
authorized_grant_types VARCHAR(128),
web_server_redirect_uri VARCHAR(128),
authorities VARCHAR(128),
access_token_validity INTEGER,
refresh_token_validity INTEGER,
additional_information VARCHAR(4096),
autoapprove VARCHAR(128)
); create table oauth_client_token (
token_id VARCHAR(128),
token BLOB,
authentication_id VARCHAR(128) PRIMARY KEY,
user_name VARCHAR(128),
client_id VARCHAR(128)
); create table oauth_access_token (
token_id VARCHAR(128),
token BLOB,
authentication_id VARCHAR(128) PRIMARY KEY,
user_name VARCHAR(128),
client_id VARCHAR(128),
authentication BLOB,
refresh_token VARCHAR(128)
); create table oauth_refresh_token (
token_id VARCHAR(128),
token BLOB,
authentication BLOB
); create table oauth_code (
code VARCHAR(128), authentication BLOB
); create table oauth_approvals (
userId VARCHAR(128),
clientId VARCHAR(128),
scope VARCHAR(128),
status VARCHAR(10),
expiresAt TIMESTAMP,
lastModifiedAt TIMESTAMP
);
//造点测试数据
/*
INSERT INTO `oauth_client_details` VALUES ('client1', 'resource1', '$2a$10$YEpRG0cFXz5yfC/lKoCHJ.83r/K3vaXLas5zCeLc.EJsQ/gL5Jvum', 'scope1,scope2', 'authorization_code,password,client_credentials,implicit,refresh_token', 'http://www.baidu.com', null, '300', '1500', null, 'false');*/
 

2.配置数据源 yml里配置后注入到clientDetailService

server:
port: 8001
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: mysql://192.168.3.158:3306/test?&useUnicode=true&characterEncoding=utf-8

3.配置clientDetailService

    @Autowired
private DataSource dataSource; //配置客户端
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//配置客户端存储到db 代替原来得内存模式
JdbcClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
clientDetailsService.setPasswordEncoder(passwordEncoder);
clients.withClientDetails(clientDetailsService);
}

4.授权码存到数据库

@Configuration
public class TokenConfig { @Autowired
private DataSource dataSource; //配置token的存储方法
@Bean
public TokenStore tokenStore() {
//配置token存储在数据库
return new JdbcTokenStore(dataSource);
}
}
    //配置token管理服务
@Bean
public AuthorizationServerTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setClientDetailsService(clientDetailsService);
defaultTokenServices.setSupportRefreshToken(true); //配置token的存储方法
defaultTokenServices.setTokenStore(tokenStore);
defaultTokenServices.setAccessTokenValiditySeconds(300);
defaultTokenServices.setRefreshTokenValiditySeconds(1500);
return defaultTokenServices;
}

以上完整代码:

AuthorizationServerConfig
@Configuration

//开启oauth2,auth server模式
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private PasswordEncoder passwordEncoder; @Autowired
private DataSource dataSource; //配置客户端
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//配置客户端存储到db
JdbcClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
clientDetailsService.setPasswordEncoder(passwordEncoder);
clients.withClientDetails(clientDetailsService);
} @Autowired
private ClientDetailsService clientDetailsService; @Autowired
private TokenStore tokenStore; //配置token管理服务
@Bean
public AuthorizationServerTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setClientDetailsService(clientDetailsService);
defaultTokenServices.setSupportRefreshToken(true); //配置token的存储方法
defaultTokenServices.setTokenStore(tokenStore);
defaultTokenServices.setAccessTokenValiditySeconds(300);
defaultTokenServices.setRefreshTokenValiditySeconds(1500);
return defaultTokenServices;
} //密码模式才需要配置,认证管理器
@Autowired
private AuthenticationManager authenticationManager; //把上面的各个组件组合在一起
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager)//认证管理器 //配置授权码存储到db
.authorizationCodeServices(new JdbcAuthorizationCodeServices(dataSource))//授权码管理
.tokenServices(tokenServices())//token管理
.allowedTokenEndpointRequestMethods(HttpMethod.POST);
} //配置哪些接口可以被访问
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()")///oauth/token_key公开
.checkTokenAccess("permitAll()")///oauth/check_token公开
.allowFormAuthenticationForClients();//允许表单认证
}
}
TokenConfig
@Configuration
public class TokenConfig { @Autowired
private DataSource dataSource; //配置token的存储方法
@Bean
public TokenStore tokenStore() {
//配置token存储在内存中,这种是普通token,每次都需要远程校验,性能较差
return new JdbcTokenStore(dataSource);
}
}
WebSecurityConfig
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
} //密码模式才需要配置,认证管理器
@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
} @Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.anyRequest().permitAll() .and()
.formLogin() .and()
.logout();
} @Bean
public UserDetailsService userDetailsService() {
return s -> {
if ("admin".equals(s) || "user".equals(s)) {
return new MyUserDetails(s, passwordEncoder().encode(s), s);
}
return null;
};
}
}

验证:

  //授权码模式
  //浏览器访问
    http://127.0.0.1:8001/oauth/authorize?client_id=client1&response_type=code&scope=scope1&redirect_uri=http://www.baidu.com

授权码也存入了数据库:

postman申请令牌

已经存入了数据库

验证令牌

OAuth2.0-3客户端授权放到数据库的更多相关文章

  1. OAuth2.0 四种授权模式

    OAuth2.0简单笔记(四种授权模式) 金天:坚持写东西,不是一件容易的事,换句话说其实坚持本身都不是一件容易的事.如果学习有捷径,那就是不断实践,不断积累.写笔记,其实是给自己看的,是体现积累的一 ...

  2. OAuth2.0和SSO授权的区别

    OAuth2.0和SSO授权   一.OAuth2.0授权协议 一种安全的登陆协议,用户提交的账户密码不提交到本APP,而是提交到授权服务器,待服务器确认后,返回本APP一个访问令牌,本APP即可用该 ...

  3. OAuth2.0认证和授权以及单点登录

    https://www.cnblogs.com/shizhiyi/p/7754721.html OAuth2.0认证和授权机制讲解 2017-10-30 15:33 by shizhiyi, 2273 ...

  4. OAuth2.0和SSO授权

    一.OAuth2.0授权协议 一种安全的登陆协议,用户提交的账户密码不提交到本APP,而是提交到授权服务器,待服务器确认后,返回本APP一个访问令牌,本APP即可用该访问令牌访问资源服务器的资源.由于 ...

  5. OAuth2.0认证和授权原理

    什么是OAuth授权?   一.什么是OAuth协议 OAuth(开放授权)是一个开放标准. 允许第三方网站在用户授权的前提下访问在用户在服务商那里存储的各种信息. 而这种授权无需将用户提供用户名和密 ...

  6. [转载] OAuth2.0认证和授权原理

    转载自http://www.tuicool.com/articles/qqeuE3 什么是OAuth授权? 一.什么是OAuth协议 OAuth(开放授权)是一个开放标准,允许第三方网站在用户授权的前 ...

  7. 一步步搭建最简单oauth2.0认证和授权

    oauth2.0 最早接触这个概念是在做微信订阅号开发.当时还被深深的绕进去,关于oauth2.0的解释网上有好多,而且都讲解的比较详细,下面给大家价格参考资料. http://owin.org/ h ...

  8. OAuth2.0 用户验证授权标准 理解

    OAuth2.0是一套标准. 一.问题 这个标准解决了这样的一个问题. 允许用户让第三方应用访问该用户在某一网站上存储的私密的资源(如照片,视频,联系人列表),而无需将用户名和密码提供给第三方应用.  ...

  9. 微信Oauth2.0网页开放授权

    网页授权获取用户基本信息 如果用户在微信中(Web微信除外)访问公众号的第三方网页,公众号开发者可以通过此接口获取当前用户基本信息(包括昵称.性别.城市.国家).利用用户信息,可以实现体验优化.用户来 ...

随机推荐

  1. 从 (a==1&&a==2&&a==3) 成立中看javascript的隐式类型转换

    下面代码中 a 在什么情况下会打印 1? var a = ?; if(a == 1 && a == 2 && a == 3){ console.log(1); } 这个 ...

  2. 记一次WPF程序带参数启动

    问题:总共有两个程序.第一个程序使用Process带参数启动第二个程序. 网上一堆人都说什么重写Main入口啊 什么的.然后还一堆人跟着复制发文章.我也是醉了,简直是坑人.为何要舍近求远,直接重写AP ...

  3. Controller怎么接收Ajax传来的data

    var json = { "VendorId": strVendorId, "VendorName": strVendorName, "Remark& ...

  4. 上亿数据怎么玩深度分页?兼容MySQL + ES + MongoDB

    面试题 & 真实经历 面试题:在数据量很大的情况下,怎么实现深度分页? 大家在面试时,或者准备面试中可能会遇到上述的问题,大多的回答基本上是分库分表建索引,这是一种很标准的正确回答,但现实总是 ...

  5. Go Pentester - HTTP CLIENTS(1)

    Building HTTP Clients that interact with a variety of security tools and resources. Basic Preparatio ...

  6. GPO - File Server Management

    Creating disk space usage quotas: File Screening Generate Storage Report, including file edit audit. ...

  7. 计算思维(Computational Thinking)在少儿编程中的体现

    本文主要针对少儿编程从业人员及正在学习编程的学生家长 大家好,我是C大叔,国内早期的少儿编程从业人员.一直以来都是在做scratch,JavaScript,python以及信息学奥赛C++的讲师,教研 ...

  8. Spring IoC深入理解

    本文相关代码(来自官方源码spring-test模块)请参见spring-demysify org.springframework.mylearntest包下. 三种注入方式 1.构造方法注入 pub ...

  9. p46_IPv4地址

    IP地址:全世界唯一的32位/4字节标识符,标识路由器主机的接口. IP地址::={<网络号>,<主机号>} 图中有6个子网 比如222.1.3.0是网络号,3是主机号,222 ...

  10. TestNg失败重跑—解决使用 dataProvider 参数化用例次数冲突问题

    问题背景 在使用 testng 执行 UI 自动化用例时,由于 UI自动化的不稳定性,我们在测试的时候,往往会加上失败重跑机制.在不使用 @DataProvider 提供用例参数化时,是不会有什么问题 ...