Error while doing Salesforce Authentication from C# Client Application - salesforce

Below is the complete code I have written to work with login() for Salesforce authentication. But, I am getting error if I execute the code in .Net client (Console Application). Can anybody please suggest me how to solve this problem.
My onsite coordinator has confirmed that everything is fine as long as Salesforce concerned.
Code
private bool login()
{
string username = "kak.mca#gmail.com";
string password = "Temp0r#ry";
string securityToken = "";
string resultSessionId = string.Empty;
string resultServerUrl = string.Empty;
binding = new SforceService();
binding.Timeout = 60000;
LoginResult lr;
try
{
#region Method1
//lr = binding.login(username, password);
#endregion Method1
#region Method2
using(binding)
{
lr = binding.login(username, password);
resultSessionId = lr.sessionId;
resultServerUrl = lr.serverUrl;
}
#endregion Method2
return true;
}
catch (SoapException e)
{
Console.WriteLine("Fault code: " + e.Code + Environment.NewLine + "Error message: " + e.Message + Environment.NewLine + "Stack trace:" + e.StackTrace);
return false;
}
}
Error:
<font color='red'>Fault code: INVALID_LOGIN<br />
Error message: INVALID_LOGIN: Invalid username, password, security token; or user Locked out.<br />
Stack trace: at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at Walkthrough.sforce.SforceService.login(String username, String password) in <filepath>\Web Reference\sforce\Reference.cs:line 545
at Walkthrough.QuickStartApiSample.login() in <filepath>\QuickstartApiSample.cs:line 54
</font>

You are missing security token. You can get one by navigating to your name > Setup > Personal Setup > My Personal Information > Reset My Security Token. Your password variable should be
password = loginPassword + securityToken;
Or you can try Set Up Authorization, Authenticating Apps with OAuth and Digging Deeper into OAuth 2.0 on Force.com

The error was due to improper credentials. When submitted proper credentials, everything went fine.

Related

Graph API: Insufficient privileges to complete the operation

I have the following permissions on my registered Azure Function..
This azure function will work as web hook and called by some application/API
but when I try to get data
public async Task<string> FindUpnByEmail(string email)
{
if (string.IsNullOrEmpty(email)) return email;
try
{
var request = new RestRequest("users")
.AddQueryParameter("$filter", $"mail eq '{email}'")
.AddQueryParameter("$select", "userPrincipalName");
var rest = new RestClient(GraphUrl)
{
Authenticator = await GetAuthenticator(),
};
var response = await rest.ExecuteGetAsync(request);
var userResponse = JsonConvert.DeserializeObject<ODataResponse<User>>(response.Content);
return userResponse.Value.Length > 0 ? userResponse.Value[0].UserPrincipalName : email;
}
catch (Exception ex)
{
return email;
}
}
I receive the following error:
Authorization_RequestDenied","message":"Insufficient privileges to
complete the operation.
Try to update the Admin consent to Yes for profile, Read Basic profile.
Or Add read write delegate permission and grant admin consent for that as well.

AuthenticationCertCallback does not work under Ubuntu / docker

I have problem with Certificate Key Vault authentication. In general, it works fine under my pc (win10), but when I run the same code under ubuntu/ docker I receive null reference exception. (On both environments, the certificate is present)
private async Task<string> AuthenticationCertCallback(string authority, string resource, string scope)
{
try
{
var clientAssertionCertPfx = CertificateHelper.FindCertificateByThumbprint(_options.KeyVaultOptions.CertThumb);
var assertionCert = new ClientAssertionCertificate(_options.KeyVaultOptions.Id, clientAssertionCertPfx);
var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
var token = await context.AcquireTokenAsync(resource, assertionCert);
return token.AccessToken;
}
catch (Exception ex)
{
Log.Error(ex, "Failed to acquire the certificate");
return string.Empty;
}
}
I use Microsoft.IdentityModel.Clients.ActiveDirectory" Version="5.2.0"
had anyone same problem ?
Ok, so the issue is with GetRSAPrivateKey() from X502Certificate2 class as it returns null under .net core

o365 calendar API not returning calendar

I am following instructions provided at https://dev.outlook.com/RestGettingStarted/Tutorial/dotnet to get my web application integrated with user's outlook calendar. I am being redirected to login into my microsoft account and it returns to my return url with the code parameter populated. However when I try to generate token out of that code it returns empty without any error.
Can someone please advise?
Following code is to generate token from the code:
// Note the function signature is changed!
public async Task<ActionResult> Authorize()
{
// Get the 'code' parameter from the Azure redirect
string authCode = Request.Params["code"];
string authority = "https://login.microsoftonline.com/common";
string clientId = System.Configuration.ConfigurationManager.AppSettings["ida:ClientID"];
string clientSecret = System.Configuration.ConfigurationManager.AppSettings["ida:ClientSecret"];
AuthenticationContext authContext = new AuthenticationContext(authority);
// The same url we specified in the auth code request
Uri redirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));
// Use client ID and secret to establish app identity
ClientCredential credential = new ClientCredential(clientId, clientSecret);
try
{
// Get the token
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
authCode, redirectUri, credential, scopes);
// Save the token in the session
Session["access_token"] = authResult.Token;
// Try to get user info
Session["user_email"] = GetUserEmail(authContext, clientId);
return Content("Access Token: " + authResult.Token);
}
catch (AdalException ex)
{
return Content(string.Format("ERROR retrieving token: {0}", ex.Message));
}
}

