【问题标题】:Spring OAuth2 ResourceServer external AuthorizationServerSpring OAuth2 ResourceServer 外部 AuthorizationServer
【发布时间】:2017-10-17 09:59:30
【问题描述】:

你如何设置一个单独的 Spring OAuth2 ResourceServer,它使用和第 3 方 AuthorizationServer

我看到的所有示例总是在同一个应用程序中实现 ResourceServer 和 AuthorizationServer。

我不想实现 AuthorizationServer,因为其他人将提供它。

试过了,没有成功

@Configuration
   @EnableResourceServer
   public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter

而 application.yml 包括

security:
  oauth2:
    resource:
      userInfoUri: https://...../userinfo

向我的问题添加更多细节::

据我了解 - 使用 OAuth 有 4 个玩家:

  • 资源所有者:一个人
  • 资源服务器:暴露受保护 API 的服务器(受身份验证服务器保护)
  • 身份验证服务器:处理向客户端颁发访问令牌的服务器
  • 客户端:在资源所有者同意后访问资源服务器 API 的应用程序(例如网站)

我尝试了各种教程,但似乎都实现了自己的授权服务器

http://www.swisspush.org/security/2016/10/17/oauth2-in-depth-introduction-for-enterprises https://gigsterous.github.io/engineering/2017/03/01/spring-boot-4.html

或者是实现客户端播放器的示例

我的问题是: 如何仅通过 3rd 方身份验证服务器实现保护我的 REST API 的资源服务器,仅此而已。

【问题讨论】:

  • 我理解本指南的方式是它实现了使用外部身份验证服务器的客户端。就像我在问如何通过外部身份验证服务器保护我自己的 API 一样。添加到我的问题:
  • 没有问题 - 只是陈述。展示你有什么和你遇到了什么问题。
  • 据我所知,您需要实现 TokenServices 才能使用远程授权端点和 Tokenextractors。

标签: spring oauth-2.0


【解决方案1】:

我已经解决了这个问题 - 你只需要:

@SpringBootApplication
@EnableResourceServer
public class ResourceServer {

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

使用原始问题中发布的 application.yml:

security:
 oauth2:
   resource:
     userInfoUri: https://........userinfo

【讨论】:

    【解决方案2】:

    我创建了两个独立的示例应用程序,其中一个充当 oauth 客户端,另一个充当资源服务器,并且它们都使用外部身份验证服务器(在本示例中为 facebook)。

    示例中的场景如下,用户打开app1(oauth客户端)被重定向到首页,点击登录后会被重定向到facebook登录,登录成功后会跳转到回到第一页。如果他点击第一个按钮,将调用同一应用程序中的 api,并将显示在消息 1 标签旁边,如果他点击第二个按钮,将调用 app2(资源服务器)中的 api完成后,该消息将显示在消息 2 标签旁边。

    如果您检查了日志,您会发现从 app1 到 app2 的 api 调用在请求参数中包含访问令牌。 Logs for app1 calling app2

    请在git仓库here找到源代码

    这是 app1(oauth 客户端)的配置

    app1 网络安全配置

    @Configuration
    @EnableOAuth2Sso
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**").authorizeRequests().antMatchers("/", "/login**", "/webjars/**", "/error**").permitAll()
                .anyRequest().authenticated().and().logout().logoutSuccessUrl("/").permitAll().and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("DELETE");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
    }
    

    app1 应用程序属性

    security:
      oauth2:
        client:
          clientId: <your client id>
          clientSecret: <your client secret>
          accessTokenUri: https://graph.facebook.com/oauth/access_token
          userAuthorizationUri: https://www.facebook.com/dialog/oauth?redirect_url=https://localhost:8443/
          tokenName: access_token
          authenticationScheme: query
          clientAuthenticationScheme: form
          registered-redirect-uri: https://localhost:8443/
          pre-established-redirect-uri: https://localhost:8443/
        resource:
          userInfoUri: https://graph.facebook.com/me
    logging:
      level:
        org.springframework.security: DEBUG
    

    这是app2(资源服务器)的配置

    app2 资源服务器配置

    @Configuration
    @EnableResourceServer
    public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
        String[] ignoredPaths = new String[] { "/error", "/login", "/doLogut", "/home", "/pageNotFound", "/css/**",
                "/js/**", "/fonts/**", "/img/**" };
    
        @Value("${security.oauth2.resource.user-info-uri}")
        private String userInfoUri;
    
        @Value("${security.oauth2.client.client-id}")
        private String clientId;
    
        @Override
        public void configure(HttpSecurity http) throws Exception {
    
            http.authorizeRequests().antMatchers(ignoredPaths).permitAll().anyRequest().authenticated();
        }
    
        @Primary
        @Bean
        public UserInfoTokenServices tokenService() {
            final UserInfoTokenServices tokenService = new UserInfoTokenServices(userInfoUri, clientId);
            return tokenService;
        }
    }
    

    app2 应用程序属性

    security:
      oauth2:
        resource:
          userInfoUri: https://graph.facebook.com/me
        client:
          client-id: <your client id>
    logging:
      level:
        org.springframework.security: DEBUG  
    

    这是 app1 控制器调用 app2 上的 api (hi2 api)

    @RestController
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public class UserController {
    
        @Autowired
        OAuth2RestTemplate restTemplate;
    
        @RequestMapping("/user")
        public Principal user(Principal principal) {
            return principal;
        }
    
        @RequestMapping("/hi")
        public String hi(Principal principal) {
            return "Hi, " + principal.getName();
        }
    
        @RequestMapping("/hi2")
        public String hi2(Principal principal) {
            final String greeting = restTemplate.getForObject("http://127.0.0.1:8082/api/hello", String.class);
    
            System.out.println(greeting);
            return greeting;
        }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-01
    • 2020-06-03
    • 2021-05-25
    • 2017-02-09
    • 2016-01-15
    • 2015-09-28
    • 2018-09-09
    • 1970-01-01
    相关资源
    最近更新 更多