最近在搞关于oauth2的系统,在网上的资料比较杂乱,也痛苦了不少了时间,最后终于开发好了符合自己实际应用的系统

在这里顺便把整理后的例子发上来,希望能够帮到别人,同时也给自己留个记录

首先,先添加依赖

        <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-oauth2</artifactId></dependency>

例子使用redis来存储token信息,加入redis依赖

       <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>

使用mysql来保存客户端信息,加入mysql依赖

        <dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.13</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency>

application.properties

server.port=8080#datasource config
spring.datasource.url=jdbc:mysql://localhost:3306/oauth_test?useUnicode=true&characterEncoding=utf8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=#redis config
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456

step1.配置spring security

package cn.tanntly.authentication.server.config;import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.csrf().disable();http.requestMatchers().antMatchers("/oauth/**", "/login/**", "/logout/**").and().authorizeRequests().antMatchers("/oauth/**").authenticated().and().formLogin().permitAll();}//配置内存模式的用户@Bean@Overrideprotected UserDetailsService userDetailsService() {//用户暂时使用内存模式,可以自行实现UserDetailsService后,进行替换InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();inMemoryUserDetailsManager.createUser(User.withUsername("user_1")
//这一堆是123456使用    BCryptPasswordEncoder 编码之后的样子
.password("$2a$10$u2.TGFJuzx13g1lDXoy.KeUQU8s6/HoqTaHCqWMV8/eeyLUEyYs9W").authorities("USER").build());return inMemoryUserDetailsManager;}@Override@Beanpublic AuthenticationManager authenticationManagerBean() throws Exception {//支持password模式return super.authenticationManagerBean();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//新版本不配置会抛空指针auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}}

step2.oauth 配置

package cn.tanntly.authentication.server.config;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
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.token.store.redis.RedisTokenStore;import javax.sql.DataSource;@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {@Autowiredprivate AuthenticationManager authenticationManager;@Autowiredprivate DataSource dataSource;@Autowiredprivate RedisConnectionFactory redisConnectionFactory;@Overridepublic void configure(AuthorizationServerSecurityConfigurer oauthServer) {oauthServer.realm("oauth2-resources").tokenKeyAccess("permitAll()").checkTokenAccess("permitAll()").allowFormAuthenticationForClients();}@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) {endpoints.authenticationManager(authenticationManager).allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST).tokenStore(new RedisTokenStore(redisConnectionFactory));}@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {// 默认使用内存,这里配置使用数据库clients.jdbc(dataSource);}
}

同时附带client的数据库结构:

CREATE TABLE `oauth_client_details` (`client_id` varchar(128) NOT NULL,`resource_ids` varchar(128) DEFAULT NULL,`client_secret` varchar(128) DEFAULT NULL,`scope` varchar(128) DEFAULT NULL,`authorized_grant_types` varchar(128) DEFAULT NULL,`web_server_redirect_uri` varchar(128) DEFAULT NULL,`authorities` varchar(128) DEFAULT NULL,`access_token_validity` int(11) DEFAULT NULL,`refresh_token_validity` int(11) DEFAULT NULL,`additional_information` varchar(4096) DEFAULT NULL,`autoapprove` varchar(128) DEFAULT NULL,PRIMARY KEY (`client_id`) USING BTREE
)

step3.测试

1.客户端模式

http://localhost:8080/oauth/token?grant_type=client_credentials&scope=all&client_id=demoApp&client_secret=123456

{"access_token": "ca8b91e3-c9a0-490f-9499-b984bcc6aa4a","token_type": "bearer","expires_in": 1199,"scope": "all"
}

2.密码模式

http://localhost:8080/oauth/token?username=user_1&password=123456&grant_type=password&client_id=demoApp&client_secret=123456

{"access_token": "79216763-d5d6-4562-a3aa-f7c93e4afb88","token_type": "bearer","refresh_token": "f01683fa-c6dc-40c6-8baa-09b404f3b7be","expires_in": 1199,"scope": "all"
}

3.授权码模式

3.1进入登录页面

http://localhost:8080/oauth/authorize?response_type=code&client_id=demoApp&redirect_uri=http://localhost:8081

3.2登录成功后,跳转到回调地址时,会带上授权码code

https://www.baidu.com/?code=3b27p3

3.3通过code获取token

http://localhost:8080/oauth/token?grant_type=authorization_code&code=3b27p3&client_id=demoApp&client_secret=123456&redirect_uri=http://localhost:8081

