【问题标题】:How to get access token from facebook using spring boot security如何使用spring boot security从facebook获取访问令牌
【发布时间】:2019-08-16 10:29:26
【问题描述】:

我必须使用 spring security 从 facebook 获取访问令牌,我有以下 HTTP 配置代码

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .antMatcher("/**")
                .authorizeRequests()
                .antMatchers("/", "/login**", "/webjars/**")
                .permitAll()
                .anyRequest()
                .authenticated().and().exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/"))
        .and().logout().logoutSuccessUrl("/").permitAll()
        .and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
        .and().addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
    }

另外,我可以在登录 facebook 后获取委托人。但我需要获取登录的用户访问令牌。

这些是我用于 Spring Boot 安全性的依赖项,

    implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
    implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    compile group: 'org.springframework.security.oauth.boot', name: 'spring-security-oauth2-autoconfigure', version: '2.1.3.RELEASE'

这是我正在使用的过滤器,

private Filter ssoFilter() {
    OAuth2ClientAuthenticationProcessingFilter facebookFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/facebook");
    OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(facebook(), oauth2ClientContext);
    facebookFilter.setRestTemplate(facebookTemplate);
    UserInfoTokenServices tokenServices = new UserInfoTokenServices(facebookResource().getUserInfoUri(), facebook().getClientId());

    tokenServices.setRestTemplate(facebookTemplate);
    facebookFilter.setTokenServices(tokenServices);

    return facebookFilter;
}

有没有办法使用spring boot security获取访问令牌

【问题讨论】:

  • 为什么要手动添加过滤器而不是使用@EnableOAuth2Sso
  • 相反,我使用的是@EnableOAuth2Client,所以我手动添加了一个过滤器。如果我使用@EnableOAuth2Sso,我可以获得访问令牌吗?
  • 一般来说是有办法的(可以看OAuth2RestTemplate本身是怎么做的);如果你能解释你想用它做什么,而透明地使用模板是无法完成的,那将会很有帮助。
  • 唯一的事情是我必须获得访问令牌,所以我手动配置了过滤器并使用@EnableOAuth2Client,如果可以使用@EnableOAuth2Sso 来实现,我会去的
  • 我在登录 Facebook 后从OAuth2RestTemplate 获得了访问令牌

标签: java spring spring-boot spring-security


【解决方案1】:

如果 facebook 与 spring security 的集成是正确的,你可以注入:

@Autowired
OAuth2ClientContext oAuth2ClientContext;

并使用此对象获取令牌:

oAuth2ClientContext.getAccessToken().getValue();

【讨论】:

    猜你喜欢
    • 2019-11-11
    • 2018-12-01
    • 2020-04-09
    • 2018-02-05
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多