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

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. 【笔记】Java语法

    Java语法 兜兜转转,又绕回到Java了. 最近在学习Java,其实以前也学过,但是技术发展太快了,Java都出到14了..是时候该更新一下知识体系了. 然后看的是网上好评如潮的<Java核心 ...

  2. Kubernetes部署通用手册 (支持版本1.19,1.18,1.17,1.16)

    Kubernetes平台环境规划 操作环境 rbac 划分(HA高可用双master部署实例) 本文穿插了ha 高可用部署的实例,当前章节设计的是ha部署双master 部署 内网ip 角色 安装软件 ...

  3. C#-性能-二维数组和数组的数组的性能比较

    两者是3:2的消耗比例 const int NUM = 10000; int[,] vec = new int[NUM, NUM]; Stopwatch sw = Stopwatch.StartNew ...

  4. js 中 attachEvent 简示例

    attachEvent绑定事件,函数的默认this指向为window,要解决问题可以通过call改变方法的指向! var div = document.getElementsByTagName('di ...

  5. git和github连接权限(这是一个简便方法,不是很安全,建议大家还是用ssh解决)

    在使用,git从github上clone下来代码后. 我们再工作区进行编辑,然后提交. 最后我们想要将我们的改变推送到github上. 但是往往这个时候,我们可能会面临这样的问题. 我们没有权限将代码 ...

  6. com.aliyun.openservices.shade.com.alibaba.fastjson.JSONException: exepct '[', but {, pos 1, line 1, column 2

    报错原因:你放的是一个非List的对象 却想取一个List对象出来 package test; import java.text.SimpleDateFormat; import java.util. ...

  7. scss : div水平垂直居中

    scss 是一个很好用的css预处理语言,有很多很好的特性. 比如 mixin. 我们可以像使用函数那样使用mixin. 比如写一个div水平垂直居中. 上代码. @mixin absolute_ce ...

  8. DP学习记录Ⅰ

    DP学习记录Ⅱ 前言 状态定义,转移方程,边界处理,这三部分想好了,就问题不大了.重点在状态定义,转移方程是基于状态定义的,边界处理是方便转移方程的开始的.因此最好先在纸上写出自己状态的意义,越详细越 ...

  9. 最小割树(Gomory-Hu Tree)

    当我们遇到这样的问题: 给定一个 \(n\) 个点 \(m\) 条边的无向连通图,多次询问两点之间的最小割 我们通常要用到最小割树. 博客 建树 分治.记录当前点集,然后随便找俩点当 \(s\) 和 ...

  10. Flutter.. 两个点语法含义

    在Flutter编程中,会经常用到".."的语法糖,如下 state.clone() ..splashImg = action.img ..famousSentence = act ...