在上一篇文章[Spring Security OAuth2.0认证授权一:框架搭建和认证测试](https://www.cnblogs.com/kuangdaoyizhimei/p/14250374.html) 详细讲解了如何搭建一个基于spring boot + oauth2.0的认证服务,这篇文章将会介绍如何搭建一个资源服务。

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

1. 引入maven依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>

这里虽然引入了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表。

5. 接口测试

源代码地址: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认证授权二:搭建资源服务的更多相关文章

  1. Spring Security OAuth2.0认证授权三:使用JWT令牌

    Spring Security OAuth2.0系列文章: Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二: ...

  2. Spring Security OAuth2.0认证授权四:分布式系统认证授权

    Spring Security OAuth2.0认证授权系列文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授 ...

  3. Spring Security OAuth2.0认证授权五:用户信息扩展到jwt

    历史文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二:搭建资源服务 Spring Security OA ...

  4. Spring Security OAuth2.0认证授权六:前后端分离下的登录授权

    历史文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二:搭建资源服务 Spring Security OA ...

  5. Spring Security OAuth2.0认证授权一:框架搭建和认证测试

    一.OAuth2.0介绍 OAuth(开放授权)是一个开放标准,允许用户授权第三方应用访问他们存储在另外的服务提供者上的信息,而不 需要将用户名和密码提供给第三方应用或分享他们数据的所有内容. 1.s ...

  6. Spring security OAuth2.0认证授权学习第四天(SpringBoot集成)

    基础的授权其实只有两行代码就不单独写一个篇章了; 这两行就是上一章demo的权限判断; 集成SpringBoot SpringBoot介绍 这个篇章主要是讲SpringSecurity的,Spring ...

  7. Spring security OAuth2.0认证授权学习第三天(认证流程)

    本来之前打算把第三天写基于Session认证授权的,但是后来视屏看完后感觉意义不大,而且内容简单,就不单独写成文章了; 简单说一下吧,就是通过Servlet的SessionApi 通过实现拦截器的前置 ...

  8. Spring security OAuth2.0认证授权学习第一天(基础概念-认证授权会话)

    这段时间没有学习,可能是因为最近工作比较忙,每天回来都晚上11点多了,但是还是要学习的,进过和我的领导确认,在当前公司的技术架构方面,将持续使用Spring security,暂不做Shiro的考虑, ...

  9. Spring security OAuth2.0认证授权学习第二天(基础概念-授权的数据模型)

    如何进行授权即如何对用户访问资源进行控制,首先需要学习授权相关的数据模型. 授权可简单理解为Who对What(which)进行How操作,包括如下: Who,即主体(Subject),主体一般是指用户 ...

随机推荐

  1. 最简 Spring AOP 源码分析!

    前言 最近在研究 Spring 源码,Spring 最核心的功能就是 IOC 容器和 AOP.本文定位是以最简的方式,分析 Spring AOP 源码. 基本概念 上面的思维导图能够概括了 Sprin ...

  2. 【CSP-S 2019】树的重心(重心的性质)

    Description 给定一颗 \(n\) 个顶点的树 \(\text T\),共 \(n-1\) 次断边操作,每次将树分为两部分 \(\text T_1, \text T_2\),求: \[\su ...

  3. 题解-Enemy is weak

    Enemy is weak 求序列 \(a\{n\}\) 中的三元逆序对数量. 数据范围:\(3\le n\le 1e6\). 这题真是一道又好又水的题,可是我看别人的题解做法真是玄学难懂,于是蒟蒻要 ...

  4. vue2中$emit $on $off实现组件之间的联动,绝对有你想了解的

    在vue2开发中,你肯定会遇到组件之间联动的问题,现在我们就来说说哪个神奇的指令可以满足我们的需求. 一.先上实例: 需求:点击A组件或者B组件可以使C组件的名称相应发生改变,同样,点击A组件也会使对 ...

  5. STL—— 容器(vector)的各种功能方法

    1. 获取容器的元素个数 size() 使用 vectorName.size() 可以输出这个容器中类型的个数,如下代码: 1 #include <iostream> 2 #include ...

  6. Spring AOP的理解(通俗易懂)。

    转载 原文链接:http://www.verydemo.com/demo_c143_i20837.html 这种在运行时,动态地将代码切入到类的指定方法.指定位置上的编程思想就是面向切面的编程. 1. ...

  7. mac下git连接远程仓库gitee

    一.注册账号 https://gitee.com/ 二.创建仓库 三.创建后显示如下 四.根据页面上展示命令敲一遍就可以了. 备注:注意!!

  8. MySQL事务提交流程

    有binlog的CR方式(重点核心!!): 有binlog情况下,commit动作开始时,会有一个Redo XID 的动作记录写到redo,然后写data到binlog,binlog写成功后,会将bi ...

  9. C语言服务器编程必备常识

    入门 包含了正确的头文件只能编译通过,没链接正确的库链接会报错. 一些常用的库gcc会自动链接. 库的缺省路径/lib /usr/lib /usr/local/lib 不知道某个函数在那个库可以nm ...

  10. css精髓:这些布局你都学废了吗?

    前言 最近忙里偷闲,给自己加油充电的时候,发现自己脑海中布局这块非常的凌乱混杂,于是花了一些时间将一些常用的布局及其实现方法整理梳理了出来,在这里,分享给大家. 单列布局 单列布局是最常用的一种布局, ...