I would like to know how to retrieve the access token on a Spring Boot 3-legged authentication using the functionalities provided by org.springframework.boot:spring-boot-starter-oauth2-client
I am able to get the access token using regular RestTemplate
calls.
I tried to get the same access token using the spring-boot-starter-oauth2-client
functionalities by following the example in https://github.com/wonwoo/spring-boot-oauth2-login.
I am able to retrieve the code provided by the server, but I cannot figure out how to get the access token.
My code looks like this:
Properties in 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 template in login.html
:
<div th:each="registration: ${registrations}">
<a th:href="@{${registration.uri}}">
Sign in with [[${registration.clientName}]]
</a>
</div>
Configuration in 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();
}
}
Controllers in 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;
}
The application successfully creates a link to the server's authentication page and the redirect URI is called back after login.
The code returned in the callback is correct
public String accessToken(Model model, @RequestParam("code") String code) {...}
but the Authentication is not of type OAuth2AuthenticationToken
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
but of type 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
How should I acquire the access token? and how should I access it to pass it on the following requests?
Thanks in advance!
Try to remove @GetMapping("authentication/3leggedtoken/callback")
endpoint and register it as a bean. Like this:
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);
}
}
Then follow this tutorial from one of Spring oauth2 developers, it helped me to integrate getting Facebook token in my project.