[英]Spring Security + Google OAuth2 Login: access token is null?
[英]How to get access token just after login in successHandler in spring oauth2 security?
目前,我正在開發一個項目,其中需要在登錄后立即在 spring 成功處理程序中收集accessToken 。 我閱讀了不同的博客,但找不到任何可能的解決方案。 在這里,我提供了我嘗試過的代碼片段,
這是我嘗試獲取 accessToken 的成功處理程序。 但是當我嘗試將authentication.getDetails() 轉換為OAuth2AuthenticationDetails 時,我遇到了異常。
@Component
public class AuthSuccessListener implements ApplicationListener<AuthenticationSuccessEvent> {
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();
System.out.println(userDetails);
System.out.println("pass is " + userDetails.getPassword());
System.out.println("username is " + userDetails.getUsername());
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//Authentication authentication = event.getAuthentication();
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
String accessToken = details.getTokenValue();
System.out.println(accessToken);
}
}
我不知道這種方法是否有效。 如果在successHandler或其他地方登錄后還有其他方法可以獲取accessToken,請幫助解決此問題。
至少我找到了一個解決方案,可以在登錄后立即在 succeshandler 處獲取令牌。 由於我沒有簡而言之相關的解決方案,這就是我發布此答案的原因。 我這樣解決了這個問題。
@Component
public class AuthSuccessListener implements ApplicationListener<AuthenticationSuccessEvent> {
private final TokenStore tokenStore;
public AuthSuccessListener(TokenStore tokenStore) {
this.tokenStore = tokenStore;
}
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();
String accessToken = null;
List<OAuth2AccessToken> tokens = (List<OAuth2AccessToken>) tokenStore.findTokensByClientIdAndUserName("your Client Id", userDetails.getUsername());
if (tokens.size() > 0) {
accessToken = tokens.get(0).getValue();
}
}
}
在這里你可以看到我使用TokenStore通過使用clientId和username方法來獲取令牌tokenStore.findTokensByClientIdAndUserName("your Client Id", userDetails.getUsername());
就是這樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.