使用 spring-boot-starter-oauth2-client 检索 OAuth2 3-legged 身份验证的访问令牌

j.xavier.atero

我想知道如何使用提供的功能在 Spring Boot 3-legged 身份验证上检索访问令牌 org.springframework.boot:spring-boot-starter-oauth2-client

我能够使用常规RestTemplate调用获取访问令牌

我尝试spring-boot-starter-oauth2-client按照https://github.com/wonwoo/spring-boot-oauth2-login 中的示例使用这些功能获取相同的访问令牌

我能够检索服务器提供的代码,但我不知道如何获取访问令牌。

我的代码如下所示:

属性在application.properties

spring.security.oauth2.client.registration.my-client-name-here.client-id=__client_id_here__
spring.security.oauth2.client.registration.my-client-name-here.client-secret=__client_secret_here__
spring.security.oauth2.client.registration.my-client-name-here.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.my-client-name-here.redirect-uri-template=http://localhost:8080/authentication/3leggedtoken/callback
spring.security.oauth2.client.registration.my-client-name-here.scope=data:read
spring.security.oauth2.client.registration.my-client-name-here.client-name=__client_name_here__
spring.security.oauth2.client.registration.my-client-name-here.client-authentication-method=POST
spring.security.oauth2.client.provider.my-client-name-here.token-uri=https://example.com/api/token
spring.security.oauth2.client.provider.my-client-name-here.authorization-uri=https://example.com/api/authorize
spring.security.oauth2.client.provider.my-client-name-here.user-info-uri=
spring.security.oauth2.client.provider.my-client-name-here.user-name-attribute=

Thymeleaf 模板在login.html

<div th:each="registration: ${registrations}">
  <a th:href="@{${registration.uri}}">
      Sign in with [[${registration.clientName}]]
  </a>
</div>

配置SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SegurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http_security) throws Exception {
        http_security.authorizeRequests().requestMatchers(PathRequest.toStaticResources().atCommonLocations())
                .permitAll().antMatchers("/authentication/**").permitAll().anyRequest().authenticated().and().oauth2Login()
                .loginPage("/authentication/login").permitAll();
    }
}

控制器AuthenticationController.java

@Controller
public class AuthenticationController {

    @Autowired
    OAuth2AuthorizedClientService clientService;

    @Autowired
    InMemoryClientRegistrationRepository clientRegistrationRepository;

    @GetMapping("authentication/login")
    public String login(Model model) {
        List<Registration> registrations = StreamSupport.stream(clientRegistrationRepository.spliterator(), true)
                .map(clientRegistration -> new Registration(clientRegistration.getRegistrationId(),
                        OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/"
                                + clientRegistration.getRegistrationId(),
                        clientRegistration.getClientName()))
                .collect(Collectors.toList());
        model.addAttribute("registrations", registrations);
        return "authentication/login";
    }

    @GetMapping("authentication/3leggedtoken/callback")
    public String accessToken(Model model, @RequestParam("code") String code) {     
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication.getClass().isAssignableFrom(OAuth2AuthenticationToken.class)) {
            OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
            String clientRegistrationId = oauthToken.getAuthorizedClientRegistrationId();
            OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(clientRegistrationId,
                    oauthToken.getName());
            return client.getAccessToken().getTokenValue();
        }
        return null;
    }

应用程序成功创建了一个到服务器认证页面的链接,并且重定向 URI 在登录后被回调。

回调中返回的代码是正确的

public String accessToken(Model model, @RequestParam("code") String code) {...}

但身份验证不是类型 OAuth2AuthenticationToken

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

但类型 AnonymousAuthenticationToken

org.springframework.security.authentication.AnonymousAuthenticationToken@ef72fdb1:
   Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true;
   Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364:
       RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: D8FFF6F20C14791E505B8B86648F7E1B;
       Granted Authorities: ROLE_ANONYMOUS

我应该如何获取访问令牌?我应该如何访问它以在以下请求中传递它?

提前致谢!

尝试删除@GetMapping("authentication/3leggedtoken/callback")端点并将其注册为 bean。像这样:

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.web.context.annotation.RequestScope;

import sample.api.facebook.Facebook;

@Configuration
public class SocialConfig {

    private final static Logger LOG = LoggerFactory.getLogger(SocialConfig.class);

    @Bean
    @RequestScope
    public Facebook facebook(OAuth2AuthorizedClientService clientService) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String accessToken = null;
        if (authentication.getClass().isAssignableFrom(OAuth2AuthenticationToken.class)) {
            OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
            String clientRegistrationId = oauthToken.getAuthorizedClientRegistrationId();
            if (clientRegistrationId.equals("facebook")) {
                OAuth2AuthorizedClient client =
                    clientService.loadAuthorizedClient(clientRegistrationId, oauthToken.getName());
                accessToken = client.getAccessToken().getTokenValue();

                LOG.error(accessToken);
            }
        }
        return new Facebook(accessToken);
    }

}

然后按照其中一位 Spring oauth2 开发人员的教程进行操作,它帮助我将获取 Facebook 令牌集成到我的项目中。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

自定义您使用OAuth2从Spring Security的身份验证错误

Spring Boot Oauth2扩展DefaultTokenServices

Spring Boot Oauth2 Client(Reactive)相互TLS / SSL令牌uri

使用Spring Security OAuth2验证不同的用户类型

如何使用Spring Boot伪装客户端进行Oauth2身份验证?

Spring Boot + oauth2:访问此资源需要完全身份验证

如何使用Spring Boot + Angular处理外部OAuth2身份验证

使用Spring Security oauth2进行两因素身份验证

在Spring Boot OAuth2授权服务器中使用Active Directory身份验证

IMAP如何使用OAuth或OAuth2身份验证访问Yahoo Mail

使用Spring Security进行gRPC和OAuth2身份验证

Spring Boot 2.0.0 + OAuth2

无法检索oauth2的访问令牌

spring boot oauth2-使用基本身份验证时无法获取访问令牌

具有Oauth2和Spring-boot-starter-parent版本2+的Spring Boot SSO

如何使用Spring在OAuth2身份验证中生成客户端密钥

使用Spring Security OAuth2的刷新令牌为null

使用Spring Boot进行OAuth2身份验证后无法正确重定向

了解Spring Boot的Oauth2入门

使用授权类型“client_credentials”时 OAuth2 身份验证失败

使用 JHipster、Spring Security 和 oauth2 控制身份验证重定向

如何在 Spring Boot 中使用预定义的令牌绕过 Oauth2 身份验证?

Spring Boot 2 + OAuth2:配置令牌的身份验证代码交换

Spring boot、Security、OAuth2:是否可以使用自定义 AuthorizationCodeResourceDetails?身份验证服务器需要重定向 url 中的特定参数

Spring Security 使用什么来生成 OAuth2 令牌?

Javascript WebApp 的 Spring Security Oauth2 身份验证

Oauth2 + Spring Boot 资源给大家

使用 Spring Boot 登录 Facebook OAuth2

无法通过 Spring Boot OAuth2 生成 JWT 令牌