Spring Security OAuth2.0(18):资源服务测试

文章目录

资源服务器配置

@EnableResourceServer注解到一个@Configuration配置类上,并且必须使用ResourceServerConfigurer这个配置对象来进行配置(可以选择继承自ResourceServerConfigurerAdapter然后覆写其中的方法,参数就是这个对象的实例),下面是一些可以配置的属性:

ResourceServerSecurityConfigurer中主要包括:

  • tokenServices: ResourceServerTokenServices类的实例,用来实现令牌服务。
  • tokenStore:TokenStore类的实例,指定令牌如何访问,与tokenServices配置可选
  • resourceId:这个资源服务的ID,这个属性是可选的,但是推荐设置并在授权服务中进行验证。
  • 其他的扩展属性例如tokenExtrator令牌提取器用来提取请求中的令牌。

HttpSecurity配置这个与Spring Security 类似:

  • 请求匹配器,用来设置需要进行保护的资源路径,默认的情况下是保护资源服务的全部路径。
  • 通过http.authorizeRequests()来设置受保护的访问规则
  • 其他的自定义权限保护规则通过HttpSecurity来进行配置。

@EnableResourceServer 注解自动增加了一个类型为OAuth2AuthenticationProcessingFilter的过滤器链。

编写资源

在order模块下创一个资源

java 复制代码
@RestController
public class OrderController {

    @GetMapping("r1")
    @PreAuthorize("hasAnyAuthority('p1')")  // 拥有p1权限可以访问此资源
    public String r1(){
        return "资源1";
    }
}

配置资源服务

在order模块下,创建配置 ResourceServerConfig

java 复制代码
package com.it2.security.distributed.order.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {


    public static final String RESOURCE_ID ="res1";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID) //资源id
                .tokenServices(tokenService()) //验证令牌的服务
                .stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
       http.authorizeRequests()
               .antMatchers("/**").access("#oauth2.hasScope('all')")
               .and().csrf().disable()
               .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

}

验证token

ResourceServerTokenServices 是组成授权服务的另一半,如果你的授权服务器和资源服务在同一个应用程序的话,你可以使用DefaultTokenServices,这样的话,你就不用考虑关于实现所有必要接口的接口的一致性问题。如果你的资源服务器是分离开的,那么你就需必须确保能够有匹配授权服务提供的ResourceServerTokenServices,它知道如何对令牌进行解码。

令牌解析方法:

使用DefaultTokenServices 在资源服务器本地配置令牌存储,解码,解析方式

使用RemoteTokenServices 资源服务器通过HTTP 请求来解码令牌,每次都请求授权服务器端点/oauth/check_token

使用授权服务的/oauth/check_token 端点你需要在授权服务将这个端点暴露出去,以便资源服务可以进行访问,这在授权服务配置中提到过,下面是一个例子,已经在授权中配置了 /oauth/check_token和/oauth/token_key这两个端点

java 复制代码
 @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
      security.tokenKeyAccess("permitAll()") //oauth/token_key 公开
              .checkTokenAccess("permitAll()") //oauth/check_token 公开
              .allowFormAuthenticationForClients();  //表单认证,申请令牌
    }

添加安全访问控制

*必须配置HttpSecurity ,否则会导致没有该资源权限也能访问。

在order的config下添加安全访问控制

java 复制代码
import org.springframework.context.annotation.Configuration;
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.WebSecurityConfigurerAdapter;

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true) //开启不同的方法权限注解
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {



    //配置安全拦截机制
    protected void configure(HttpSecurity security) throws Exception {
        security.csrf().disable().authorizeRequests()
                .antMatchers("/r/**").authenticated()//所有的/r/**的请求必须认证通过
                .anyRequest().permitAll(); //除此之外的请求,都可以访问
    }


}

查看令牌权限

http://localhost:53020/uaa/oauth/check_token

问题

这种方式的缺点:每次请求进行鉴权时,都需要请求远程接口,请求量大时,这种网络请求将会占用大量网络资源。

相关推荐
阿无,19 分钟前
布隆过滤器
java·算法·哈希算法
掘金者阿豪19 分钟前
Codex 怎么突然变慢了?一个需求跑几十分钟,我才发现它的工作方式已经变了
前端·后端
Pocker_Spades_A24 分钟前
飞算JavaAI 48分钟能做完Java全栈项目吗?
java·springboot·#ai编程·#飞算javaai·#java代码生成·#aicoding模型·#java开发
Zadig24 分钟前
Zadig 全面支持 CRD,至此所有 K8s 资源类型均可一键发布!
后端·devops
得物技术33 分钟前
EP-Harness:从个人 AI Coding 到团队级 Agent 工作流|得物技术
后端·程序员·架构
用户1257585243636 分钟前
对象存储 URL 为什么别到处拼:后台附件预览要验这一层
后端·go·ai编程
步行cgn43 分钟前
MyBatis 一对多关联映射详解
java·后端
阿弱1 小时前
pi 扩展机制:加载、执行与能力
后端·llm·agent
用户3126874877201 小时前
线程池到底怎么调?从源码看懂 ThreadPoolExecutor 的 7 个参数
java
caimouse1 小时前
ReactOS 图形系统分析(53):系统库存对象 — stockobj.c
c语言·开发语言·spring