2021-01-11

返回主页
狂盗一枝梅
博客园首页新随笔联系订阅管理随笔 - 229 文章 - 1 评论 - 30
Spring Security OAuth2.0认证授权二:搭建资源服务
目录

  1. 引入maven依赖
  2. 配置配置文件
  3. 新建启动类
  4. Resource服务核心配置
    4.1 新建ResouceServerConfig类
    4.2 核心配置
    4.3 auth2.0安全配置
    4.4 Web安全配置
    4.5 暴露资源接口
  5. 接口测试
    5.1 准备工作
    5.2 获取token
    5.3 请求资源服务
    5.4 请求演示
    6.源代码
    在上一篇文章Spring Security OAuth2.0认证授权一:框架搭建和认证测试 详细讲解了如何搭建一个基于spring boot + oauth2.0的认证服务,这篇文章将会介绍如何搭建一个资源服务。

根据oath2.0协议内容,应当有一个资源服务管理资源并提供访问安全控制。

  1. 引入maven依赖

    org.springframework.boot
    spring-boot-starter-web


    org.springframework.cloud
    spring-cloud-starter-security


    org.springframework.cloud
    spring-cloud-starter-oauth2


    org.springframework.security
    spring-security-jwt


    com.alibaba
    fastjson


    org.projectlombok
    lombok

    这里虽然引入了jwt的依赖,但是暂时还未用到。

  2. 配置配置文件
    server:
    port: 30001
    spring:
    application:
    name: resource-server

  3. 新建启动类
    @SpringBootApplication
    public class ResourceServerApplication {

    public static void main(String[] args) {
    SpringApplication.run(ResourceServerApplication.class, args);
    }
    }

  4. Resource服务核心配置
    4.1 新建ResouceServerConfig类
    该类需要继承ResourceServerConfigurerAdapter类并需要使用@EnableResourceServer注解注释。

@Configuration
@EnableResourceServer
public class ResouceServerConfig extends ResourceServerConfigurerAdapter {

}
4.2 核心配置
重写ResouceServerConfig类以下方法以实现ResourceServer的基本配置:

org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter#configure(org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer)

@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources
.resourceId(RESOURCE_ID)
.tokenServices(resourceServerTokenServices)//令牌服务
.stateless(true);
}
resourceId方法标志了该服务的id,需要和在auth-center服务中配置的id一致。
tokenServices方法指定了令牌管理的实例,Bean创建方法如下
@Bean
public ResourceServerTokenServices resourceServerTokenServices(){
RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
remoteTokenServices.setCheckTokenEndpointUrl(“http://127.0.0.1:30000/oauth/check_token”);
remoteTokenServices.setClientId(“c1”);
remoteTokenServices.setClientSecret(“secret”);
return remoteTokenServices;
}
stateless方法指定了当前资源是否仅仅允许token验证的方法进行校验,默认为true
4.3 auth2.0安全配置
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").access("#oauth2.hasScope(‘all’)")
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
}
该配置和下面的Web安全配置很像,但是不一样,这里仅仅对auth2.0的安全进行配置。这里的.antMatchers("/
").access("#oauth2.hasScope(‘all’)")表示所有的请求携带的令牌都必须拥有all的授权范围,其中all授权范围必须和认证服务中的配置相一致。

4.4 Web安全配置
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf()
            .disable()
            .authorizeRequests()
            .antMatchers("/r/r1").hasAuthority("p2")
            .antMatchers("/r/r2").hasAuthority("p2")
            .antMatchers("/**").authenticated()//所有的r/**请求必须认证通过
            .anyRequest().permitAll();//其它所有请求都可以随意访问
}

}
4.5 暴露资源接口
@RestController
@Slf4j
public class OrderController {

@GetMapping("/r1")
@PreAuthorize("hasAnyAuthority('p1')")
public String r1(){
    return "访问资源r1";
}

}
由于4.4启用了prePostEnabled,所以这里可以使用@PreAuthorize注解对资源安全请求进行管理。

@PreAuthorize(“hasAnyAuthority(‘p1’)”)表示请求者必须拥有p1权限,p1权限定义在auth-center服务表的t_permission表。

  1. 接口测试
    源代码地址:https://gitee.com/kdyzm/spring-security-oauth-study/tree/v3.0.0

5.1 准备工作
首先,阅读下 https://gitee.com/kdyzm/spring-security-oauth-study/tree/v3.0.0/auth-center 项目的自述文件,配置好数据库和表、配置文件,配置完成之后分别启动认证服务auth-center服务(端口号30000)和资源服务resource-server(端口号30001)。

5.2 获取token
阅读下 https://gitee.com/kdyzm/spring-security-oauth-study/tree/v3.0.0/auth-center 项目的自述文件,有四种获取token的方式。

