SpringBoot 整合 oauth2(三)实现 token 认证
nanshan 2024-10-30 02:57 11 浏览 0 评论
内容导读
这里重写了security认证UserDetailsService 的接口方法,添加了自定义数据库密码的查询和校验。没搞过dubbo的朋友就把它当作是调用service层就行。描述: 从request的请求头中拿到Authorization信息,根据clientId获取到secret和请求头中的secret信息做对比,如果正确,组建一个新的TokenRequest类,然后根据前者和clientDetails创建OAuth2Request对象,然后根据前者和authentication创建OAuth2Authentication对象。注意是Basic 开头然后是clientid:clientScret 格式进行base64加密后的字符串。一般来讲,认证服务器是第三方提供的服务,比如你想接入qq登陆接口,那么认证服务器就是腾讯提供,然后你在本地做资源服务,但是认证和资源服务不是非要物理上的分离,只需要做到逻辑上的分离就好。认证服务中,我们获取到ClientDetailsServiceConfigurer 并设置clientId和secret还有令牌有效期,还有支持的授权模式,还有用户权限范围。
关于session和token的使用,网上争议一直很大。
总的来说争议在这里:
- session是空间换时间,而token是时间换空间。session占用空间,但是可以管理过期时间,token管理部了过期时间,但是不占用空间.
- sessionId失效问题和token内包含。
- session基于cookie,app请求并没有cookie 。
- token更加安全(每次请求都需要带上)。
开始正文了...
本文大概流程:
oauth2流程简介
我在这里只介绍常用的密码授权。
Oauth2 密码授权流程
在oauth2协议里,每一个应用都有自己的一个clientId和clientSecret(需要去认证方申请),所以一旦想通过认证,必须要有认证方下发的clientId和secret。
原理这块确实很麻烦,希望不理解的多看看参考文档。
1. pom
<!--security--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> </dependency>
2. 项目架构介绍
我们需要这七个类来完成。
3. UserDetail实现认证第一步
MyUserDetailsService.java
/** * Created by Fant.J. */ @Component public class MyUserDetailsService implements UserDetailsService { @Reference(version = "2.0.0") private UserService userService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { String passwd = ""; System.out.println("收到的账号"+username); if (CheckFormat.isEmail(username)){ passwd = userService.selectPasswdByEmail(username); }else if (CheckFormat.isPhone(username)){ passwd = userService.selectPasswdByPhone(username); }else { throw new RuntimeException("登录账号不存在"); } System.out.println("查到的密码"+passwd); return new User(username, passwd, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")); } }
这里重写了security认证UserDetailsService 的接口方法,添加了自定义数据库密码的查询和校验。
为什么我把它放在了controller包了呢,因为我用的dubbo,@Reference注解扫描包是controller。这注解在别的包下失效。没搞过dubbo的朋友就把它当作是调用service层就行。
4. 认证成功/失败处理器
改动一:去掉了返回view还是json的判断,统一返回json。
改动二:修改登陆成功处理器,添加oauth2 客户端的认证。
MyAuthenticationFailHandler.java
/** * 自定义登录失败处理器 * Created by Fant.J. */ @Component public class MyAuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler { private Logger logger = LoggerFactory.getLogger(getClass()); @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { logger.info("登录失败"); //设置状态码 response.setStatus(500); response.setContentType("application/json;charset=UTF-8"); //将 登录失败 信息打包成json格式返回 response.getWriter().write(JSON.toJSONString(ServerResponse.createByErrorMessage(exception.getMessage()))); } }
MyAuthenticationSuccessHandler.java
/** * Created by Fant.J. */ @Component public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private ClientDetailsService clientDetailsService; @Autowired private AuthorizationServerTokenServices authorizationServerTokenServices; @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { logger.info("登录成功"); String header = request.getHeader("Authorization"); if (header == null && !header.startsWith("Basic")) { throw new UnapprovedClientAuthenticationException("请求投中无client信息"); } String[] tokens = this.extractAndDecodeHeader(header, request); assert tokens.length == 2; //获取clientId 和 clientSecret String clientId = tokens[0]; String clientSecret = tokens[1]; //获取 ClientDetails ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); if (clientDetails == null){ throw new UnapprovedClientAuthenticationException("clientId 不存在"+clientId); //判断 方言 是否一致 }else if (!StringUtils.equals(clientDetails.getClientSecret(),clientSecret)){ throw new UnapprovedClientAuthenticationException("clientSecret 不匹配"+clientId); } //密码授权 模式, 组建 authentication TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_MAP,clientId,clientDetails.getScope(),"password"); OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails); OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request,authentication); OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(oAuth2Authentication); //判断是json 格式返回 还是 view 格式返回 //将 authention 信息打包成json格式返回 response.setContentType("application/json;charset=UTF-8"); response.getWriter().write(JSON.toJSONString(ServerResponse.createBySuccess(token))); } /** * 解码请求头 */ private String[] extractAndDecodeHeader(String header, HttpServletRequest request) throws IOException { byte[] base64Token = header.substring(6).getBytes("UTF-8"); byte[] decoded; try { decoded = Base64.decode(base64Token); } catch (IllegalArgumentException var7) { throw new BadCredentialsException("Failed to decode basic authentication token"); } String token = new String(decoded, "UTF-8"); int delim = token.indexOf(":"); if (delim == -1) { throw new BadCredentialsException("Invalid basic authentication token"); } else { return new String[]{token.substring(0, delim), token.substring(delim + 1)}; } } }
描述:
从request的请求头中拿到Authorization信息,根据clientId获取到secret和请求头中的secret信息做对比,如果正确,组建一个新的TokenRequest类,然后根据前者和clientDetails创建OAuth2Request对象,然后根据前者和authentication创建OAuth2Authentication对象。最后通过AuthorizationServerTokenServices和前者前者创建OAuth2AccessToken对象。然后将token返回。
提示:
密码授权,我们在请求token的时候,需要一个包含clientid和clientSecret的请求头还有三个参数。
- 请求头:Authorization -> Basic aW50ZXJuZXRfcGx1czppbnRlcm5ldF9wbHVz 。注意是Basic 开头然后是clientid:clientScret 格式进行base64加密后的字符串。
- 请求参数:username和password是必须要的参数,值对应的就是账号密码,还有给可有可无的就是scope,它来声明该用户有多大的权限,默认是all。grant_type也是默认的参数,默认是password,它表示你以哪种认证模式来认证。
这是请求头解密现场
5. 配置认证/资源服务器
MyResourceServerConfig.java
/** * 资源服务器 * Created by Fant.J. */ @Configuration @EnableResourceServer public class MyResourceServerConfig extends ResourceServerConfigurerAdapter { @Autowired private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler; @Autowired private MyAuthenticationFailHandler myAuthenticationFailHandler; @Override public void configure(HttpSecurity http) throws Exception { //表单登录 方式 http.formLogin() .loginPage("/authentication/require") //登录需要经过的url请求 .loginProcessingUrl("/authentication/form") .successHandler(myAuthenticationSuccessHandler) .failureHandler(myAuthenticationFailHandler); http .authorizeRequests() .antMatchers("/user/*") .authenticated() .antMatchers("/oauth/token").permitAll() .anyRequest() .permitAll() .and() //关闭跨站请求防护 .csrf().disable(); } }
我这里只需要认证/user/*开头的url。@EnableResourceServer这个注解就决定了这十个资源服务器。它决定了哪些资源需要什么样的权限。
MyAuthorizationServerConfig.java
/** * 认证服务器 * Created by Fant.J. */ @Configuration @EnableAuthorizationServer public class MyAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Autowired private UserDetailsService userDetailsService; @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { super.configure(security); } /** * 客户端配置(给谁发令牌) * @param clients * @throws Exception */ @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory().withClient("internet_plus") .secret("internet_plus") //有效时间 2小时 .accessTokenValiditySeconds(72000) //密码授权模式和刷新令牌 .authorizedGrantTypes({"refresh_token","password"}) .scopes( "all"); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .authenticationManager(authenticationManager) .userDetailsService(userDetailsService); } } }
@EnableAuthorizationServer就代表了它是个认证服务端。
一般来讲,认证服务器是第三方提供的服务,比如你想接入qq登陆接口,那么认证服务器就是腾讯提供,然后你在本地做资源服务,但是认证和资源服务不是非要物理上的分离,只需要做到逻辑上的分离就好。
认证服务中,我们获取到ClientDetailsServiceConfigurer 并设置clientId和secret还有令牌有效期,还有支持的授权模式,还有用户权限范围。
执行
好了,启动项目。
1. 给/oauth/token 发送post请求获取token
请求头:Authorization:Basic +clientid:secret 的base64加密字符串 (认证服务器中设置的client信息)
请求参数:username password (用户登陆账号密码)
{ "data": { "refreshToken": { "expiration": 1528892642111, "value": "xxxxxx-xxxxxx-xxxxx-xxxxxxxx" }, "scope": [ "all" ], "tokenType": "bearer", "value": "xxxxxx-xxxxxx-xxxxx-xxxxxxxx" }, "status": 200, "success": true }
2. 给/oauth/token 发送post请求刷新token
请求头: 不需要
请求参数:
- grant_type:refresh_token
- refresh_token:获取token时返回的refreshToken的value
3. 访问受保护的资源,比如/user/2
类型:get请求
请求头:Authorization: bearer + tokenValue
介绍下我的所有文集:
流行框架
底层实现原理:
相关推荐
- 雷军1994年写的老代码曝光,被称像诗一样优雅
-
大数据文摘授权转载自程序员的那些事雷军的代码像诗一样优雅↓↓↓有些网友在评论中质疑,说雷军代码不会是“屎”一样优雅吧。说这话的网友,也许是开玩笑的,也许是真没看过雷军写过的代码。在2011年的时候,我...
- 原创经验分享:低级bug耗费12小时Fix
-
调试某程序非常简单的程序,简单到认为不可能存在缺陷,但该BUG处理时间超过12小时:程序属于后台进程,监控系统每隔15秒检查外设IO状态,IO异常后发出报警或复位外设,外设都在linux下有/sys/...
- SpringBoot实现的简单停车位管理系统附带导入和演示教程视频
-
这一次为大家带来的是简单的停车位管理系统,基于SpringBoot+Thymeleaf+Mybatis框架,这个系统相对来说比较简单,很容易学习并快速上手,因为逻辑很清晰,没有太复杂的代码逻辑,所以学...
- 一个开箱即用的代码生成器(代码自动生成工具开源)
-
今天给大家推荐一个好用的代码生成器,名为renren-generator,该项目附带前端页面,可以很方便的选择我们所需要生成代码的表。首先我们通过git工具克隆下来代码(地址见文末),导入idea。...
- 【免费开源】JeecgBoot单点登录源码全部开源了
-
JeecgBoot单点登录源码全部开源了,有需要的朋友可以来薅羊毛了。一、JeecgBoot介绍JeecgBoot是一款企业级的低代码平台!前后端分离架构SpringBoot2.x,SpringCl...
- SpringBoot+JWT+Shiro+Mybatis实现Restful快速开发后端脚手架
-
作者:lywJee来源:cnblogs.com/lywJ/p/11252064.html一、背景前后端分离已经成为互联网项目开发标准,它会为以后的大型分布式架构打下基础。SpringBoot使编码配置...
- 为什么越来越多的人选择使用idea软件
-
IDEA软件是什么?IDEA软件是干什么的?为什么越来越多的人选择使用IDEA软件?IDEA软件,全称IntelliJIDEA,它是由JetBrains公司开发开发的一款功能强大的集成开发环境(ID...
- 开题报告大学生互助系统(附源码)java毕设
-
本系统(程序+源码)带文档lw万字以上文末可获取一份本项目的java源码和数据库参考。系统程序文件列表开题报告内容选题背景随着互联网技术的飞速发展,大学生群体对信息共享与互助的需求日益增长。关于大...
- SpringBoot项目快速开发框架JeecgBoot——项目简介及系统架构!
-
项目简介及系统架构JeecgBoot是一款基于SpringBoot的开发平台,它采用前后端分离架构,集成的框架有SpringBoot2.x、SpringCloud、AntDesignof...
- 新手配电脑13代CPU怎么选择(新手配电脑13代cpu怎么选择好)
-
Intel第13代酷睿i3、i5、i7、i9系列处理器的核心参数、性能差异及适用群体的详细说明(以桌面端为例):一、13代酷睿全系参数对比(桌面端主流型号)参数i3-13100i5-13600Ki7-...
- 加速 SpringBoot 应用开发,官方热部署神器真带劲
-
平时使用SpringBoot开发应用时,修改代码后需要重新启动才能生效。如果你的应用足够大的话,启动可能需要好几分钟。有没有什么办法可以加速启动过程,让我们开发应用代码更高效呢?今天给大家推荐一款Sp...
- 基于微信小程序的移动端物流系统-计算机毕业设计源码+LW文档
-
摘要随着Internet的发展,人们的日常生活已经离不开网络。未来人们的生活与工作将变得越来越数字化,网络化和电子化。网上管理,它将是直接管理移动端物流系统app的最新形式。本论文是以构建移动端物流系...
- springboot教务管理系统+微信小程序云开发附带源码
-
今天给大家分享的程序是基于springboot的管理,前端是小程序,系统非常的nice,不管是学习还是毕设都非常的靠谱。本系统主要分为pc端后台管理和微信小程序端,pc端有三个角色:管理员、学生、教师...
- SpringBoot全家桶:23篇博客加23个可运行项目让你对它了如指掌
-
SpringBoot现在已经成为Java开发领域的一颗璀璨明珠,它本身是包容万象的,可以跟各种技术集成。本项目对目前Web开发中常用的各个技术,通过和SpringBoot的集成,并且对各种技术通...
- Maven+JSP+Servlet+C3P0+Mysql实现的音乐库管理系统
-
本系统基于Maven+JSP+Servlet+C3P0+Mysql实现的音乐库管理系统。简单实现了充值、购买歌曲、poi数据导入导出、歌曲上传下载、歌曲播放、用户注册登录注销等功能。难度等级:简单技术...
你 发表评论:
欢迎- 一周热门
-
-
UOS服务器操作系统防火墙设置(uos20关闭防火墙)
-
极空间如何无损移机,新Z4 Pro又有哪些升级?极空间Z4 Pro深度体验
-
手机如何设置与显示准确时间的详细指南
-
如何修复用户配置文件服务在 WINDOWS 上登录失败的问题
-
如何在安装前及安装后修改黑群晖的Mac地址和Sn系列号
-
NAS:DS video/DS file/DS photo等群晖移动端APP远程访问的教程
-
日本海上自卫队的军衔制度(日本海上自卫队的军衔制度是什么)
-
10个免费文件中转服务站,分享文件简单方便,你知道几个?
-
爱折腾的特斯拉车主必看!手把手教你TESLAMATE的备份和恢复
-
FANUC 0i-TF数据备份方法(fanuc系统备份教程)
-
- 最近发表
- 标签列表
-
- linux 查询端口号 (58)
- docker映射容器目录到宿主机 (66)
- 杀端口 (60)
- yum更换阿里源 (62)
- internet explorer 增强的安全配置已启用 (65)
- linux自动挂载 (56)
- 禁用selinux (55)
- sysv-rc-conf (69)
- ubuntu防火墙状态查看 (64)
- windows server 2022激活密钥 (56)
- 无法与服务器建立安全连接是什么意思 (74)
- 443/80端口被占用怎么解决 (56)
- ping无法访问目标主机怎么解决 (58)
- fdatasync (59)
- 405 not allowed (56)
- 免备案虚拟主机zxhost (55)
- linux根据pid查看进程 (60)
- dhcp工具 (62)
- mysql 1045 (57)
- 宝塔远程工具 (56)
- ssh服务器拒绝了密码 请再试一次 (56)
- ubuntu卸载docker (56)
- linux查看nginx状态 (63)
- tomcat 乱码 (76)
- 2008r2激活序列号 (65)