[英]Spring boot - google oauth2, store refresh token in database
我正在嘗試從登錄我的系統的用戶那里獲取刷新令牌,並將其存儲在數據庫中。 因此,我的生態系統中的不同系統可以訪問存儲的刷新令牌,使用它生成訪問令牌,並使用谷歌日歷 api 和用戶憑據。
到目前為止,我已經設法登錄
@Configuration
public class AppConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ClientRegistrationRepository clientRegistrationRepository;
@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeRequests()
.antMatchers("/**").authenticated()
.anyRequest().permitAll()
.and()
.oauth2Login()
.authorizationEndpoint()
.authorizationRequestResolver(new CustomAuthorizationRequestResolver(
this.clientRegistrationRepository))
.and()
.and()
.rememberMe();
}
}
和
public class CustomAuthorizationRequestResolver implements OAuth2AuthorizationRequestResolver {
private final OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver;
public CustomAuthorizationRequestResolver(
ClientRegistrationRepository clientRegistrationRepository) {
this.defaultAuthorizationRequestResolver =
new DefaultOAuth2AuthorizationRequestResolver(
clientRegistrationRepository, "/oauth2/authorization");
}
@Override
public OAuth2AuthorizationRequest resolve(HttpServletRequest request) {
OAuth2AuthorizationRequest authorizationRequest =
this.defaultAuthorizationRequestResolver.resolve(request);
return authorizationRequest != null ?
customAuthorizationRequest(authorizationRequest) :
null;
}
@Override
public OAuth2AuthorizationRequest resolve(
HttpServletRequest request, String clientRegistrationId) {
OAuth2AuthorizationRequest authorizationRequest =
this.defaultAuthorizationRequestResolver.resolve(
request, clientRegistrationId);
return authorizationRequest != null ?
customAuthorizationRequest(authorizationRequest) :
null;
}
private OAuth2AuthorizationRequest customAuthorizationRequest(
OAuth2AuthorizationRequest authorizationRequest) {
Map<String, Object> additionalParameters = new LinkedHashMap<>(authorizationRequest.getAdditionalParameters());
additionalParameters.put("access_type", "offline");
return OAuth2AuthorizationRequest.from(authorizationRequest)
.additionalParameters(additionalParameters)
.build();
}
}
我如何以及在哪里可以訪問已登錄用戶的刷新令牌?
我在這里回答了一個類似的問題,但它在 kotlin 中,所以我會為你添加一個 java 版本。
這是獲取刷新令牌的兩種方法(或者更確切地說是OAuth2AuthorizedClient
,您可以從中獲取刷新令牌)。 您使用哪一種取決於您的需求。
OAuth2AuthorizedClient
注入到端點方法中:@GetMapping("/foo")
void foo(@RegisteredOAuth2AuthorizedClient("google") OAuth2AuthorizedClient user) {
OAuth2RefreshToken refreshToken = user.getRefreshToken();
}
OAuth2AuthorizedClientService
注入托管組件,並使用客戶端注冊 ID 和主體名稱獲取所需的OAuth2AuthorizedClient
實例:@Autowired
private OAuth2AuthorizedClientService clientService;
public void foo() {
OAuth2AuthorizedClient user = clientService.loadAuthorizedClient("google", "principal-name");
OAuth2RefreshToken refreshToken = user.getRefreshToken();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.