How to validate the SalesForce Consumer Key and Consumer Secret - c#

We have a system, where we want to push the records (e.g. Contact, Account, Opportunity) from our system to SalesForce.
To achieve this, we have used ForceToolKit for .Net. We are successfully pushing the contact records from our system to Salesforce.
First customer has to provide the consumer key and secret and upon providing these details, the user will be redirected to Salesforce login page for OAuth. We are storing the RefreshToken and it will be used at the time of Data push.
Here, if user provides incorrect consumer key, then it is redirecting to Salesforce login page and shows below message:
error=invalid_client_id&error_description=client%20identifier%20invalid
Now, we have to validate the Consumer key & secret before it redirects to Salesforce URL and check if it is valid or not.
Can anyone help me on how to achieve this?

I understand your question so why the Error will be like mismatch of URL which you provided in Enpoint URL. This is first reson and next is consider the method post or get but main Reason is URL mis match intha URL you have to use request type. And consumer key secret key and username password this are the maditory to get the access token.

As Aleander said, it's the first wrong endpoint URL and you need to consider additional things.
Instance = login for Production, and test for the sandbox.
URL - https://<instance>.salesforce.com/services/oauth2/token
Method - POST
Params -
grant_type - password (hardcoded)
UserName - Username which you may have
Password - Here it's a bit tricky if you have IP enabled in the org for your user profile, then you need to append your security token with the password.
Consumer Key - consumer key you're trying.
Consumer Secret - Consumer secret you're trying.
You can check similar details in the below link as well -
Link - https://medium.com/#krissparks/postman-a-salesforce-rest-web-service-28edc0a69851

Related

Recover Account functionality For WCF rest API

I am looking for the working example of "Recover Account or Forgot Password" For WCF RestAPis.
What I have tried?
I have build a Forget Password API, which takes email as an input parameter and if email exists in the database, it genertes an "JWT Identity Token" contains encypted userID and expiration Date as a payload and sent it to email as a link.
token is generted as per this example: https://www.codeproject.com/Tips/1208535/Create-and-Consume-JWT-Tokens-in-Csharp
That link will hit another API which takes the token and encrypt it, if the expiration time does not get passed, then it will allow updation of the password against the userID
Now my concerns over the above approach are:
Is it even right way to do it?
when password gets changed, how to make token to gets expired?
What are the other ways?
Thanks In advance

How can I create a random unique token and use it to verify an email address for a user in ASP.NET Core?

I have all the logic written for my user registration except for email verification. Via my researched I learned that, simplifyingly, I need to create a random unique token and include that token in a link sent to the email address that is to be verified.
How can I create this random token and what how should I process the request from the activation link?
I don't know about Nuget but you can code yourself for sending an activation link and processing it.
The steps are:
1) Generate random unique token and save it in your database. For generating unique token you can use UUID in Java as
String uniqueID = UUID.randomUUID().toString();
2) Include that token, encrypt it (not necessary though) and send it to the email ID.
example: www.xyz.com/activation?action=a273jsjh2718sjhdj271jgsdjaj28jh
3) When ever the user clicks that link, invoke the method for further processing in your controller. Map the url to your method in your controller.
Here is the example done using Spring Framework. I hope it helps.
PS: I don't know whether it is good practice for production. I just tried to help you.

Restful Login - proper implementation

New to RESTful services but read a lot on the subject. Implementing in VS2010 C#
Similar (nearly identical) questions have been asked and answered here on stackoverflow, but honestly I learned nothing from the responses.
I want to implement an AuthenticatUser call where a username and password is sent and an authentication key is returned.
Given that this needs to be done with a GET, POST, PUT, OR DELETE, it seems the GET would be most appropriate.
So perhaps GET mydomain/myservice/authenticate/{username}/{password}
I don’t like this because the username and password is passed in the URI, but as I understand it is not a good idea to send a body in a GET. So a POST or PUT would work, but that seems to diverge from the RESTFul philosophy.
Question 1: Is it OK to send sensitive data like password in the URL? The site will use SSL.
Question 2: In GETs when there are multiple parameters being passed, it seems like the URI concept would get a bit crazy, how are complex queries supposed to be handled RESTfully?
Question 3: What is the preferred (normal, most common) method of authentication in a RESTful API?
It is not correct to pass password in url. I have done some research on this. Firstly you should use Basic Authentication over SSL if that is possible. In the Authentication header pass the userid and password. Now as far as rest is concerned the session is not maintained in server. So you need to pass user id and password for every call. It is risky to store the password in the local storage. Hence use a POST call for first time authentication and pass userid and password. Then on return of successful authentication the server returns a tokenkey and tokenvalue. tokenkey and tokenvalue are similar to Amazon private key share initially. From next request onwards send the tokenkey and sign your data using tokenvalue. Pass the tokenkey and signature everytime. On serverend, the server verifies the signature since it has a copy of tokenvalue. tokenkey and tokenvalue can be stored locally if possible encrypted. You cannot use the tokenkey and tokenvalue forever. Hence on each request the server sends a nonce in response. This nonce is stored in database in server end and changes for every request. When you send a request to server include this nonce. The nonce is formed using timestamp. If a request is sent say after 15 mins, the nonce is decrypted and timestamp is found to be more than 15 minutes and hence you redirect him to login page. Formation of Nonce is given in http://www.ietf.org/rfc/rfc2617.txt. Once the nonce is successfully validated this nonce is discarded and and a new nonce is now sent (formed again with latest timestamp). This will also help to prevent replay attack.

