use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project dishevelled by heuermh.
the class GoogleGenomicsFactory method createGenomics.
Genomics createGenomics(final GenomicsKey genomicsKey) throws IOException {
final String rootUrl = genomicsKey.rootUrl();
final String authorizationCode = genomicsKey.authorizationCode();
final GoogleAuthorizationCodeFlow googleAuthorizationCodeFlow = genomicsKey.googleAuthorizationCodeFlow();
if (logger.isInfoEnabled()) {
logger.info("creating new google genomics api for root url {} authorization code {}", rootUrl, abbrev(authorizationCode));
}
TokenResponse tokenResponse = googleAuthorizationCodeFlow.newTokenRequest(authorizationCode).setRedirectUri(REDIRECT_URI).execute();
if (logger.isInfoEnabled()) {
logger.info("received token response {}", abbrev(tokenResponse.getAccessToken()));
}
final Credential credential = googleAuthorizationCodeFlow.createAndStoreCredential(tokenResponse, "user");
if (logger.isInfoEnabled()) {
logger.info("received credential {} expires in {} s", abbrev(credential.getAccessToken()), credential.getExpiresInSeconds());
}
Genomics genomics = new Genomics.Builder(httpTransport, jsonFactory, credential).setApplicationName(APPLICATION_NAME).setRootUrl(rootUrl).setServicePath("/").setHttpRequestInitializer(new HttpRequestInitializer() {
@Override
public void initialize(final HttpRequest httpRequest) throws IOException {
credential.initialize(httpRequest);
// 60 seconds
httpRequest.setReadTimeout(60000);
}
}).build();
if (logger.isInfoEnabled()) {
logger.info("created new google genomics api for root URL {} authorization code {} application name {}", rootUrl, abbrev(authorizationCode), genomics.getApplicationName() == null ? "null" : genomics.getApplicationName());
}
return genomics;
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project hub-alert by blackducksoftware.
the class AzureBoardsProperties method requestTokens.
public Optional<Credential> requestTokens(AuthorizationCodeFlow authorizationCodeFlow, String authorizationCode) throws IOException {
AuthorizationCodeTokenRequest tokenRequest = authorizationCodeFlow.newTokenRequest(authorizationCode);
TokenResponse tokenResponse = tokenRequest.execute();
Credential credential = authorizationCodeFlow.createAndStoreCredential(tokenResponse, oauthUserId);
return Optional.ofNullable(credential);
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project isaac-api by isaacphysics.
the class FacebookAuthenticator method exchangeCode.
@Override
public String exchangeCode(final String authorizationCode) throws CodeExchangeException {
try {
AuthorizationCodeTokenRequest request = new AuthorizationCodeTokenRequest(httpTransport, jsonFactory, new GenericUrl(TOKEN_EXCHANGE_URL), authorizationCode);
request.setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret));
request.setRedirectUri(callbackUri);
TokenResponse response = request.execute();
String accessToken;
Long expires;
if (response.get("error") != null) {
throw new CodeExchangeException("Server responded with the following error" + response.get("error") + " given the request" + request.toString());
}
if (response.getAccessToken() != null && response.getExpiresInSeconds() != null) {
accessToken = response.getAccessToken();
expires = response.getExpiresInSeconds();
} else {
throw new IOException("access_token or expires_in values were not found");
}
TokenResponse tokenResponse = new TokenResponse();
tokenResponse.setAccessToken(accessToken);
tokenResponse.setExpiresInSeconds(expires);
// I don't really want to use the flow storage but it seems to be
// easier to get credentials this way.
Builder builder = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), httpTransport, jsonFactory, new GenericUrl(TOKEN_EXCHANGE_URL), new ClientParametersAuthentication(clientId, clientSecret), clientId, AUTH_URL);
builder.setScopes(requestedScopes);
AuthorizationCodeFlow flow = builder.setDataStoreFactory(MemoryDataStoreFactory.getDefaultInstance()).build();
Credential credential = flow.createAndStoreCredential(tokenResponse, authorizationCode);
String internalReferenceToken = UUID.randomUUID().toString();
credentialStore.put(internalReferenceToken, credential);
flow.getCredentialDataStore().clear();
return internalReferenceToken;
} catch (IOException e) {
String message = "An error occurred during code exchange";
throw new CodeExchangeException(message, e);
}
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project google-oauth-java-client by googleapis.
the class AuthorizationCodeInstalledApp method authorize.
/**
* Authorizes the installed application to access user's protected data.
*
* @param userId user ID or {@code null} if not using a persisted credential store
* @return credential
* @throws IOException
*/
public Credential authorize(String userId) throws IOException {
try {
Credential credential = flow.loadCredential(userId);
if (credential != null && (credential.getRefreshToken() != null || credential.getExpiresInSeconds() == null || credential.getExpiresInSeconds() > 60)) {
return credential;
}
// open in browser
String redirectUri = receiver.getRedirectUri();
AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(redirectUri);
onAuthorization(authorizationUrl);
// receive authorization code and exchange it for an access token
String code = receiver.waitForCode();
TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();
// store credential and return it
return flow.createAndStoreCredential(response, userId);
} finally {
receiver.stop();
}
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project dockstore by dockstore.
the class TokenResource method addOrcidToken.
@POST
@Timed
@UnitOfWork
@Path("/orcid.org")
@JsonView(TokenViews.User.class)
@ApiOperation(value = orcidSummary, authorizations = { @Authorization(value = JWT_SECURITY_DEFINITION_NAME) }, notes = orcidDescription, response = Token.class)
@Operation(operationId = "addOrcidToken", summary = orcidSummary, description = orcidDescription, security = @SecurityRequirement(name = "bearer"))
public Token addOrcidToken(@ApiParam(hidden = true) @Parameter(hidden = true, name = "user") @Auth final User user, @QueryParam("code") final String code) {
String accessToken;
String refreshToken;
String username;
String orcid;
String scope;
long expirationTime;
if (code == null || code.isEmpty()) {
throw new CustomWebApplicationException("Please provide an access code", HttpStatus.SC_BAD_REQUEST);
}
final AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), HTTP_TRANSPORT, JSON_FACTORY, new GenericUrl(orcidUrl + "oauth/token"), new ClientParametersAuthentication(orcidClientID, orcidClientSecret), orcidClientID, orcidUrl + "/authorize").build();
try {
TokenResponse tokenResponse = flow.newTokenRequest(code).setScopes(Collections.singletonList(orcidScope)).setRequestInitializer(request -> request.getHeaders().setAccept(MediaType.APPLICATION_JSON)).execute();
accessToken = tokenResponse.getAccessToken();
refreshToken = tokenResponse.getRefreshToken();
// ORCID API returns the username and orcid id along with the tokens
// get them to store in the token and user tables
username = tokenResponse.get("name").toString();
orcid = tokenResponse.get("orcid").toString();
scope = tokenResponse.getScope();
Instant instant = Instant.now();
instant.plusSeconds(tokenResponse.getExpiresInSeconds());
expirationTime = instant.getEpochSecond();
} catch (IOException e) {
LOG.error("Retrieving accessToken was unsuccessful" + e.getMessage(), e);
throw new CustomWebApplicationException(e.getMessage(), HttpStatus.SC_BAD_REQUEST);
}
if (user != null) {
// save the ORCID to the enduser table
User byId = userDAO.findById(user.getId());
byId.setOrcid(orcid);
Token token = new Token();
token.setTokenSource(TokenType.ORCID_ORG);
token.setContent(accessToken);
token.setRefreshToken(refreshToken);
token.setUserId(user.getId());
token.setUsername(username);
TokenScope tokenScope = TokenScope.getEnumByString(scope);
if (tokenScope == null) {
LOG.error("Could not convert scope string to enum: " + scope);
throw new CustomWebApplicationException("Could not save ORCID token, contact Dockstore team", HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
token.setScope(tokenScope);
token.setExpirationTime(expirationTime);
checkIfAccountHasBeenLinked(token, TokenType.ORCID_ORG);
long create = tokenDAO.create(token);
LOG.info("ORCID token created for {}", user.getUsername());
return tokenDAO.findById(create);
} else {
LOG.info("Could not find user");
throw new CustomWebApplicationException("User not found", HttpStatus.SC_CONFLICT);
}
}
Aggregations