Клиентскую библиотеку Google OAuth2 можно использовать для аутентификации на любом провайдере OAuth2, добавив следующие два класса:
public class ClientUsernamePasswordTokenRequest extends TokenRequest {
/**
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @param tokenServerUrl token server URL
* @param grantType grant type ({@code "authorization_code"}, {@code "password"},
* {@code "client_credentials"}, {@code "refresh_token"} or absolute URI of the extension
*/
public ClientUsernamePasswordTokenRequest(HttpTransport transport, JsonFactory jsonFactory, GenericUrl tokenServerUrl, String grantType) {
super(transport, jsonFactory, tokenServerUrl, grantType);
}
@Override
public TokenResponse execute() throws IOException {
return convertStringToObject(executeUnparsed().parseAs(Map.class));
}
private TokenResponse convertStringToObject(Map content) {
TokenResponse tokenResponse = new TokenResponse();
String tokenType = (String) content.get("token_type");
tokenResponse.setTokenType(tokenType);
String scope = (String) content.get("scope");
tokenResponse.setScope(scope);
String accessToken = (String) content.get("access_token");
tokenResponse.setAccessToken(accessToken);
String refreshToken = (String) content.get("refresh_token");
tokenResponse.setRefreshToken(refreshToken);
return tokenResponse;
}
}
и
package com.identityforge.idfserver.backend.rest.auth;
import com.google.api.client.http.HttpExecuteInterceptor;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.UrlEncodedContent;
import com.google.api.client.util.Data;
import com.google.api.client.util.Preconditions;
import java.util.Map;
public class ClientParametersAuthentication implements HttpRequestInitializer, HttpExecuteInterceptor {
/**
* Client identifier issued to the client during the registration process.
*/
private final String clientId;
/**
* Client password or {@code null} for none.
*/
private final String password;
/**
* Client username
*/
private final String username;
/**
* Resource for which access is requested
*/
private final String resource;
private final String clientSecret;
/**
* @param clientId client identifier issued to the client during the registration process
* @param password password or {@code null} for none
* @param username
* @param resource
* @param clientSecret
*/
public ClientParametersAuthentication(String clientId, String password, String username, String resource, String clientSecret) {
this.clientId = Preconditions.checkNotNull(clientId);
this.password = Preconditions.checkNotNull(password);
this.username = Preconditions.checkNotNull(username);
this.resource = resource;
this.clientSecret = clientSecret;
}
public void initialize(HttpRequest request) {
request.setInterceptor(this);
}
public void intercept(HttpRequest request) {
Map<String, Object> data = Data.mapOf(UrlEncodedContent.getContent(request).getData());
data.put("client_id", clientId);
data.put("password", password);
data.put("username", username);
if (resource != null)
data.put("resource", resource);
if (clientSecret != null) {
data.put("client_secret", clientSecret);
}
}
}
Теперь токен доступа можно запросить, указав значения учетных данных в следующем коде
private void fetchToken() throws IOException {
TokenResponse tokenResponse;
if (genericUrl == null) {
genericUrl = new GenericUrl(tokenUrl);
}
if (authentication == null) {
authentication = new ClientParametersAuthentication(clientId, passwd, username, resource, clientSecret);
}
if (tokenRequest == null) {
tokenRequest = new ClientUsernamePasswordTokenRequest(new ApacheHttpTransport(), JacksonFactory.getDefaultInstance(), genericUrl, grantType);
tokenRequest.setClientAuthentication(authentication);
}
tokenResponse = tokenRequest.execute();
String accessToken = tokenResponse.getAccessToken();
}
Здесь tokenUrl
- конечная точка аутентификации.