5.3 请求资源服务
假设在5.2已经成功获取到了token:

{
“access_token”: “11c5eaec-768f-400a-85e1-e2b52276b83d”,
“token_type”: “bearer”,
“refresh_token”: “34eb5d57-de7e-4f26-b35e-64162c64117e”,
“expires_in”: 7199,
“scope”: “all”
}
接下来要携带着token请求资源服务:

header value
Authorization Bearer 0cc2da26-b634-4ccb-a8fe-14f454a13090
GET请求:http://127.0.0.1:30001/r1

请求成功,结果返回:

访问资源r1
请求失败,结果返回:

{
“error”: “invalid_token”,
“error_description”: “0cc2da26-b634-4ccb-a8fe-14f454a13090”
}
5.4 请求演示
下面演示使用postman基于密码模式获取token并请求资源服务的过程:

6.源代码
源代码地址:https://gitee.com/kdyzm/spring-security-oauth-study/tree/v3.0.0

我的博客地址:https://blog.kdyzm.cn/

标签: Spring Security, OAuth2.0, JAVA
好文要顶 关注我 收藏该文
狂盗一枝梅
关注 - 13
粉丝 - 148
+加关注
00
« 上一篇: Spring Security OAuth2.0认证授权一:框架搭建和认证测试
posted @ 2021-01-11 10:30 狂盗一枝梅 阅读(68) 评论(0) 编辑 收藏
刷新评论刷新页面返回顶部
登录后才能发表评论,立即 登录 或 注册, 访问 网站首页
【推荐】阿里出品,对标P7!限时免费,七天深入MySQL实战营报名开启
【推荐】大型组态、工控、仿真、CADGIS 50万行VC++源码免费下载
【推荐】AWS携手博客园为开发者送福利,注册立享12个月免费套餐
【推荐】第一个NoSQL数据库,在大规模和一致性之间找到了平衡
【推荐】七牛云新老用户同享 1 分钱抢 CDN 1TB流量大礼包!
【推荐】了不起的开发者,挡不住的华为,园子里的品牌专区
【推荐】未知数的距离,毫秒间的传递,声网与你实时互动

相关博文:
· SpringSecurityOAuth2学习
· SpringSecurityOAuth2Demo——密码模式(Password)
· SpringSecurityOAuth2Demo——授权码模式
· SpringSecurityOAuth2Demo——隐式授权模式(Implicit)
· 使用JWT作为SpringSecurityOAuth2的token存储
» 更多推荐…

最新 IT 新闻:
· 为什么贝壳、百度、蔚来值得放在一起研究?
· 能刷好评也能删差评 大众点评变味了?
· 前懂球帝CTO许立强日前正式加入字节跳动 曾担任百度主任架构师
· 82万的新车一月连撞两车 女司机称刹车失灵!特斯拉:你去告我们
· 比宝马5系贵2万多!秦力洪:蔚来ET7订单达预期 不会降价
» 更多新闻…
公告
昵称: 狂盗一枝梅
园龄: 7年8个月
粉丝: 148
关注: 13
+加关注
< 2021年1月 >
日 一 二 三 四 五 六
27 28 29 30 31 1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31 1 2 3 4 5 6
搜索

常用链接
我的随笔
我的评论
我的参与
最新评论
我的标签
我的标签
JAVA EE(83)
JAVA(38)
数据采集系统(20)
PHP(14)
Spring(12)
Hibernate(12)
Struts2(11)
JavaScript(7)
JQuery(7)
java学习笔记(6)
更多
随笔分类
acm水题(2)
bfs应用(3)
c(13)
c++(6)
c语言之栈与队列(8)
dfs应用(4)
JAVA EE 学习笔记(85)
Java 学习笔记(33)
java大数处理(1)
MySQL学习笔记(1)
PHP学习笔记(13)
poj:简单题(3)
查找与排序(7)
大数算法(3)
函数使用(2)
模拟题(1)
数据结构大杂烩(3)
数据结构之树与二叉树(6)
数据结构之图论(9)
数据结构之线性表(9)
数学(2)
贪心法和动态规划(1)
无分类(2)
有疑问的题目和代码(2)
随笔档案
2021年1月(2)
2020年12月(3)
2018年3月(1)
2016年12月(1)
2016年1月(6)
2015年12月(24)
2015年11月(6)
2015年10月(3)
2015年9月(20)
2015年8月(10)
2015年7月(7)
2015年6月(8)
2015年5月(1)
2015年3月(3)
2015年2月(1)
2015年1月(6)
2014年11月(1)
2014年10月(19)
2014年9月(16)
2014年8月(2)
2014年7月(1)
2014年4月(2)
2014年3月(1)
2013年12月(7)
2013年11月(9)
2013年10月(9)
2013年9月(3)
2013年8月(37)
2013年7月(19)
2013年6月(1)
最新评论

  1. Re:Spring Security OAuth2.0认证授权一:框架搭建和认证测试
    @小小病毒丶 请教下 如何自定义传参和返回参数,比如传参的client_id 想换成clientId 你可以看下这个方法:org.springframework.security.oauth2.pro…
    –狂盗一枝梅
  2. Re:Spring Security OAuth2.0认证授权一:框架搭建和认证测试
    请教下 如何自定义传参和返回参数,比如传参的client_id 想换成clientId

