DotNetOpenAuth ResourceServer Get User ID from Principal - c#

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.

Related

What is the idiomatic way to get a user's email from Xero's OAuth flow

I have a web app which uses the Xero.NetStandard.OAuth2Client package to allow for authentication with Xero.
Once the user is redirected back into my app, I use the IXeroClient.RequestAccessTokenAsync method to exchange their code for an IXeroToken object, which allows me to make calls against the Xero API, as expected.
The one thing I do not know how to do, and which I can't seem to find in the official documentation, is how do I extract the user's details (namely their name and email address) from the IXeroToken object.
As per the standard, the information is encoded as JWT string in the IdToken property, but I am not sure how I am meant to get the information out of it without an additional dependency.
The built in System.IdentityModel.Tokens.Jwt.JwtSecurityToken class can deserialize the IdToken payload.
new JwtSecurityToken(accessToken.IdToken).Claims contains all the claims in the token.
The relevant types are:
email - The user's email
xero_userid - The user's id (guid)
given_name - The user's first name
family_name - The user's last name
The claims' existence is obviously conditional to the appropriate scope being set.

how to get the user attribute from aws cognito in c#

I am using AmazonCognitoIdentityProviderClient SDK.
I am trying to get a custom attribute for user in cognito. from c# front end i am passing username , password and email id. is there any function to retrieve the user atribute from cognito ?
After Cognito successfully authenticates a user in your pool, you will receive several JWTs - an access token, an ID token, and a refresh token. These tokens can be accessed in the authentication result object that is returned by the SDK (InitiateAuthResponse).
You can verify and decode the ID token to unpack the claims about the user's identity. This will also include any custom attributes you have defined on your User Pool. For .NET you can use JwtSecurityTokenHandler to decode the JWT (Sytem.IdentityModel.Tokens.Jwt namespace). After decoding the token, access the Claims property to get the user information. Custom attributes are prefixed with custom:, while Cognito attributes (such as username) are prefixed with cognito:.
Here's an AWS doc on how to decode the token: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html
Here's an example on how to use JwtSecurityTokenHandler: https://www.jerriepelser.com/blog/manually-validating-rs256-jwt-dotnet/
You can also use the Access Token to use the SDK to lookup a user directly, and the response from the AWS SDK will include the user attributes. Here's the doc on that: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUser.html
Try Amazon.CognitoIdentityProvider.AmazonCognitoIdentityProviderClient.GetUserAsync(), it will return all standard and custom attributes. Please note that the method will only return the attributes for which a value is set.

How to validate the SalesForce Consumer Key and Consumer Secret

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

Check domain name of email Id for google oauth

I am trying to authenticate my app using google oauth. I want to allow only a particular set of people having a specific "#eg.com" to be able to obtain access.
I tried including the
hd="eg.com"
in my url.
But it is accepting even "#gmail.com" or "#company.com" domains.
Is there a way to do this, so that users like "users#eg.com" only gain access tokens and stuff?
Edit:
I am using a webview in my app to perform the authorization
You can (and should!) validate your id_token with a call to the google api. Call https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=XYZ123 and check the various fields of the response. If you request the "profile" permission you will also get the email field. You can then check this email against your domain, and deny the access if it does not fit.
For detailed documentation see:
https://developers.google.com/identity/sign-in/web/backend-auth#calling-the-tokeninfo-endpoint
i think you will have to implement that in your application
just don't store the tokens and show some error message if the domain part is not the one allowed.
you can get the domain part in c# using
string s = "users#eg.com";
string[] words = s.Split('#');
words[0] would be users and words[1] would be eg.com
Alternatively you can use MailAddress

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!

Categories