Using OAuth with SforceServiceLocator - soap

I'm looking at some code which is using the Salesforce SOAP API to create a session and access data:
SoapBindingStub binding = (SoapBindingStub) new SforceServiceLocator().getSoap();
String username;
String password;
[...]
LoginResult result = binding.login(username, password);
binding._setProperty(SoapBindingStub.ENDPOINT_ADDRESS_PROPERTY,result.getServerUrl());
SessionHeader sh = new SessionHeader();
sh.setSessionId(result.getSessionId());
binding.setHeader(new SforceServiceLocator().getServiceName().getNamespaceURI(), "SessionHeader", sh);
Given that I've got an OAuth access token and endpoint, is there a way to adapt this to work correctly without a username/password?

After a lot of trial and error -- the answer appears to be the following
Use the OAuth Access token as the sessionID
The ENDPOINT_ADDRESS_PROPERTY is the Endpoint URL and a SOAP API URL, eg: https://na15.salesforce.com/services/Soap/u/21.0

Related

Generate access token using JWT

I've been given access to an okta token endpoint. I would like to use this service to request a token. I was given a url, client id, client secret, scope and grant type. I can use postman to make a POST call to the url (/v1/token) and pass the above info (client id, client secret, scope and grant type) and I get an access token back.
I can easily make this call in java with RestTemplate or equivalent, but I would like to use an API that would manage the token for me.
I've found JJWT. All the examples I see out there show me how to create a JWT using JJWT. What I would like to do is to get my access token, but I'm not sure how to do that. I mean i get that JJWT is an API to create JWT, but then how can I use the JWT to get my access token?
Any help/clarification/direction is much appreciated.
We using JWT with the node.js, to create new Token jwt.sign(data, key) takes at least to an argument, the fist must be some credential like userId, email..., the second will be key to verify later. to verify the token is it valid we use jwt.verify(), the first argument is token (where the jwt.sing() give you) and the second is the key (where you provide when creating);
example:
Creating JWT token:
var jwt = require('jsonwebtoken');
cosnt token = jwt.sign({ email: 'test#test.com', userId: '993333' }, 'secretkey');
verifying Token:
try {
const decodedToken = jwt.verify(token, 'secretkey');
}
catch(err) {
throw new Error(err)
}
// once verified
conosole.log(decodedToken)
I found this post how to create and verify token using java, thanks!

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.

Get access token on Microsoft federated accounts

I'm trying to get access token for Power BI API. Our account is a federated account.
I've been trying this but it keeps giving me an error saying Incorrect username or password. To use the resource owner password credentials grant flow to get the access token for Azure AD, I make a call to http request diectly using the HttpClient
HttpClient clie = new HttpClient();
string tokenEndpoint = "https://login.microsoftonline.com/{tenant}/oauth2/token";
var body = "resource=https://analysis.windows.net/powerbi/api&client_id={client_id}&grant_type=password&username={username}&password={password}";
var stringContent = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");
string result = clie.PostAsync(tokenEndpoint, stringContent).ContinueWith((response) =>
{
return response.Result.Content.ReadAsStringAsync().Result;
}).Result;
This will work for non federated accounts. How can I implement the same for federated accounts?
The easier would be to leverage MSAL.NET (or ADAL.NET) which does a lot to achieve that. See https://aka.ms/msal-net-up
scopes = new string[]{ "https://analysis.windows.net/powerbi/api/Dashboard.Read.All"}
result = await app.AcquireTokenByUsernamePasswordAsync(scopes, "joe#contoso.com",
securePassword);
Even better if you know that your machine is domain joined or AAD joined, you can use Integrated Windows Authentication: https://aka.ms/msal-net-iwa
result = await app.AcquireTokenByIntegratedWindowsAuthAsync(scopes);
Note that, I recommend using MSAL.NET (instead of ADAM.NET), because with MSAL/NET/the Azure AD v2.0 endpoint, PowerBI offers a better control of the permission scopes:
See the API permissions tab in an app registration in https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview

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.

"invalid signature" JWT Token Opentok

I am trying to use the Opentok REST API with JWT to generate a video session token. I am using the following credentials to create the JWT following the JSONWebToken documentation at https://github.com/kylef/JSONWebToken.swift.
I have used the generated token for authorisation and followed the documentation at https://tokbox.com/developer/rest/#authentication and called the api from postman, but I am getting Invalid Signature error message. Where am i wrong?
var claims = ClaimSet()
claims["iss"] = "3*****2"
claims["ist"] = "account"
claims["iat"] = (Calendar.current.date(byAdding: .minute, value: 330, to: Date())?.timeIntervalSince1970)!
claims["exp"] = (Calendar.current.date(byAdding: .minute, value: 334, to: Date())?.timeIntervalSince1970)!
claims["jti"] = "\(NSUUID.init())"
claims["aud"] = "www.example.com"
let jToken = JWT.encode(claims: claims, algorithm: .hs256("334******************************d5af".data(using: .utf8)!))
print(jToken)
Hi Ram you are calling the session/create rest api. This api requires a project level authentication, however from you claims it looks like you are trying to generate a account level token.
The iss should be your API Key/ Project Id and the ist should be the string project.
Let me know if this helps and works.
I'm sure you figured your issue out by now but the archive mode and p2p.preference are not supposed to be header attributes but part of the body as json
At the Value field of "X-OPENTOK-AUTH" you first have to Write: "Bearer " + token.
If it doesn't work try changing "X-OPENTOK-AUTH" with "Authorization".