Plaid API get Access Token java android - java

I am a beginner with communicating with APIs and I am currently working with the Plaid API in order to retrieve transaction data for an android application. Currently, I have successfully integrated with the Plaid Link and can obtain public tokens through the app, however I am now having trouble exchanging the public token for the access token. I obtain the public token from here:
private ActivityResultLauncher<LinkTokenConfiguration> linkAccountToPlaid = registerForActivityResult(
new OpenPlaidLink(),
result -> {
if (result instanceof LinkSuccess) {
//Exchange public token for persistent access token
I believe the following code on the server is used to exchange the public token:
app.post('/api/set_access_token', function (request, response, next) {
PUBLIC_TOKEN = request.body.public_token;
Promise.resolve()
.then(async function () {
const tokenResponse = await client.itemPublicTokenExchange({
public_token: PUBLIC_TOKEN,
});
prettyPrintResponse(tokenResponse);
ACCESS_TOKEN = tokenResponse.data.access_token;
ITEM_ID = tokenResponse.data.item_id;
if (PLAID_PRODUCTS.includes('transfer')) {
TRANSFER_ID = await authorizeAndCreateTransfer(ACCESS_TOKEN);
}
response.json({
access_token: ACCESS_TOKEN,
item_id: ITEM_ID,
error: null,
});
})
.catch(next);
});
I have the quickstart server running, my question is, how do I then make the call to the server to exchange the public token for the access token? or in other words, how do I make a post call, containing the public token to the server to receive the access token

Response from the Plaid Android team:
So in our Android quickstart sample on GitHub, we already have a Retrofit API set up to retrieve the link_token.
What you would want to do is to add something like
#POST("/api/get_transactions")
fun getTransactions(publicToken: PublicToken): Single<Transactions>
data class PublicToken(#SerializedName("public_token") publicToken: String)
data class Transactions( #SerializedName("transactions") val transactions: List<Transaction>
)
data class Transaction( #SerializedName("amount") val amount: Float,
#SerializedName("category") val category: String,
)

Related

Can't set up OAuth with Vkontakte via SpringBoot

Need help to implement login via Vkontakte OAuth.
According to spring-boot docs made this:
#Bean
public ClientRegistrationRepository clientRegistrationRepository() {
return new InMemoryClientRegistrationRepository(vkClientRegistration());
}
private ClientRegistration vkClientRegistration() {
return ClientRegistration.withRegistrationId("vk")
.authorizationUri("https://oauth.vk.com/authorize")
.clientId("######")
.clientSecret("######")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("{baseUrl}/login/oauth2/code/{registrationId}")
.scope("friends", "groups")
.tokenUri("https://oauth.vk.com/access_token")
// .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo")
// .userNameAttributeName(IdTokenClaimNames.SUB)
// .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs")
.clientName("Vkontakte")
.build();
}
As a result: context starts, localhost:8080 redirects to authorization page.
But after clicking "Allow" button browser comes back to login page with error:
[invalid_token_response] An error occurred while attempting to
retrieve the OAuth 2.0 Access Token Response: 401 Unauthorized: [no
body]
I used VK API documentation from this:
https://dev.vk.com/api/access-token/authcode-flow-user
What should I correct to complete authorization flow?
Update
Debugging I found the reason of such behavior:
VK service returns access token like this:
{
"access_token":"ed0f46118dec0a5e6935ca198......",
"expires_in":86400,
"user_id":1111111,
"email":"1111222#mail.ru"
}
And it does not have property "token_type". As a result OAuth2AccessToken constructor fails.
public OAuth2AccessToken(TokenType tokenType, String tokenValue, Instant issuedAt, Instant expiresAt,
Set<String> scopes) {
super(tokenValue, issuedAt, expiresAt);
Assert.notNull(tokenType, "tokenType cannot be null");
this.tokenType = tokenType;
this.scopes = Collections.unmodifiableSet((scopes != null) ? scopes : Collections.emptySet());
}
There is a solution which detailed describes configuring flow at the link (in Russian)

How to read email with proper rights in token

I am trying to upgrade an application (it should fetch emails from a mailbox every few minutes) from Microsoft EWS deprecated API to the new Graph API, but I am facing some issues.
This is my class for the connector :
public class O365graphApiConnector {
private final GraphServiceClient<Request> graphClient;
public O365graphApiConnector(String clientId, String username, String password) {
final UsernamePasswordCredential usernamePasswordCredential =
new UsernamePasswordCredentialBuilder()
.clientId(clientId)
.username(username)
.password(password)
.build();
final TokenCredentialAuthProvider tokenCredentialAuthProvider =
new TokenCredentialAuthProvider(usernamePasswordCredential);
graphClient=GraphServiceClient.builder()
.authenticationProvider(tokenCredentialAuthProvider)
.buildClient();
}
public User getUserProfile() {
return graphClient.me().buildRequest().get();
}
public MessageCollectionPage getOutlookEmails() {
return graphClient.me().messages().buildRequest().get();
}
}
I am using com.azure:azure-identity:1.4.2 and com.microsoft.graph:microsoft-graph:5.8.0.
I build the connector, passing the clientId, username and password. I am able to call getUserProfile , and I am getting something, so the authentication "works".
However, I get a 404 when calling getOutlookEmails :
SEVERE: Throwable detail:
com.microsoft.graph.http.GraphServiceException: Error code:
ResourceNotFound Error message: Resource could not be discovered.
GET https://graph.microsoft.com/v1.0/me/messages SdkVersion :
graph-java/v5.8.0
404 : Not Found [...]
When I run this in debug mode and intercept the token, it seems to be OK though : I have a bunch of rights that my admin has given to the applicative account :
"scp": "EWS.AccessAsUser.All Mail.Read Mail.Read.Shared Mail.ReadBasic Mail.ReadWrite
Mail.ReadWrite.Shared Mail.Send Mail.Send.Shared MailboxSettings.ReadWrite User.Read User.Read.All User.ReadWrite profile openid email"
This is part of what we see on the admin side (more rights were added after the screenshot was taken) :
My understanding is that this should be enough to get access to the emails of the given mailbox programmatically, but apparently, it's not.
Any idea of what I am missing ?
actually, the technical "user" I am using didn't really have a mailbox (despite the user name being an email address.. that confused me).
It had been given the permissions on the given mailbox I am interested in though, so the fix is simply to select the mailbox/user before retrieving the messages :
public MessageCollectionPage getOutlookEmailsFor(String mailbox) {
return graphClient.users(mailbox).messages().buildRequest().get();
}

E00007 : User authentication failed due to invalid authentication values. in auth.net

I am new to the Authorized.net API and facing the below E00007, User authentication failed due to invalid authentication values. in authorized.net. I am using the authorize.net version to call the GetTransactionDetails API.
Any idea on what is the issue ? Any help ?
<dependency>
<groupId>net.authorize</groupId>
<artifactId>anet-java-sdk</artifactId>
<version>1.8.6</version>
</dependency>
and I am using the below code
public class GetTransactionDetails {
public static final String apiLoginId= "6LaBc8HJ6Q";
public static final String transactionKey= "XXXXXXXX";
public static void main(String[] args) {
ApiOperationBase.setEnvironment(Environment.SANDBOX);
MerchantAuthenticationType merchantAuthenticationType = new MerchantAuthenticationType() ;
merchantAuthenticationType.setName(apiLoginId);
merchantAuthenticationType.setTransactionKey("transactionKey");
ApiOperationBase.setMerchantAuthentication(merchantAuthenticationType);
//need valid transacaction Id to run
String transId = "60024624183";
GetTransactionDetailsRequest getRequest = new GetTransactionDetailsRequest();
getRequest.setMerchantAuthentication(merchantAuthenticationType);
getRequest.setTransId(transId);
GetTransactionDetailsController controller = new GetTransactionDetailsController(getRequest);
controller.execute();
GetTransactionDetailsResponse getResponse = controller.getApiResponse();
TransactionDetailsType transactionDetailsType = getResponse.getTransaction();
if (getResponse!=null) {
if (getResponse.getMessages().getResultCode() == MessageTypeEnum.OK) {
System.out.println(getResponse.getMessages().getMessage().get(0).getCode());
System.out.println(getResponse.getMessages().getMessage().get(0).getText());
System.out.println("---------------------------------------");
System.out.println("Auth Amount : "+transactionDetailsType.getAuthAmount());
System.out.println("Auth Code : "+transactionDetailsType.getAuthCode());
System.out.println("Response Reason Description : "+transactionDetailsType.getResponseReasonDescription());
System.out.println("Transaction Status : "+transactionDetailsType.getTransactionStatus());
System.out.println("Submit Date : "+transactionDetailsType.getSubmitTimeLocal());
}else{
System.out.println("Failed to get transaction details: " + getResponse.getMessages().getResultCode());
List<Message> messages = getResponse.getMessages().getMessage();
for (Message message : messages) {
System.out.println("Code : "+message.getCode());
System.out.println("Text : "+message.getText());
}
}
}
}
}
output:
06/02/17 00:35:48,733: INFO [pool-1-thread-1] (net.authorize.util.LogHelper:24) - Use Proxy: 'false'
Failed to get transaction details: ERROR
Code : E00007
Text : User authentication failed due to invalid authentication values.
Can you try removing the quotes from setTransactionKey
merchantAuthenticationType.setTransactionKey("transactionKey");
change to
merchantAuthenticationType.setTransactionKey(transactionKey);
There are multiple causes of this error, which may include:
Using the wrong API Login ID (the "name" field in some of the API calls)
Using the wrong Transaction Key
Using the wrong API endpoint. Authorize.net has two API endpoints, one for sandbox and one for production:
Sandbox API Endpoint: https://apitest.authorize.net/xml/v1/request.api
Production API Endpoint: https://api.authorize.net/xml/v1/request.api
To test your Authorize.net authentication credentials, go to [Authorize.net's API documentation site] and choose API Endpoints and Authentication, then the test your authentication credentials box.1

How to identify and verifying tokenId from google API?

I can't find any solution for as i think very general issue...
I use google API for LogIn, and according to this article i can get tokenId using this method
private String getTokenId(GoogleSignInResult result) {
String tokenId = null;
GoogleSignInAccount googleSignInAccount = result.getSignInAccount();
if (googleSignInAccount != null) {
tokenId = googleSignInAccount.getIdToken();
}
return tokenId;
}
it is standard method, but why this method retern back token id which the contains 857 char of String? And i can't verify it with standard link
https://www.googleapis.com/oauth2/v3/tokeninfo?access_token= <857 char>;
and i get back this response
{
"error_description": "Invalid Value"
}
I am sure if google provide method to get token id there is have to be a method to verify it...
What am i doing wrong?

Spring FacebookTemplate raises permission exception for user profile

I'm having trouble continuing an OAuth session using a token obtained on an iOS client from a back-service. Specifically it looks to be a permission problem:
iOS Client Obtains Access Token (ObjC / FB iOS SDK v3.24)
Session established with the following permissions:
[FBSession openActiveSessionWithReadPermissions:#[
#"email",
#"user_about_me",
#"user_friends",
#"user_birthday",
#"public_profile" . . .
On completion . . .
FBSession *session = [FBSession activeSession];
NSString *accessToken = [session.accessTokenData accessToken];
Access Token Sent to Backend (which is Spring Boot + Kotlin)
A Spring FacebookTemplate is instantiated using the token obtained above, as follows:
#Test fun testFacebookTemplate()
{
val facebook = FacebookTemplate("$$TOKEN_FROM_FACEBOOK_IOS_SDK$$")
//Raises exception . .
val profile = facebook.userOperations().userProfile
println("Profile: " + profile)
}
The OAuth session established on the iOS client is continued from the backend successfully, and eg, a Facebook friend list can be returned. However, attempting to retrieve the profile, as shown above raises an error:
Error from Facebook: {"error":{"message":"(#3) Application does not have the capability to make this API call." , "type":"OAuthException","code":3,"fbtrace_id":"B4C+eS3n2PW"}}
DEBUG o.s.s.f.a.impl.FacebookErrorHandler - Facebook error:
DEBUG o.s.s.f.a.impl.FacebookErrorHandler - CODE : 3
DEBUG o.s.s.f.a.impl.FacebookErrorHandler - TYPE : OAuthException
Question:
Which permission is missing to return the User object. This does not appear to be documented in Spring's FacebookTemplate
Is this requested during OAuth authentication/authorization ( in my case with the FB iOS SDK) or via the developer console? This is unclear to me because both the openActiveSessionWithPermissions and the definition of the application in Facebook's web console contain references to these permissions.
It appears as though Spring's FacebookTemplate v2.0.2.RELEASE has some permission related error when invoking the request for user profile against the Facebook Graph API v2.3
As a work-around use:
val profile = facebook.fetchObject("me", User::class.java,
"id", "first_name", "last_name", "email");
After facebook API change, field "first_name" was replaced by field : "name"
public FacebookUser getFacebookUserData() {
Facebook facebook = new FacebookTemplate(accessToken);
String[] fields = {"id", "name", "email"};
FacebookUser user = facebook.fetchObject("me", FacebookUser.class, fields);
return user;
}
where FacebookUser is :
public class FacebookUser {
String id;
String name;
String email;
public FacebookUser(){ }
public FacebookUser(String id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}

Categories

Resources