REST API token authentication

I just started a development of my first REST API in .NET. Since it will be stateless I will use tokens for authentication:
Basic idea (System.Security.Cryptography):
AES for encryption + HMACSHA256 for integrity
token data will consist object with properties: username, date of issuing and timeout
database will hold username, hashed password and HMAC hash
Login:
check if credentials are valid (username, compare hashed password to db value)
if true, encrypt data object
use HMAC on generated token and store it to database
return token (without HMAC) to user (cookie/string)
Request to method which requires authentication:
user sends token with each request
token is decrypted
if it is expired, error
if not expired use HMAC and compare username + generated hash with db values
if db check valid, user is authenticated
The way I see it, this approach has following pros:
even if db is comprosmised, it does not contain actual token (hash cannot be reversed...)
even if attacker has token, he cannot increase expiration by updating fields since expiration date is in the token itself
Now firstly, I wonder if this is good approach at all.
Besides that I still didn't figure out, where to store AES and SHA256 keys on server (should i just hardcode them? If I put them into web.config or use machine key than I have a problem in case of load balanced servers,...).
And lastly where do I store AES IV vectors, since Crypto.CreateEncryptor requires it for decryption? Does it mean that users have to send token + IV with each request?
I hope this makes any sense and I thank you for answers in advance.
UPDATE:
Ok, now I did some more research and came down with this solution:
token will contain originally specified data (username, date of issuing and timeout)
token is generated with encrypt-then-mac (it includes AES encrypted data, IV vector + tag of these 2 values for authentication, generated with HMACSHA265)
token tag will be written to db
user will be authenticated if:
tag is valid (token authentication)
data can be decrypted
token has not expired yet
tag matches the one written in database
user is not blocked in database (token invalidation on demand)
keys will be stored in web.config separate section. Same keys will have to be on every server (per application of course)
I didn't use FormsAuthenticationTicket because in .NET there are following issues:
same keys are used for different purposes (machinekey for view states, resources and formauthtickets)
mac-then-encrypt, used by .NET is not considered as safe as encrypt-then-mac
no built in way to invalidate token before it is expired
This is a follow up from the comment thread under the question.
You seem to be a bit confused as to what, exactly, OAuth is, so hopefully I can clarify it here.
OAuth is not a web service or something you consume. It is a protocol that describes the way that a site can authenticate a user against a service, without allowing the site to know what the user's credentials are. As a side benefit, most OAuth providers also have a web service to query the user's information, and permission to do so can be granted at the same time.
Typically, you are interested in implementing OAuth from the perspective of the site (eg, AcmeWidgets.com) so that a user can log in via Facebook or Google or something. However, you can also implement the service side (eg, where Facebook normally would be), and allow others to authenticate against YOU.
So, for example, let's say you have a web service to allow for third-party sites to provision Acme-brand Widgets for users. Your first third-party implementor is the popular MyBook.org. The flow would look something like this:
Someone invites the User to use the "Acme Widgets" app on their MyBook profile.
The user clicks on the button, which redirects to AcmeWidgets.com. The URL looks something like:
http://acmewidgets.com/oauth/user?r=http%3A%2F%2Fmybook.org%2Foauth%2Fclient&appid=12345
The user is asked if they want to allow MyBook to access their data and provision widgets.
The user clicks Yes, whereupon Acme Widgets notes that the user has allowed it.
The user is redirected back to MyBook, at a URL like this:
http://mybook.org/oauth/client?token=ABCDEFG
MyBook, on the server side, now takes that token, and places a web service call BACK to AcmeWidgets:
http://acmewidgets.com/oauth/validate?token=ABCDEFG&appid=12345&appsecret=67890
AcmeWidgets replies with the final authentication token identifying the user.
Alternately, it fails, which means the user is trying to fake a token, or they denied permission or some other failure condition.
MyBook, with the token, can now call AcmeWidgets APIs:
http://acmewidgets.com/api/provision?appid=12345&token=ABC123&type=etc
This is all known as the OAuth dance. Note that there are a number of implementation defined things here, like URLs, the means of encoding the various tokens, whether tokens can expire or be revoked, etc.
Hopefully that clears everything up for you!

DotNetOpenAuth ResourceServer Get User ID from Principal

I have created a project that uses DotNetOpenAuth to implement both an OAuth2 AuthorizationServer and ResourceServer in one.
What I am wanting to do is use the OAuth as pseudo-authentication where the Client is authorised by OAuth to get the associated resource which is the user's profile.
On the ResourceServer I can use resourceServer.VerifyAccess( request, out result );
to successfully return the IPrincipal.
My question is: on the ResourceServer (which is the same as the Authorization Server) how can I get the user/user id/user profile from the Principal (or anything else that I have access to). The Principal name looks like a base64 encoded string. But that doesn't seem to match anything else that I have access to.
DotNetOpenAuth's ResourceServer.VerifyAccess method gives you a principal whose name is the user who authorized the access token, and whose roles are the scopes that were granted to that token.
If you're seeing some base64 encoded string looking thing as the principal's name, it sounds like you should double check your code. I suggest you start at the point in your authorization server code that you call AuthorizationServer.PrepareApproveAuthorizationRequest passing in the authorizing username. Make sure that's what it should be.
It's highly unlikely that it was corrupted in transit because the token is encrypted and signed.

Categories