How to create bulkconnection with accesstoken in salesforce - java

I need to create BulkConnection for bulk API into salesforce.
We can able to create BulkConnection using ConnectorConfig with basic SOAP authentication.
Code is below,
ConnectorConfig config = new ConnectorConfig();
config.setUsername("USERNAME");
config.setPassword("PASSWORD+TOKEN");
config.setCompression(true);
config.setTraceFile("traceLogs.txt");
config.setTraceMessage(true);
config.setPrettyPrintXml(true);
config.setAuthEndpoint("https://login.salesforce.com/services/Soap/u/39.0");
PartnerConnection connection = new PartnerConnection(config);
String soapEndpoint = config.getServiceEndpoint();
String apiVersion = "39.0";
String restEndpoint = soapEndpoint.substring(0, soapEndpoint.indexOf("Soap/")) + "async/" + apiVersion;
config.setRestEndpoint(restEndpoint);
bulkConnection = new BulkConnection(config);
Above code is working fine.
But in my case, I can't able to collect username & password for each of the customer's salesforce account.
Is this possible to create BulkConnection using accestoken?..
Please give me your suggestion.
Thanks,
Harish

Related

Error code AADSTS70000121 when using One Drive through Microsoft Graph in Java

I have a Java application that integrates with One Drive through Microsoft Graph. I followed the documentation and I am able to pass the authorisation step but when interrogating the API I get this error:
"AADSTS70000121: The passed grant is from a personal Microsoft account and is required to be sent to the /consumers or /common endpoint."
What am I missing?
This is the code I am using:
Get an authorisation token using the URL bellow
private static final String RESPONSE_TYPE = "code";
private static final String SCOPE = "openid%20Files.Read%20Files.ReadWrite%20Contacts.Read%20offline_access";
String authorizeUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=" + CLIENT_ID
+ "&scope=" + SCOPE + "&response_type=" + RESPONSE_TYPE + "&redirect_uri=" + REDIRECT_URL;
Exchange the received authorization token
List<String> scopes = new LinkedList<String>();
scopes.add("https://graph.microsoft.com/.default");
AuthorizationCodeCredential authCodeCredential = new AuthorizationCodeCredentialBuilder()
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.authorizationCode(authorizationCode)
.redirectUrl(REDIRECT_URL)
.build();
TokenCredentialAuthProvider tokenCredAuthProvider = new TokenCredentialAuthProvider(scopes, authCodeCredential);
GraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider(tokenCredAuthProvider).buildClient();
User me = graphClient.me()
.buildRequest()
.get();
As you are using the personal account then please change the endpoint to consumers instead of common,
https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize?
ref doc - https://learn.microsoft.com/en-au/azure/active-directory/develop/v2-oauth2-auth-code-flow
Hope this helps
Thanks

Getting a Security Token for Azure Pack in Java Using Apache CXF

I am trying to write code in Java that can obtain a Security Token from the STS for Azure Pack, which I can then use to authenticate calls to the Azure Pack APIs. Here is example code that Microsoft provides (which works) for obtaining this token in C#:
string windowsAuthSiteEndPoint = EnvironmentToUse + ":30072";
var identityProviderEndpoint = new EndpointAddress(new Uri(windowsAuthSiteEndPoint + "/wstrust/issue/windowstransport"));
var identityProviderBinding = new WS2007HttpBinding(SecurityMode.Transport);
identityProviderBinding.Security.Message.EstablishSecurityContext = false;
identityProviderBinding.Security.Message.ClientCredentialType = MessageCredentialType.None;
identityProviderBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
var trustChannelFactory = new WSTrustChannelFactory(identityProviderBinding, identityProviderEndpoint)
{
TrustVersion = TrustVersion.WSTrust13,
};
var channel = trustChannelFactory.CreateChannel();
var rst = new RequestSecurityToken(RequestTypes.Issue)
{
AppliesTo = new EndpointReference("http://azureservices/AdminSite"),
KeyType = KeyTypes.Bearer,
};
RequestSecurityTokenResponse rstr = null;
SecurityToken token = null;
token = channel.Issue(rst, out rstr);
Here is what I currently have in Java, where I am attempting to do the same thing:
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBusFactory;
import org.apache.cxf.sts.STSConstants;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
import org.apache.cxf.ws.security.trust.STSClient;
SpringBusFactory springBusFactory = new SpringBusFactory();
Bus bus = springBusFactory.createBus();
STSClient stsClient = new STSClient(bus);
stsClient.setLocation("https://" + endpoint + ":30072/wstrust/issue/windowstransport");
stsClient.setServiceName("{http://schemas.microsoft.com/ws/2008/06/identity/securitytokenservice}SecurityTokenService");
stsClient.setEndpointName("{http://schemas.microsoft.com/ws/2008/06/identity/securitytokenservice}WS2007HttpBinding_IWSTrust13Sync");
stsClient.setKeyType(STSConstants.BEARER_KEY_KEYTYPE);
stsClient.isEnableAppliesTo();
bus.setProperty(SecurityConstants.STS_CLIENT, stsClient);
bus.setProperty(SecurityConstants.STS_APPLIES_TO, "http://azureservices/AdminSite");
SecurityToken securityToken = stsClient.requestSecurityToken();
I get a 401 Unauthorized HTTP response when running my Java test code:
Caused by: org.apache.cxf.transport.http.HTTPException: HTTP response '401: Unauthorized' when communicating with https://endpoint:30072/wstrust/issue/windowstransport
It looks like I'm missing the following pieces of functionality when attempting to recreate what the C# code does, but I can't figure out what the equivalent of the following code would be in Java/using the Apache CXF library:
1) identityProviderBinding.Security.Message.EstablishSecurityContext = false;
2) identityProviderBinding.Security.Message.ClientCredentialType = MessageCredentialType.None;
3) identityProviderBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
It's also possible I'm doing other things wrong as well. Any thoughts or suggestions?
Have you tried using management certificates to authenticate your requests instead of security tokens. https://msdn.microsoft.com/en-us/library/azure/ee460782.aspx#bk_cert has information on how to do it in Azure, but it should not differ much for Azure Pack.

