Can someone please explain me how to access the protected web api using a web app client?
I am trying something mentioned here in the following link. But I am always getting
The provided access grant is invalid or malformed.
https://msdn.microsoft.com/en-us/library/azure/dn645542.aspx
Here is the code i am using for java
AuthenticationResult result = null;
try {
final Future<AuthenticationResult> resultFuture = context.acquireTokenByAuthorizationCode(
code, new URI(redirectUri), new ClientCredential(clientId, clientSecret), RESOURCE_GRAPH_API, null);
result = resultFuture.get();
} catch (InterruptedException | ExecutionException e) {
LOG.info("Failed to obtain access token: " + e.getMessage());
} catch (URISyntaxException e) {
}
Related
I am implementing "Login with Microsoft button" and I need to store the refresh token in my database so that I can use that to obtain new access tokens in future. I am trying to do this with Java sdk for microsoft graph.
Edit 1: I actually want to create calendar events using my web application. So, the goal is for the web app to access Graph API without having a signed in user present.
This is what the code looks like:
AuthorizationCode authorizationCode = new AuthorizationCode(httpServletRequest.getParameter("code"));
String currentUri = httpServletRequest.getRequestURL().toString();
IAuthenticationResult result;
ConfidentialClientApplication app;
try {
app = createClientApplication();
String authCode = authorizationCode.getValue();
Set<String> scopes = new HashSet<String>();
scopes.add("Calendars.ReadWrite");
AuthorizationCodeParameters parameters = AuthorizationCodeParameters.builder(authCode, new URI(currentUri)).scopes(scopes)
.build();
Future<IAuthenticationResult> future = app.acquireToken(parameters);
result = future.get();
} catch (ExecutionException e) {
throw e.getCause();
}
String accessToken = result.accessToken();
/*
IAuthenticationResult does not contain any method to get the refresh token - how do I get the refresh token??
I want to do something like: result.refreshToken();
*/
IAuthenticationResult is implemented by AuthenticationResult -- but, AuthenticationResult is declared in another class and is not public. AuthenticationResult exposes a method to obtain refreshToken but, I am not able to access it.
Can someone help me access the refresh token?
Thanks!
I got the answer from this link: https://github.com/AzureAD/microsoft-authentication-library-for-java/issues/228
Short Answer: Use reflection
try {
//see com.microsoft.aad.msal4j.AuthenticationResult#refreshToken
final Field refreshTokenField = result.getClass()
.getDeclaredField("refreshToken");
refreshTokenField.setAccessible(true);
return refreshTokenField.get(result).toString();
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
Following their guide in usage here I couldn't get started.
The code:
KucoinClientBuilder builder = new KucoinClientBuilder()
.withApiKeyVersion(2)
.withBaseUrl("https://openapi-sandbox.kucoin.com")
.withApiKey("MyKey", "MySecret", "MyPass");
KucoinRestClient kucoinRestClient = builder.buildRestClient();
KucoinPrivateWSClient kucoinPrivateWSClient;
try {
kucoinPrivateWSClient = builder.buildPrivateWSClient();
KucoinPublicWSClient kucoinPublicWSClient = builder.buildPublicWSClient();
} catch (IOException e) {
e.printStackTrace();
}
builder.buildPrivateWSClient() throws an exception with this message:
KucoinApiException{code='400003', message='KC-API-KEY not exists'}
I copied the Api Key and Secret and pass from the api page
What am I missing here? Why the KC-API-KEY does not exist?
The "sandbox" account is different than the original account.
Its domain is different and you need to register in the sandbox version of the website here
Hi i am using SmartFoxServer with a Java extension. Inside that extension i am trying to get firestore instance. Below is the code i am using to connect to service that is working fine inside IDE (Eclipse). but when i deploy my extension on SmartFoxServer it gives a null pointer exception on firestoreOptions.getService
String jsonPath = "data/************.json";
GoogleCredentials credentials = null;
try {
credentials = GoogleCredentials.fromStream(new FileInputStream(jsonPath))
.createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
} catch (FileNotFoundException e1) {
trace("Exception" + e1.toString());
} catch (IOException e1) {
trace("Exception" + e1.toString());
}
FirestoreOptions firestoreOptions = FirestoreOptions.newBuilder().setCredentials(credentials).build();
Firestore db = firestoreOptions.getService();
this.db = db;
try {
run();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
trace("Exception : " + e);
}
Here is the exception i am getting.
com.google.cloud.firestore.FirestoreException:
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Exception: com.google.cloud.firestore.FirestoreException
Message: java.lang.NullPointerException
Description: Extension initialization failed.
+--- --- ---+
Stack Trace:
+--- --- ---+
com.google.cloud.firestore.FirestoreException.networkException(FirestoreException.java:70)
com.google.cloud.firestore.FirestoreOptions$DefaultFirestoreRpcFactory.create(FirestoreOptions.java:81)
com.google.cloud.firestore.FirestoreOptions$DefaultFirestoreRpcFactory.create(FirestoreOptions.java:71)
com.google.cloud.ServiceOptions.getRpc(ServiceOptions.java:506)
com.google.cloud.firestore.FirestoreOptions.getFirestoreRpc(FirestoreOptions.java:306)
com.google.cloud.firestore.FirestoreImpl.<init>(FirestoreImpl.java:76)
com.google.cloud.firestore.FirestoreOptions$DefaultFirestoreFactory.create(FirestoreOptions.java:62)
com.google.cloud.firestore.FirestoreOptions$DefaultFirestoreFactory.create(FirestoreOptions.java:55)
com.google.cloud.ServiceOptions.getService(ServiceOptions.java:493)
sfs2x.extension.game.quiz.QuizExtension.init(QuizExtension.java:159)
com.smartfoxserver.v2.entities.managers.SFSExtensionManager.createExtension(SFSExtensionManager.java:303)
com.smartfoxserver.v2.entities.managers.SFSZoneManager.createZone(SFSZoneManager.java:426)
i am new to firestore. Don't know if any jar file/library is missing to run this code on server. any help would be appreciated.
GOOGLE_APPLICATION_CREDENTIALS
environment variable must be added with the correct credential's file path and name to run firestore on server.
I'm trying to send messages to single devices using their token from a Java application. I'm using the Firebase Admin SDK. Below is what I have
FileInputStream serviceAccount = null;
try {
serviceAccount = new FileInputStream("google-services.json");
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
FirebaseOptions options = null;
try {
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://MYPROJECTID.firebaseio.com/")
.build();
} catch (IOException e1) {
e1.printStackTrace();
}
FirebaseApp.initializeApp(options);
String registrationToken = "MYDEVICETOKEN";
// See documentation on defining a message payload.
Message message = Message.builder().putData("time", "2:45").setToken(registrationToken)
.build();
// Send a message to the device corresponding to the provided
// registration token.
String response = null;
try {
response = FirebaseMessaging.getInstance().sendAsync(message).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
But I get the following exception
java.io.IOException: Error reading credentials from stream, 'type' field not specified.
What am I doing wrong here?
Click on Generate new private key button.
The error means that your google-services.json file contains invalid data. GoogleCredentials class expects your file to have a type property, but it's not there.
Brief googling gave me this post regarding very similar problem. It says:
From the API Manager, just create select "Create credentials" >
"Service Account key" and generate a new key for the Service
that is associated to your Google Play account.
I have a serious issue regarding the REST API of Mailjet as used with the recommended v3 library.
When I try to UPDATE I am able to do so for the first time without errors, but when I try to do so again, I got NullPointerException. In spite of that, it does update the stat in the Mailjet Server part.
Also the HTTP Response I get is HTTP/1.1 500 Internal Server Error
Code used:
thisUser=cl.createCall(User.Update).identifiedBy(UserProperty.ID, **myUniqueID**).property(UserProperty.USERNAME, propertyValue).execute();
Any thoughts would be more than welcome.
Ok after the comment, here is the function:
#Path("/userUpdate/{propertyName}/{propertyValue}")
#GET
public Response userUpdate(#PathParam("propertyName") String propertyName, #PathParam("propertyValue") String propertyValue) throws ClientProtocolException, IOException{
MailJetApiClient cl=null;
User thisUser=null;
Response resp=null;
StringEntity stringEntity = null;
try {
cl = MailjetUsersRest.createClient();
} catch (MailJetClientConfigurationException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
thisUser=cl.createCall(User.Get).identifiedBy(UserProperty.ID, ___MY_UNIQUE_ID___).execute();
} catch (MailJetApiCallException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String email = thisUser.getEmail();
String lastip = thisUser.getLastIp();
Date lastlogin = thisUser.getLastLoginAt();
String local = thisUser.getLocale();
String timezone = thisUser.getTimezone();
Date warned = thisUser.getWarnedRatelimitAt();
try {
cl = MailjetUsersRest.createClient();
switch(propertyName){
case "Username":
thisUser=cl.createCall(User.Update).identifiedBy(UserProperty.ID, ___MY_UNIQUE_ID___).property(UserProperty.USERNAME, propertyValue).execute();
resp = Response.status(200).entity(thisUser).build();
break;
default:
System.out.println("Invalid propertyName.");
break;
}
} catch (MailJetClientConfigurationException | MailJetApiCallException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resp;
}
First of all, thank you for using Mailjet!
After some testing, I was unable to reproduce your issue. You will find below the code I used.
However I strongly suggest that you open a ticket with our support here.
A working code
Please note that it is unnecessary and considered bad practice to rebuild the client before each call.
// Build a Mailjet client config
MailJetClientConfiguration config;
config = new MailJetClientConfiguration()
.setBaseUrl("https://api.mailjet.com/v3/REST/")
.setDefaultApiKey(System.getenv("MJ_PROD_PUBLIC"))
.setDefaultSecretKey(System.getenv("MJ_PROD_PRIVATE"));
// Build a Mailjet client
MailJetApiClient client = config.buildClient();
// Your code (adapted to my environment, ie no 'Response' object
// and no client factory.)
User thisUser = null;
try
{
// Note that the 'L' in the 'identifiedBy' value fi is necessary
thisUser = client
.createCall(User.Get)
.identifiedBy(UserProperty.ID, /*Our user's ID*/L)
.execute();
}
catch (MailJetApiCallException e2)
{
e2.printStackTrace();
}
String email = thisUser.getEmail();
String lastip = thisUser.getLastIp();
Date lastlogin = thisUser.getLastLoginAt();
String local = thisUser.getLocale();
String timezone = thisUser.getTimezone();
Date warned = thisUser.getWarnedRatelimitAt();
try
{
thisUser = client
.createCall(User.Update)
.identifiedBy(UserProperty.ID, /*Our user's ID*/L)
.property(UserProperty.USERNAME, "DevRel Team Mailjet")
.execute();
}
catch (MailJetApiCallException e)
{
e.printStackTrace();
}
Copy pasting the last bit (the update process) so that the update call is executed twice (without the same new username, of course) doesn't throw any error and certainly not a NullPointerException or a 500 HTTP error code.
And the username is changed accordingly.
So yeah, as written above, please contact our support here. This will allow us to better help you.
If this answer satisfies you, don't forget to accept & upvote it so that others going through similar issues can know this helped :-)