SpringBoot整合Oauth2实现认证授权

应用场景

OAuth2.0 协议的使用场景主要为:第三方登录开放接口的调用

第三方登录就是使用微信等第三方的方式来登录一个应用或者网站,比如用微信账号登录gitee。

开发接口的调用,则比如说微信、美团等平台向外提供一些自己的接口,这些接口会由很多商家调用来进行开发,对于这些接口的调用则同样可以使用 OAuth2.0 协议。

应用搭建

授权服务器

  1. 引入依赖
        <dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</artifactId><version>2.5.2.RELEASE</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>
  1. 增加授权配置
/*** 模拟第三方授权配置*/
@EnableAuthorizationServer
@Configuration
public class AuthConfig extends AuthorizationServerConfigurerAdapter {@ResourceClientDetailsService clientDetailsService;/*** 资源服务器校验Token*/@Overridepublic void configure(AuthorizationServerSecurityConfigurer security) {security.checkTokenAccess("permitAll()").allowFormAuthenticationForClients();}/*** 第三方客户端请求配置,和资源服务访问的配置,不设置默认都可以访问,提供默认回调地址*/@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory().withClient("cc_client").secret(new BCryptPasswordEncoder().encode("cc_secret")).resourceIds("cc_resource").authorizedGrantTypes("authorization_code","refresh_token").scopes("all").redirectUris("http://localhost:9093/notify.html");}/*** 配置访问端点*/@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) {endpoints.authorizationCodeServices(authorizationCodeServices()).tokenServices(tokenServices());}/*** 内存管理*/@BeanAuthorizationCodeServices authorizationCodeServices() {return new InMemoryAuthorizationCodeServices();}/*** Token管理规则*/@BeanAuthorizationServerTokenServices tokenServices() {DefaultTokenServices services = new DefaultTokenServices();services.setClientDetailsService(clientDetailsService);services.setSupportRefreshToken(true);services.setTokenStore(tokenStore());services.setAccessTokenValiditySeconds(3600);services.setRefreshTokenValiditySeconds(3600*7);return services;}@BeanTokenStore tokenStore() {return new InMemoryTokenStore();}
}
  1. 增加授权服务器的登录校验配置
/*** 模拟本地用户配置*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {/*** 密码加密方式*/@Beanpublic PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}/*** 内存中虚拟用户和角色*/@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("user");}/*** 表单登录*/@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().formLogin();}
}
  1. 设置端口号9091