{
  "access_token": "79216763-d5d6-4562-a3aa-f7c93e4afb88",
  "token_type": "bearer",
  "refresh_token": "f01683fa-c6dc-40c6-8baa-09b404f3b7be",
  "expires_in": 690,
  "scope": "all"
}

spring boot security oauth2 认证服务器搭建相关推荐

  1. Spring Boot Security OAuth2 入门

    1. 概述 本文,我们来入门 Spring Security OAuth2.0 的使用.通过本文,希望你对 OAuth2.0 有一次身临其境的感受. 另外,这是一篇入门的文章,所以实际场景下,需要做一 ...

  2. spring boot项目initializr本地服务器搭建

    有时候我们创建spring boot项目时会连接不上 https://start.spring.io 的服务器,后来我查找谷歌百度发现可以本地搭建 spring initializr 本地服务器,官网 ...

  3. gateway oauth2 对称加密_深入理解Spring Cloud Security OAuth2及JWT

    因项目需要,需要和三方的oauth2服务器进行集成.网上关于spring cloud security oauth2的相关资料,一般都是讲如何配置,而能把这块原理讲透彻的比较少,这边自己做一下总结和整 ...

  4. Oauth2.0 认证服务器搭建

    核心 POM <dependency><groupId>org.springframework.cloud</groupId><artifactId>s ...

  5. 玩转Spring Cloud Security OAuth2身份认证扩展——电话号码+验证码认证

    在程序的认证过程中,除了常规的用户名和密码方式(可以参考深入理解Spring Cloud Security OAuth2身份认证),也经常会出现电话号码+密码的方式:电话号码+验证码的方式:或者第三方 ...

  6. 【java_wxid项目】【第七章】【Spring Cloud Security Oauth2集成】

    主项目链接:https://gitee.com/java_wxid/java_wxid 项目架构及博文总结: 点击:[使用Spring Boot快速构建应用] 点击:[使用Spring Cloud O ...

  7. 《深入理解 Spring Cloud 与微服务构建》第十六章 Spring Boot Security 详解

    <深入理解 Spring Cloud 与微服务构建>第十六章 Spring Boot Security 详解 文章目录 <深入理解 Spring Cloud 与微服务构建>第十 ...

  8. spring boot security学习

    spring boot security(一) 配置认证和授权 通过继承WebSecurityConfigurerAdapter,可以重写其认证和授权的逻辑. @Configuration @Enab ...

  9. spring boot security 将您重定向的次数过多

    在学习spring boot security的过程中遇到了这样的一个问题. 查看代码,为了跳转到我们自己定义的登录页面,写了loginPage("/login.html"),按照 ...

最新文章

  1. 区块链还可以这么玩?“点亮莫高窟”背后的腾讯云区块链
  2. 使用genext2fs制作ramdisk
  3. JAM - how count is got - SAP Fiori和JAM的集成
  4. 在Android命令行启动程序的方法
  5. linux修改密码最短生存时间,Linux基础命令---修改用户密码
  6. 织梦使用if判断某个字段是否为空
  7. rman坏块的检测与恢复
  8. Bootstrap模态出现在背景下
  9. 是清单 Dog List的子类 Animal ? 为什么Java泛型不是隐式多态的?
  10. FreeSwitch+Sipml5实现SIP协议WebRTC视频聊天(没呼叫成功)
  11. ibm watson_使用IBM Watson Assistant构建AI私人教练-第1部分
  12. c语言编写面条排序算法,腾讯PCG事业部腾讯视频面经
  13. 虎牙直播源解析【可选清晰度】
  14. 基于django的视频点播网站开发-step15-项目部署 1
  15. Flash 芯片类型介绍
  16. 转载一篇JAVA面试题
  17. 华为IBMC管理口提示:当前无可操作的RAID控制器 以及 在远程控制台做raid的方法
  18. 斑马Zebra 170Xi4 打印机驱动
  19. 人防工程防排烟及通风空气调节规范
  20. 华图教育_南京_前端实习面试

热门文章

  1. 游戏动画设计师的发展前景如何?
  2. js 日期对象深拷贝
  3. 新手站长说说之伪静态与纯静态 哪个对SEO更好
  4. zzuli OJ 1114: 逆序
  5. 创业内外部环境综合分析:创业究竟需要什么?
  6. 估计google封闭Google Sync效劳
  7. 伪装为 吃鸡账号获取器 的QQ木马分析
  8. GNU Make 使用手册(于凤昌中译版)
  9. Gerrit 升级文档,gerrit 安装插件。
  10. WPL、最优二叉树(哈夫曼树)