gpt4 book ai didi

spring-boot - 使用 spring-boot-starter-oauth2-client 检索 OAuth2 3 足身份验证的访问 token

转载 作者:行者123 更新时间:2023-12-02 03:14:37 24 4
gpt4 key购买 nike

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

我可以使用常规 RestTemplate 获取访问 token 来电。

我尝试使用 spring-boot-starter-oauth2-client 获取相同的访问 token 按照https://github.com/wonwoo/spring-boot-oauth2-login中的示例操作.

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

我的代码如下所示:

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 :

@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

我应该如何获取访问 token ?我应该如何访问它以将其传递给以下请求?

提前致谢!

最佳答案

尝试删除@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);
}

}

然后按照本教程 from one of Spring oauth2 developers 进行操作,它帮助我将获取 Facebook token 集成到我的项目中。

关于spring-boot - 使用 spring-boot-starter-oauth2-client 检索 OAuth2 3 足身份验证的访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56533989/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com