5、oauth2之资源服务配置类EnableResourceServer

简介

资源服务器会对所有的请求进行拦截认证,当然除了oauth相关的请求之外。同时会创建一个拦截器OAuth2AuthenticationProcessingFilter,该拦截器会对请求头Authorization中的值进行相关验证。

使用方式:

1、添加注解@EnableResourceServer

2、继承ResourceServerConfigurerAdapter

@Configuration
@EnableResourceServer
public static class ResourceServerConfigurer extends ResourceServerConfigurerAdapter {
   
}

@EnableResourceServer导入了ResourceServerConfiguration配置类,该配置类继承了WebSecurityConfigurerAdapter,拥有了http security的相关能力。

@Configuration
public class ResourceServerConfiguration extends WebSecurityConfigurerAdapter implements Ordered {
......

 //请求匹配,对oauth相关请求放行,其他请求拦截
   private static class NotOAuthRequestMatcher implements RequestMatcher {

      private FrameworkEndpointHandlerMapping mapping;

      public NotOAuthRequestMatcher(FrameworkEndpointHandlerMapping mapping) {
         this.mapping = mapping;
      }

      @Override
      public boolean matches(HttpServletRequest request) {
         String requestPath = getRequestPath(request);
         for (String path : mapping.getPaths()) {
            if (requestPath.startsWith(mapping.getPath(path))) {
               return false;
            }
         }
         return true;
      }

      private String getRequestPath(HttpServletRequest request) {
         String url = request.getServletPath();

         if (request.getPathInfo() != null) {
            url += request.getPathInfo();
         }

         return url;
      }

   }

   @Override
   protected void configure(HttpSecurity http) throws Exception {
       //资源服务可配置类,添加了OAuth2AuthenticationProcessingFilter过滤器,对请求头Authorization进行验证
      ResourceServerSecurityConfigurer resources = new ResourceServerSecurityConfigurer();
      ResourceServerTokenServices services = resolveTokenServices();
      if (services != null) {
         resources.tokenServices(services);
      }
      else {
         if (tokenStore != null) {
            resources.tokenStore(tokenStore);
         }
         else if (endpoints != null) {
            resources.tokenStore(endpoints.getEndpointsConfigurer().getTokenStore());
         }
      }
      if (eventPublisher != null) {
         resources.eventPublisher(eventPublisher);
      }
      for (ResourceServerConfigurer configurer : configurers) {
         configurer.configure(resources);
      }
      // @formatter:off
      http.authenticationProvider(new AnonymousAuthenticationProvider("default"))
      // N.B. exceptionHandling is duplicated in resources.configure() so that
      // it works
      .exceptionHandling()
            .accessDeniedHandler(resources.getAccessDeniedHandler()).and()//访问拒绝处理类
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .csrf().disable();
      // @formatter:on
      http.apply(resources);
      if (endpoints != null) {
         // Assume we are in an Authorization Server
         http.requestMatcher(new NotOAuthRequestMatcher(endpoints.oauth2EndpointHandlerMapping()));
      }
      for (ResourceServerConfigurer configurer : configurers) {
         // Delegates can add authorizeRequests() here
         configurer.configure(http);
      }
      if (configurers.isEmpty()) {
         // Add anyRequest() last as a fall back. Spring Security would
         // replace an existing anyRequest() matcher with this one, so to
         // avoid that we only add it if the user hasn't configured anything.
         http.authorizeRequests().anyRequest().authenticated();
      }
   }
......

}

附流程图

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: Spring Boot 中的 OAuth 资源服务配置需要在应用程序的配置文件中添加一些属性,并在应用程序中启用 OAuth 资源服务器。 1. 在配置文件中添加以下属性: - spring.security.oauth2.resource.jwt.key-value: 用于验证 JWT 令牌的公钥或私钥 - spring.security.oauth2.resource.user-info-uri: 用于获取用户信息的 URI 2. 在应用程序中启用 OAuth 资源服务器: - 在主中添加 @EnableResourceServer 注解 - 在配置中添加 @EnableAuthorizationServer 注解 3. 配置安全配置,在这个中添加配置信息 参考代码: ``` @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Value("${spring.security.oauth2.resource.jwt.key-value}") private String jwtKeyValue; @Value("${spring.security.oauth2.resource.user-info-uri}") private String userInfoUri; @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId("resource-server-rest-api").tokenStore(tokenStore()); } @Bean public TokenStore tokenStore() { return new JwtTokenStore(jwtTokenEnhancer()); } @Bean protected JwtAccessTokenConverter jwtTokenEnhancer() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setSigningKey(jwtKeyValue); return converter; } @Override public void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/api/**").authenticated() .and() .requestMatcher(new OAuthRequestedMatcher()); } private static class OAuthRequestedMatcher implements RequestMatcher { public boolean matches(HttpServletRequest request) { String auth = request.getHeader("Authorization"); // Determine if the client request contained an OAuth Authorization boolean haveOauth2Token = (auth != null) && auth.startsWith("Bearer"); boolean haveAccessToken = request.getParameter(" ### 回答2: Spring Boot中的OAuth资源服务配置是通过添加相关依赖和配置文件来实现的。 首先,我们需要在项目的pom.xml文件中添加Spring Security和Spring Security OAuth2的依赖,例如: ``` <dependencies> <!-- Spring Security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- Spring Security OAuth2 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency> </dependencies> ``` 然后,我们需要在项目的配置文件(例如application.yml)中配置相关的OAuth2资源服务器属性,例如: ``` spring: security: oauth2: resourceserver: jwt: issuer-uri: <身份验证服务器的URL> ``` 在上述配置中,我们需要指定身份验证服务器的URL,它将用于验证和解析传入的JWT令牌。 接下来,我们可以创建一个配置资源服务器的行为,例如: ```java @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/public/**").permitAll() .anyRequest().authenticated(); } } ``` 在上述示例中,我们使用@EnableResourceServer注解启用资源服务器,并指定了访问权限规则。在这个例子中,我们允许/public路径下的请求被所有人访问,其他任何请求都需要通过身份验证。 最后,我们可以使用@RestController注解创建一个简单的REST控制器来演示资源服务器的功能,例如: ```java @RestController public class HelloController { @GetMapping("/hello") public String hello() { return "Hello, World!"; } } ``` 这样,我们就可以使用OAuth2的令牌来访问该控制器所暴露的资源。 综上所述,通过添加依赖、配置属性和编写相关配置,我们可以在Spring Boot中配置OAuth资源服务器。 ### 回答3: 在Spring Boot中配置OAuth资源服务器包括以下步骤: 1. 添加必要的依赖:在pom.xml文件中添加Spring Security OAuth2依赖。例如,可以添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> </dependency> ``` 2. 创建一个配置:创建一个@Configuration注解的配置,并使用@EnableResourceServer注解启用资源服务器。例如: ``` @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/api/**").authenticated() .anyRequest().permitAll(); } @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId("my-resource-id"); } } ``` 3. 配置访问权限:使用HttpSecurity配置http的请求权限。在上述示例中,`/api/**`路径的请求需要进行身份验证。可以根据实际情况配置其他路径和权限。 4. 配置资源ID:使用ResourceServerSecurityConfigurer配置资源服务器的资源ID。资源ID可以是任何唯一标识符,用于标识受保护的资源。 以上是基本的OAuth资源服务配置步骤。配置完成后,可以使用OAuth2的授权服务器进行认证,并使用访问令牌对受保护的资源进行访问控制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值