Oauth 2.0 exchange authorization code for token : Invalid scheme for redirect uri

i'm trying to exchange a received authorization code wth a token in a web application but when I call GoogleAuthorizationCodeTokenRequest i get this error :
"Invalid parameter value for redirect_uri:
Invalid scheme:https://mapmydayunamur.appspot.com/getauthcodeservlet"
I've tried many redirect_uri and don't know why I get this error.
The Uri is in my redirect Uri in developers console.
Here's my code :
in getauthcodeservlet.java :
String authcode = req.getParameter("code");
String clientID = "CLIENTID_FROM_GOOGLEDEVELOPERSCONSOLE"
String clientSecret = "CLIENTSECRET_FROM_GOOGLEDEVELOPERSCONSOLE";
String redirectUri = "https://mapmydayunamur.appspot.com/getauthcodeservlet";
try {
GoogleTokenResponse response =
new GoogleAuthorizationCodeTokenRequest(new NetHttpTransport(), new JacksonFactory(),clientID, clientSecret, authcode,redirectUri).execute();
resp.getWriter().println("Access token: " + response.getAccessToken());
} catch (TokenResponseException e) {
if (e.getDetails() != null) {
resp.getWriter().println("Error: " + e.getDetails().getError());
if (e.getDetails().getErrorDescription() != null) {
resp.getWriter().println(e.getDetails().getErrorDescription());
}
if (e.getDetails().getErrorUri() != null) {
resp.getWriter().println(e.getDetails().getErrorUri());
}
} else {
resp.getWriter().println(e.getMessage());
}
}
}
Thanks for helping me
Problem solved by inruducing the redirect_uri via
.setRedirectUri(getRedirectUri(req))
and adding the method
static String getRedirectUri(HttpServletRequest req) {
GenericUrl requestUrl = new GenericUrl(req.getRequestURL().toString());
requestUrl.setRawPath("/getauthcodeservlet");
return requestUrl.build();
}
You cannot specify a subdirectory. Per Google's documentation when changing Client Credential settings in the developer's console:
Cannot contain a wildcard (http://*.example.com) or a path
(http://example.com/subdir).
So you should change to https://mapmydayunamur.appspot.com

Could not connect to SMTP host) error while sending mail

I am facing (Could not connect to SMTP host) error while sending mail by using javax.mail.jar. I am able to send mail through smtp.gmail.com, but when i am trying to connect to my company mail server i am getting the error. I tried from telnet and i am able to send mail from telnet and another python program is also running which is sending mail using the same mail server(ip and port), our bugzilla server is also running on same ip and port and it is successfully sends the mail. I tried to configure the same from java as well as from log4j through SMTP appender but no sucess.
Please guid me.
Thanks In Advance
my code as below -
private Session getSession()
{
Authenticator authenticator = new Authenticator();
Properties properties = new Properties();
properties.setProperty("mail.smtp.submitter", authenticator
.getPasswordAuthentication().getUserName());
properties.setProperty("mail.smtp.auth", "true");
properties.put("mail.smtp.socketFactory.port", "25");
//properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.host", smtpServer);
properties.setProperty("mail.smtp.port", smtpPort);
return Session.getInstance(properties, authenticator);
}
private class Authenticator extends javax.mail.Authenticator
{
private final javax.mail.PasswordAuthentication authentication;
public Authenticator()
{
authentication =
new javax.mail.PasswordAuthentication(username, password);
}
#Override
protected javax.mail.PasswordAuthentication getPasswordAuthentication()
{
return authentication;
}
}
public boolean sendEmail() throws MessagingException
{
boolean isSuccess = false;
String setBody = "";
String setSubject = "";
try
{
Message message = new MimeMessage(getSession());
setReceipients(message);
message.addFrom(new InternetAddress[]
{ new InternetAddress(emailFrom, "Notification") });
setSubject = emailSubject;
message.setSubject(setSubject);
setBody = emailBody + "\nThis is a System Generated Mail";
message.setContent(setBody, "text/plain");
Transport.send(message);
log.info("Mail Sent Successfully to - " + emailTo);
isSuccess = true;
}
catch (UnsupportedEncodingException ex)
{
log.error("Error in sending Mail without Attachment- "
+ ex.getMessage());
log.warn("Mail Sending Failed for Mail ID:" + emailTo);
}
catch (SendFailedException e)
{
log.error("Invalid Addresses \"" + emailTo + "\" specified:"
+ e.getMessage());
log.warn("Mail Sending Failed for Mail ID:" + emailTo);
}
catch (Exception e)
{
log.error("Error in sending Mail without Attachment- "
+ e.getMessage());
log.warn("Mail Sending Failed for Mail ID:" + emailTo);
}
return isSuccess;
}
The JavaMail FAQ has debugging tips.
It would help to see the debug output from JavaMail.
Possibly you have a firewall or anti-virus program that is blocking port 25.

Resources