Check domain name of email Id for google oauth - c#

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

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.

DotNetOpenAuth ClaimedIdentifier changes? What should I store in database to identify users

There are quite a few questions like this and this which all claims that ClaimedIdentifier should be used to uniquely identify each user.
After successful login I am storing ClaimedIndentifier in database. Whenever a user logs in, I traverse through my records looking for the ClaimedIdentifier. However I noticed that ClaimedIdentifiers are changing. What should I store in database to identify my users. I am using Google account.
This is how I am retrieving storing it into database
OpenIdRelyingParty rp = new OpenIdRelyingParty();
IAuthenticationResponse r = rp.GetResponse();
UserController.addUser(new UserController.User(r.ClaimedIdentifier.ToString(), 0));
This isn't a DotNetOpenAuth unique issue. This is a Google behavior. Google's OpenID Provider issues what are called pairwise-unique identifiers. They will always be the same for a given user so long as your OpenID realm is constant.
If you log users in without explicitly supplying a realm to DotNetOpenAuth's OpenIdRelyingParty.CreateRequest method, DotNetOpenAuth simply uses the current web application root URL. This is a reasonable default, except that if your site is accessible in more than one way (e.g. http and https, or with and without the www. host name) than the default realm will vary based on the URL the user happened to use to reach your login page. And when the realm varies, so do Google's generated claimed identifier.
The fix then, is for you to pick one realm (preferably one with an https scheme if that's an option) and explicitly supply it to the CreateRequest method. You must also ensure that your return_to argument to the same method shares a common root with the realm you've chosen. For example, if the realm you choose is:
https://www.mysite.com/
Then you must ensure that your return_to is based on that. Something like:
https://www.mysite.com/login.aspx
If the user has browsed to http://mysite.com/login.aspx, that would be the default URL for the return_to, which would not match the realm you've chosen.
So altogether, it may look like this:
var request = relyingParty.CreateRequest(
"https://www.google.com/accounts/o8/id",
"https://www.mysite.com/",
new Uri("https://www.mysite.com/login.aspx"));
Note that your return_to does not need to be exactly the same with each request as the realm does. So you could have several login page URLs and each one specify its own URL as the return_to parameter. But all return_to URLs must be based on the realm URL.
With that change consistently applied to everywhere you allow users to log in, you should see consistent claimed identifiers from google. Unfortunately, the claimed identifiers you have already obtained using other realms won't match the ones you'll get after this fix. If you need to merge these user accounts, and if you have email addresses for the users you might try merging based on that. But be very wary of this step. It can only be safely done if you're sure the email addresses you have on file belong to those users. If you obtained those email addresses via OpenID when the users logged in, and double checked that it was from an OpenID Provider you trust and that verifies emails, then you're probably OK. Note that just hard-coding Google OP Identifier into CreateRequest does not guarantee that only Google users log in. To make sure of that, you'd have had to be checking that the IAuthenticationResponse.Provider.Uri property matches https://www.google.com/accounts/o8/ud when the positive assertion comes in.

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.

Generic OAuth Library C#

What i am Trying to do:
Write a Generic Library in C# to handle OAuth Flow to every service ( Just like Twitter,LinkedIn and Foursquare). The hardest part is that, i want to simulate all the user input in code so that no user action is needed to click on buttons like "Ok,I will Allow It",or even writing its username/password.
Doubts That i have so far:
1 - Whats the usage of the authenticity_token in twitters API ?
2 - What are the factors that all services use, so that i can implement a generic usage of OAuth Flow. For example i´ve found the first Step is really easy to make a Generic method to execute. All i have to do is change the URL for the webRequest,and BAM, i have the Request tokens.
3 - How do i Get the Verifier for each service? In LinkedIn Service for instance, i was able to parse a page to fetch this value, but i can't find this verifier for twitter API for example. Even when authorizing in browser my aplication, i see no Verifier in any HTML during the flow, or any JavaScript generating it.
Observations:
1 - I know that there are Lots of OAuth Libraries out there, like this or that ones, but there is no Library that allows me to make what i want to, that is to Authenticate and authorize a user, without prompting for any user input.
2 - I can't,by any means,ask for user input. All the values like username and password for the authentication, will be hardcoded and every user will use the same account for this requests.
3 - I also know, that there are other posts here that i've written, with almost the same doubts, and the reason i am resposting is to try to make it clearer and fresher.
4 - Sorry about any english mistake or missunderstanding of concepts in advance.
Basic Code Sample:
This is, for instance, the method i am using (that is avaible widely abroad the web) for getting request tokens for any service. All i have to do is change the REQUEST_TOKEN value to the specific url to be used for a service,so i can get the Tokens for LinkedIn,Twitter or Foursquare for instance. But i can't manage to apply the same process in the other steps.
public string AuthorizationLinkGet()
{
string ret = null;
string response = oAuthWebRequest(Method.GET, REQUEST_TOKEN, String.Empty);
if (response.Length > 0)
{
//response contains token and token secret. We only need the token.
NameValueCollection qs = HttpUtility.ParseQueryString(response);
if (qs["oauth_callback_confirmed"] != null)
{
if (qs["oauth_callback_confirmed"] != "true")
{
throw new Exception("OAuth callback not confirmed.");
}
}
if (qs["oauth_token"] != null)
{
ret = AUTHORIZE + "?oauth_token=" + qs["oauth_token"];
}
}
return ret;
}
Don't.
OAuth was designed to require a user to press that button once. If you automate it you will have your application key revoked and your program will no longer work.
What you need to do is save locally the authorization token and reuse that. The user clicks"I Allow" once then you re-use the authorization token for future connections. You need to check to make sure it is not expired, and if it is you just re-authorize and they click "I Allow" again.
No website doing OAuth correctly will allow you to bypass the website authorization, some will allow you to pass the username and password via a query and get a token, but if they have a web authorization, you MUST have the user manually do it.
If you are the OAuth provider and consumer you need to do something Dropbox did for their v0 of the API (I can't find any links to their old API, if anyone can find it edit this post) that passed the username and password to a special address that returned a autorization token without using a webpage. Or you need to use a different authentication scheme than OAuth.

fetch email of a friend in facebook app

How do I fetch the email of my friend programmatically in my facebook application? Does facebook provide this functionality?
The answer is no, Facebook does not provide this functionality. Facebook tries to protect the privacy of its users, and therefore user email addresses are explicitly not available.
The only way to email a user is to prompt them to grant you extended email permissions via a Facebook prompt. If they grant you the permission, you can then use the notifications.sendEmail API method, or query the user table for the proxied_email field, and send them an email via Facebook's Email Proxy system.
edit: This changed with the newer Graph API's permissions system. Users now have the option to use the proxymail address, but it appears to reveal the true e-mail by default.
Facebook's API calls do not reveal users' e-mail addresses, ever.
Even when a user specifically grants you permission to e-mail them, it's a proxied e-mail address that doesn't reveal their true address - something like apps+###########.#########.#######################proxymail.facebook.com.
See http://wiki.developers.facebook.com/index.php/Proxied_Email for details.
I don't think you can do this via FQL.
As an academic exercise you might need to use CURL and then have a CAPTCHA-parsing service
see also:
http://www.25hoursaday.com/weblog/2007/08/21/FacebookTheSocialGraphRoachMotel.aspx
and
http://weblogs.mozillazine.org/gerv/archives/2007/09/facebook_imagetoemail.html
of course Christopher Finke's plug-in:
http://www.chrisfinke.com/2007/09/11/convert-facebook-e-mail-images-to-actual-e-mail-links/
The functionality is available,the new facebook ios sdk has extended permissions where u can declare the Permissions to grant access while logging in by the user, when access granted we can access their Email ID,
like this,i have fetched ,
_permissions = [[NSArray arrayWithObjects:
#"publish_stream",#"email", #"offline_access",nil] retain];
NSString *emailUsr = [result objectForKey:#"email"];
Now you can get the Facebook User Email.

Categories