Facebook4j access token error 2500

I would like get data from facebook with facebook4j library, but I received this error
An active access token must be used to query information about the
current user. code - 2500
The code:
ConfigurationBuilder confBuilder = new ConfigurationBuilder();
confBuilder.setDebugEnabled(true);
confBuilder.setOAuthAppId("MY ID APP");
confBuilder.setOAuthAppSecret("MY APP SECRET");
confBuilder.setUseSSL(true);
confBuilder.setJSONStoreEnabled(true);
Configuration configuration = confBuilder.build();
FacebookFactory facebookFactory = new FacebookFactory(configuration );
Facebook facebookClient = facebookFactory.getInstance();
AccessToken accessToken = null;
OAuthSupport oAuthSupport = new OAuthAuthorization(configuration );
accessToken = oAuthSupport.getOAuthAppAccessToken();
facebookClient.setOAuthAccessToken(accessToken);
ResponseList<Post> feeds = facebookClient.getHome(new Reading().limit(1000));
You go to the following link: https://developers.facebook.com/tools/explorer/
There you choose your app, which you created and want to access from.
.setOAuthAccessToken("The User Access Token")
accessToken = oAuthSupport.getOAuthAccessToken(); // NOT AppAccessToken!!!
Then it should work

AWS cognito does not generate tokens when run from a serverlet

I am trying to get amazon cognito to work. If I run the code to generate a login token from a standalone java program it works.
public class cognito extends HttpServlet
{
public static void main(String[] args) throws Exception {
AWSCredentials credentials = new BasicAWSCredentials("*******", "********");
AmazonCognitoIdentityClient client =
new AmazonCognitoIdentityClient(credentials);
client.setRegion(Region.getRegion(Regions.EU_WEST_1));
GetOpenIdTokenForDeveloperIdentityRequest tokenRequest =
new GetOpenIdTokenForDeveloperIdentityRequest();
tokenRequest.setIdentityPoolId("*************");
HashMap<String, String> map = new HashMap<String, String>();
//Key -> Developer Provider Name used when creating the identity pool
//Value -> Unique identifier of the user in your <u>backend</u>
map.put("test", "AmazonCognitoIdentity");
//Duration of the generated OpenID Connect Token
tokenRequest.setLogins(map);
tokenRequest.setTokenDuration(1000l);
GetOpenIdTokenForDeveloperIdentityResult result = client
.getOpenIdTokenForDeveloperIdentity(tokenRequest);
String identityId = result.getIdentityId();
String token = result.getToken();
System.out.println("id = " + identityId + " token = " + token);
}
}
However when I run this code from a servlet on a redhat linux server, it always times out.
Any suggestion would be helpful
map.put("test", "AmazonCognitoIdentity");
are you sure your developer provider name is "test"?
you can see it in your cognito identity pool edit page.
And "AmazonCognitoIdentity" should be your own unique user-id.
Without the actual exception, it is hard to tell what is the exact issue. It could be that something else running in your servlet engine is setting a much more aggressive socket timeout than the default when it runs from the command line. You might want to explicitly set the connection and socket timeouts using methods using this class http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/ClientConfiguration.html and pass it in to the identity client constructor.

Getting one field from response entity json

i need to connect to a rest service to get the user id by using a token.
List<Object> providers = new ArrayList<>();
providers.add(new JacksonJaxbJsonProvider());
client = WebClient.create(properties.getProperty(URL), providers);
client = client.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE);
client.path(PATH + token);
Response response = client.get();
The entity of response have this format:
{"message":"Token is valid","userId":1}
To get the userId, i have:
response.readEntity(AuthResponse.class).userId;
It is possible to take only the userId without creating an class with that format ? (without AuthResponse.class)
You can try to read your JSON as Map, for example: response.readEntity(Map.class).get("userId")
Please refer to this page for more information.

Categories