Need example showing OAUTH2 connection to Microsoft Exchange in JavaMail - rest

I am trying to write a basic program in Java, using JavaMail, to send an email using Microsoft's new OAUTH2 mechanism.
On StackOverflow, I found the following code via a link, but it does not authenticate given a current access token:
public static void main(String[] args) throws IOException, MessagingException
{
Properties props = new Properties();
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imap.auth.mechanisms", "XOAUTH2");
Session session = Session.getInstance(props);
Store store = session.getStore("imap");
String userEmail = "email_account_here";
String accessToken = access_token_here"
store.connect("imap-mail.outlook.com",993,userEmail, accessToken);
session.setDebug(true);
}
I am generating the token using a call to the Microsoft Graph API (not using JavaMail).
Result is "Authentication Failed".
I have searched but cannot find an example that works.
Would appreciate any code samples that work. :)
Thanks!

Related

Websphere Commerce Custom REST service for Login using social sign in not generating valid WC Tokens and CTXMGMT table not getting updated

In the current website, social login is implemented using the mapping in struts and it will call the custom controller command "XYZThirdPartyLoginCmdImpl" which will authenticate the details passed and it will call the out of the box "LogonCmd" for login.
For creating a REST service for the above functinality, created a custom REST handler " XYZThirdPartyLoginHandler" and from there called the existing command "XYZThirdPartyLoginCmdImpl" using the method executeControllerCommandWithContext. Once the response is generated, WCToken and WCTrustedToken is generated by the below code.
ActivityToken token = getActivityToken();
String identitySignature = token.getSignature();
String identityId = token.getActivityGUID().getGUID().toString();
Map<String, Object> identityTokenInfo = new HashMap();
identityTokenInfo.put(MemberFacadeConstants.EC_USERID, new String[] { userId.toString() } );
identityTokenInfo.put(MemberFacadeConstants.ACTIVITY_TOKEN_ID, new String[] { identityId } );
identityTokenInfo.put(MemberFacadeConstants.ACTIVITY_TOKEN_SIGNATURE, new String[] { identitySignature } );
Map<String, String> commerceTokens = CommerceTokenHelper.generateCommerceTokens(identityTokenInfo);
String wcToken = commerceTokens.get(CommerceTokenHelper.WC_TOKEN);
String wcTrustedToken = commerceTokens.get(CommerceTokenHelper.WC_TRUSTED_TOKEN);
The tokens generated using this is not valid. If we try to invoke any other rest service using this token it shows invalid user session error. "XYZThirdPartyLoginCmdImpl" authentication is success as the userId returned is correct. After executing this the user context is not getting created in CTXMGMT table.
Please guide on how to generate the valid tokens in REST flow in this use case.
If you are on v9, you might want to investigate the oauth_validate REST call (/wcs/resources/store//loginidentity/oauth_validate). See the KC article for more information: [https://www.ibm.com/support/knowledgecenter/SSZLC2_9.0.0/com.ibm.commerce.integration.doc/tasks/tcv_sociallogin.htm][1]. This calls some different commands (OAuthTokenValidationCmdImpl and OpenUserRegisterCmd) than what you might be using, but it allows you to pass in a 3rd party token, and it generates the right tokens.

Servicenow Rest API call to check if credentials are valid

I am calling ServiceNow Rest API for tables in my application. I allow the user to enter their servicenow instance credentials and domain url in my application.
I want to know if there is a Simple API call which I can make to ensure that the credentials entered are valid.
Currently I am making a call to get sys_user table and making the check.
This call seems to take more time. Is there a simpler REST URL which I can use here?
public static HttpConnectionResponse checkConnection(String host, String username, String password) {
String CHECK_URL = "/api/now/table/sys_user";
HttpConnectionResponse response = new HttpConnectionResponse();
String completeUrl = "https://"+host+CHECK_URL;
HashMap<String, String> requestHeaders = ConnectionUtils.getDefaultInputHeader();
Credential credential = ConnectionUtils.populateCredentials(username, password);
try{
response = HttpConnectorClient.getMethod(completeUrl, requestHeaders, credential);
}
catch(Exception e){
e.printStackTrace();
}
return response;
}
Why not just use any table or record that you've set to be accessible to any authenticated user, then make a REST API call with their credentials as the basic authentication credentials, to that resource? If you get the record rather than "access denied", the creds are valid. :-)
You could even make a simple UI page, or better yet, a Processor, just for that purpose.

Indico API Wrapper For Java Returning Key Not Found

I'm attempting to use indico's sentiment analysis api, I've debugged and inspected the "indico" object, and confirmed the correct api key is stored within it. I am also able to make calls to the API using curl from terminal, so I don't believe its my network settings (unless its something java specific?).
The code:
public double querySentiment(String qsent) throws UnsupportedOperationException, IOException, IndicoException{
double response = 0;
indico = new Indico(apikey);
IndicoResult single = indico.sentiment.predict(qsent);
log.inf("QUERY SEND SUCCESSFUL");
response = single.getSentiment();
log.inf("QUERY RECEIVE SUCCESSFUL");
return response;
}
The exception:
java.lang.IllegalArgumentException: API key not found. To use our API, sign up for a free account and api key at http://indico.io/register.
Wrong code snippet is given on indico API site. You have to pass key in params as well while making an indico object. Below code will work.
HashMap<String,String> params = new HashMap<String,String>();
params.add("api_key",apikey);
indico = new Indico(apikey,params);

rest api unauthorized Azure Data Catalog

I am using Azure Data Catalog of my organization. I am not creator/administrator/owner of the Catalog but I have access to register/delete catalogs from the web interface.
I want to use rest API for Azure Data Catalog. Is it possible with my level of permission?
I have followed all the steps from https://msdn.microsoft.com/en-us/library/mt428033.aspx and written the following piece of code:
class Program
{
static void Main(string[] args)
{
string url = "https://api.azuredatacatalog.com/catalogs/DefaultCatalog/search/search?searchTerms=My_Server&count=10&startPage=1&api-version=2016-03-30";
HttpWebRequest request = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
Console.WriteLine(AccessToken().CreateAuthorizationHeader());
try
{
WebResponse response = request.GetResponse();
Console.WriteLine(response.ContentLength);
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadKey();
}
static AuthenticationResult AccessToken()
{
string resourceUri = "https://datacatalog.azure.com";
string clientId = "my-client-id";
string redirectUri = "my-redirect-uri";
string authorityUri = "https://login.windows.net/common/oauth2/authorize";
AuthenticationContext authContext = new AuthenticationContext(authorityUri);
return authContext.AcquireToken(resourceUri, clientId, new Uri(redirectUri), PromptBehavior.RefreshSession);
}
}
and when I try to run the search from API, I get the following error:
System.Net.WebException: The remote server returned an error: (401)
Unauthorized. at System.Net.HttpWebRequest.GetResponse() at
HRBIADCAPI.Program.Main(String[] args) in
c:\users\naghimir\documents\visual studio
2015\Projects\HRBIADCAPI\HRBIADCAPI\Program.cs:line 32
Now I think the problem is that I have not given access to the client program created to read/write data catalog (that I did in Azure Data Factory) but that step is not there in the documentation either.
Do I need to be the owner or can I request permission from the owner to use Azure Data Catalog API?
Based on the description, you were using the OAuth 2.0 code grant flow to grant the app to delegate the user to manipulate the Azure Data Catalog.
To ensure the request works well, we need to grant the scope to the app like figure below:
And since the app only delegate the users’ permission, please ensure that user have the sufficient permission to operate the resource manfully.

Intuit - first connection

I have a question about Intuit API. I want to connect for the first time with this API. I'm using .NET SDK. I'm going througt this tutorial: http://goo.gl/PzIzoa . I don't know what i have to pass in arguments issuerId and subject (Step 1.b). I left them empty for the first try and I'm catching InvalidTokenException.
What arguments I have to pass to make it work?
Edit:
Thanks for your help, now I'm connecting via your web app.
Now I want to connect using my application. I wrote this code:
string certificateFile = "C:\\OpenSSL-Win32\\bin\\testapp1.crt";
string password = "xxx";
X509Certificate2 certificate = new X509Certificate2(certificateFile, password);
string consumerKey = "xxx";
string consumerSecret = "xxx";
string issuerId = "";
string subject = "";
SamlRequestValidator val = new SamlRequestValidator(certificate, consumerKey, consumerSecret, issuerId, subject);
After calling SamlRequestValidator constructor I'm catching InvalidTokenException. What am I doing wrong? What I have to do to make it work?
Please take a look at the following link.
https://developer.intuit.com/docs/0020_customeraccountdata/007_firstrequest
You can use apiexplorer tool to test these API calls without using devkit.
(It will ensure that your OAuth keys are working fine)
https://developer.intuit.com/apiexplorer?apiname=CustomerAccountData
You can refer the following .Net sample app as well.
https://developer.intuit.com/docs/0020_customeraccountdata/devkits/285.net_sample_app_for_cad_services
Let me know if you get any issue related to this process.
Thanks