–小小病毒丶
3. Re:Spring Security OAuth2.0认证授权一:框架搭建和认证测试
@孙长宇 spring-cloud-oauth2和spring-security-oauth2这些组件已经被标记为过期了,想升级到spring-boot 2.4.x和spring-cloud 2020…
–狂盗一枝梅
4. Re:Spring Security OAuth2.0认证授权一:框架搭建和认证测试
spring-cloud-oauth2和spring-security-oauth2这些组件已经被标记为过期了,想升级到spring-boot 2.4.x和spring-cloud 2020.x.x的…
–孙长宇
阅读排行榜

  1. 【Java EE 学习 21 下】【 使用易宝支付接口实现java网上支付功能】(12776)
  2. 【JAVA单例模式详解】(11646)
  3. 【Java EE 学习 67 上】【OA项目练习】【JBPM工作流的使用】(5082)
  4. 【Java EE 学习 67 下】【OA项目练习】【SSH整合JBPM工作流】【JBPM项目实战】(3739)
  5. 【Java远程debug】(3523)
    评论排行榜
  6. 【Java EE 学习 67 下】【OA项目练习】【SSH整合JBPM工作流】【JBPM项目实战】(5)
  7. Spring Security OAuth2.0认证授权一:框架搭建和认证测试(4)
  8. win10新版wsl2使用指南(3)
  9. 【Java EE 学习 74 上】【数据采集系统第六天】【使用Jfreechart的统计图实现】【Jfreechart的基本使用方法】(3)
  10. 【Java EE 学习 67 上】【OA项目练习】【JBPM工作流的使用】(2)
    推荐排行榜
  11. 【Java EE 学习 67 上】【OA项目练习】【JBPM工作流的使用】(7)
  12. 【Java EE 学习 74 上】【数据采集系统第六天】【使用Jfreechart的统计图实现】【Jfreechart的基本使用方法】(3)
  13. 【Java EE 学习 67 下】【OA项目练习】【SSH整合JBPM工作流】【JBPM项目实战】(3)
  14. 【JAVA单例模式详解】(3)
  15. 【Java EE 学习 69 上】【struts2】【paramsPrepareParamsStack拦截器栈解决model对象和属性赋值冲突问题】(2)
    Copyright © 2021 狂盗一枝梅
    Powered by .NET 5.0 on Kubernetes
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个获取当前日期时间,并将它以“XXXX年XX月XX日 hh:mm:ss”的格式输出打印的示例代码: ```java import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class DateUtils { // 获取当前日期时间,并将它以“XXXX年XX月XX日 hh:mm:ss”的格式输出打印 public static void showCurrentDateTime() { DateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); Date date = new Date(); String dateTime = dateFormat.format(date); System.out.println(dateTime); } // 计算并显示若天后的日期值 public static void showDateAfterDays(String currentDate, int days) { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { Date date = dateFormat.parse(currentDate); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_YEAR, days); Date newDate = calendar.getTime(); String newDateString = dateFormat.format(newDate); System.out.println(newDateString); } catch (ParseException e) { e.printStackTrace(); } } // 计算并显示两个日期之间相距的天数 public static void showDaysBetweenDates(String date1, String date2) { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { Date startDate = dateFormat.parse(date1); Date endDate = dateFormat.parse(date2); long diff = endDate.getTime() - startDate.getTime(); long diffDays = diff / (24 * 60 * 60 * 1000); System.out.println(diffDays); } catch (ParseException e) { e.printStackTrace(); } } } ``` 使用示例: ```java public static void main(String[] args) { // 获取当前日期时间,并将它以“XXXX年XX月XX日 hh:mm:ss”的格式输出打印 DateUtils.showCurrentDateTime(); // 计算并显示若天后的日期值 DateUtils.showDateAfterDays("2021-01-01", 10); // 计算并显示两个日期之间相距的天数 DateUtils.showDaysBetweenDates("2021-01-01", "2021-01-11"); } ``` 输出结果: ``` 2021年05月01日 15:23:45 2021-01-11 10 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值