资源服务器

  1. 引入pom依赖
        <dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</artifactId><version>2.5.2.RELEASE</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>
  1. 增加资源配置类
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {/*** Token令牌校验*/@BeanRemoteTokenServices tokenServices() {RemoteTokenServices services = new RemoteTokenServices();services.setCheckTokenEndpointUrl("http://localhost:9091/oauth/check_token");services.setClientId("cc_client");services.setClientSecret("cc_secret");return services;}/*** 服务资源ID配置*/@Overridepublic void configure(ResourceServerSecurityConfigurer resources) throws Exception {resources.resourceId("cc_resource").tokenServices(tokenServices());}/*** 模拟用户权限规则*/@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/user/**").hasRole("user").anyRequest().authenticated();}
}
  1. 建立资源API
@RestController
@RequestMapping("/user")
public class ResourceController {@GetMapping("/get_resource")public String hello() {return "我是被保护的资源接口";}
}
  1. 设置端口号9092

访问测试

  1. 认证接口

请求认证接口的链接,询问用户是否同意授权

http://localhost:9091/oauth/authorize?client_id=cc_client&response_type=code
  1. 进入登录页面,输入用户名密码,点击登录以后,进入授权认证页面。浏览器提示我们,你是否允许cc_client访问你的受保护的资源?
  2. 选择允许之后,点击授权,会跳转到我们提前配置好的重定向地址 http://localhost:9093/user/hello,同时带上授权码 code 的值
  3. 根据授权码 code 获取 token。拿到了授权码,我们再根据 grant_type、redirect_url 以及 scope 来使用如下链接,申请令牌 access_token(该链接为 post 请求方式)
http://localhost:9091/oauth/token?code=ox2aO6&grant_type=authorization_code&redirect_uri=http://localhost:8093/notify.html&scope=all

{"access_token": "47Map5HXp7gio0zWYyLDrygEmQ8","token_type": "bearer","refresh_token": "Jty8PwzwVMO4MafYTPpAQfrKGGY","expires_in": 2212,"scope": "all"
}
  1. 校验 token 的正确性

采用 链接 http://localhost:9091/oauth/check_token?token=47Map5HXp7gio0zWYyLDrygEmQ8,进行 token 正确性的检验。

{"aud": ["cc_resource"],"user_name": "admin","scope": ["all"],"active": true,"exp": 1672120906,"authorities": ["ROLE_user"],"client_id": "cc_client"
}
  1. 访问资源服务器。http://localhost:9092/user/get_resource

总结

  1. 当我们需要访问第三方服务(gitee),我们需要微信的认证和授权(认证授权服务器)获取到我们在微信端的用户基础信息(资源服务器),第三方服务会帮我们做跳转。
  2. 用户进行登录认证,第三方服务可以获取到授权码,根据授权码获取到access_token。
  3. 第三方应用根据access_token可以获取到资源服务器上面的资源。

项目地址

  • https://gitee.com/charles_ruan/demo-oauth2

【Oauth2】SpringBoot整合Oauth2实现认证授权相关推荐

  1. 实战干货!Spring Cloud Gateway 整合 OAuth2.0 实现分布式统一认证授权!

    今天这篇文章介绍一下Spring Cloud Gateway整合OAuth2.0实现认证授权,涉及到的知识点有点多,有不清楚的可以看下陈某的往期文章. 文章目录如下: 微服务认证方案 微服务认证方案目 ...

  2. SpringBoot 整合oauth2实现授权第三方应用(实战版)

    程序员的成长之路 互联网/程序员/技术/资料共享 关注 阅读本文大概需要 11 分钟. 来自:blog.csdn.net/u014365523/article/details/112317015 什么 ...

  3. springboot 整合 oauth2报错 Redirect URI mismatch

    最近在学习oauth2,搭建demo工程,password认证模式正常,但authorization_code模式,获取到code后,通过code换取token时,一直报异常 {"error ...

  4. Springboot集成JWT做认证授权

    目录 1.1.JWT简介 1.2.JWT能做什么? 1.3.JWT认证流程是什么? 1.4.JWT的结构是什么? 1.5.使用JWT 1.生成token 2.解析token 1.6.封装工具类 1.7 ...

  5. OAuth2.0 - 介绍与使用 及 授权码模式讲解

    一.OAuth2.0 前面我们已经学习了SpringSecurity在SpringMVC环境下和WebFlux环境下用户认证授权以及整合JWT作为Token无状态认证授权,但是在前面的演示中都会发现全 ...

  6. Springboot整合Shiro之授权

      本文我们来介绍SpringBoot整合Shiro来实现授权的操作 一.注解的使用方式 1.配置类修改   在权限校验的时候,我们一般在控制中通过注解来实现权限的校验,但我们需要放开注解的使用,在配 ...

  7. jwt token注销_【原创精选】OAuth 2.0+JWT+spring security完成认证授权-生产级-附带源码...

    前言导读 分析一下为什么要用OAuth2和JWT来做 1. **单点登录(SSO)**方案单击登录方案是最常见的解决方案,但单点登录需要每个与用户交互的服务都必须与认证服务进行通信,这不但会造成重复, ...

  8. SpringBoot整合篇-雷丰阳-专题视频课程

    SpringBoot整合篇-317人已学习 课程介绍         本视频<SpringBoot>属于下部,着重介绍SpringBoot的与各大场景的整合使用,内容包括:缓存(整合Red ...

  9. SpringCloud+SpringBoot+OAuth2+Spring Security+Redis实现的微服务统一认证授权

    因为目前做了一个基于Spring Cloud的微服务项目,所以了解到了OAuth2,打算整合一下OAuth2来实现统一授权.关于OAuth是一个关于授权的开放网络标准,目前的版本是2.0,这里我就不多 ...

最新文章

  1. 关于网站购买商品的一些感悟
  2. 关于inline函数
  3. python寻找屏幕上的特定字符_库Turtle:用Python指挥小海龟在屏幕上绘图,流行的儿童编程...
  4. vue @click 多个事件_VUE学习记录3
  5. 许可证密钥_如何激活和停用NVivo的许可证
  6. 选择 Veeam ONE v10 的其他三大原因!
  7. 想成为NLP算法工程师,你必须要看一下这10篇论文!
  8. 【python】*与** 参数问题
  9. 2018-04-26java实习面试记录
  10. 2017中国“互联网+”数字经济指数 | 腾讯研究院
  11. java解析marc乱码_国际C语言乱码大赛(IOCCC)的一个经典作品
  12. web前端入门到实战:行内和块状元素水平居中与单行或多行文本垂直居中及隐性改变display类型
  13. [转]体育运动比赛英语
  14. 第5章 字典之物品清单
  15. C语言文件操作+通讯录实现文件操作
  16. 如何补丁1个文件(linux diff patch)
  17. SpringCloud-4-OpenFeign
  18. SAP MM零基础学习-第一篇-模块简介
  19. bit(比特)和 byte(字节)的关系
  20. mysql还原.bak文件

热门文章

  1. 如何正确的设置使用代理IP?
  2. CATIA 二次开发 C#
  3. 高手如何做全网整合营销推广?全网营销方法和策略有哪些?
  4. 看过这篇文章,一切关于NFT的疑问都可以迎刃而解
  5. Failed to resolve: com.github.chrisbanes:PhotoView:1.2.6 Show in File Show i
  6. JAVA 导出Excel 单元格合并
  7. Linux 内核协议栈的 TSO、GSO
  8. 软件测试简历个人技能和项目经验怎么写?(附项目资料)
  9. 专业mac绘图软件:FireAlpaca for Mac
  10. Android实现截屏的方法