Trying to get Facebook Cookie from codebehind, but is getting (OAuthException) - asp.net

I am using Facebook C# SDK on my site, and is trying to access the cookie made by Facebook when the user has chosen to use Facebook as login, but I am getting the following error:
(OAuthException) An active access token must be used to query
information about the current user.
Here is the code I am using:
var client = new FacebookClient([App ID], [App Secret]);
dynamic me = client.Get("me");
string firstName = me.first_name;
Response.Write(firstName);
What am i doing wrong?
Thanks in advance

You need to authorize first before trying to access the user. This does the necessary redirects and plumbing to have Facebook set the cookie.
var auth = new CanvasAuthorizer { Permissions = new string[] {"user_about_me"} };
if (auth.Authorize()) {
var client = new FacebookClient([App ID], [App Secret]);
dynamic me = client.Get("me");
string firstName = me.first_name;
Response.Write(firstName);
}

Related

How to get IdentityUser by Username

I have previously worked with Membership through "System.Web.Security.Membership"
Here, you can do the following:
var currentUser = Membership.GetUser();
var otherUser = Membership.GetUser(username);
...giving you a MembershipUser.
Now, with Identity, I can find a load of ways to get the current logged in user.
But no way to get another user.
I can use:
var userStore = new UserStore<IdentityUser>();
var userManager = new UserManager<IdentityUser>(userStore);
var user = userManager.Find(username, password);
But that takes both username and password, with no overload for just username.
How do i get the IdentityUser from only a username?
Almost every answer I find is connected to MVC.
This is for a WCF service, where authorization is made using Identity. And in some cases the user is getting to the site from an other site with a generated "token" - an encrypted string, containing the username. From here, user is logged in and a session-cookie is set, depending on users settings.
Also, is there a shorter way to get UserInformation?
"var currentUser = Membership.GetUser(username);"
is much more convenient than
"var user2 = (new UserManager((new UserStore()))).Find(username, password);"
UserManager has UserManager<TUser>.FindByNameAsync method. You can try using it to find user by name.

Impersonate using json credentials file

I have a service account setting up with domain wide delegation to Gsuite domain.
I'd like to impersonate one of the users to be the organizer of a created event.
My code is:
List<String> scopes = new ArrayList<>();
scopes.add(CalendarScopes.CALENDAR);
scopes.add(CalendarScopes.CALENDAR_EVENTS);
InputStream credentialsJSON = Service5.class.getClassLoader()
.getResourceAsStream("credentials.json");
GoogleCredential gcFromJson = GoogleCredential.fromStream(credentialsJSON, HTTP_TRANSPORT, JSON_FACTORY).createScoped(scopes);
GoogleCredential cred = new GoogleCredential.Builder()
.setTransport(gcFromJson.getTransport())
.setJsonFactory(gcFromJson.getJsonFactory())
.setServiceAccountId(gcFromJson.getServiceAccountId())
.setServiceAccountUser("edt#company.tn")
.setServiceAccountPrivateKey(gcFromJson.getServiceAccountPrivateKey())
.setServiceAccountScopes(gcFromJson.getServiceAccountScopes())
.build();
Calendar service = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, cred).setApplicationName(APPLICATION_NAME).build();
Event event = new Event().setSummary("Test");
DateTime startDateTime = new DateTime("2020-04-27T09:00:00.000Z");
EventDateTime start = new EventDateTime()
.setDateTime(startDateTime)
.setTimeZone("Africa/Tunis");
event.setStart(start);
DateTime endDateTime = new DateTime("2020-04-27T10:30:00.000Z");
EventDateTime end = new EventDateTime()
.setDateTime(endDateTime)
.setTimeZone("Africa/Tunis");
event.setEnd(end);
List<EventAttendee> attendees = new ArrayList<EventAttendee>();
EventAttendee ens = new EventAttendee().setEmail("user#company.tn");
attendees.add(ens);
event.setAttendees(attendees);
String calendarId = "primary";
event = service.events().insert(calendarId, event).execute();
But I got that exception:
EDIT - 1
I downloaded the json file resulted from CREATE KEY
Got that exception:
Exception in thread "main"
com.google.api.client.auth.oauth2.TokenResponseException: 401
Unauthorized at
com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
at
com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at
com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at
com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:394)
at
com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:493)
at
com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at
com.google.api.client.http.HttpRequest.execute(HttpRequest.java:880)
at
com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at
com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at
com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at tn.esprit.spring.google.calendar.Service5.main(Service5.java:183)
Could you please tell me what I missed?.
Thanks a lot
To use a service account, you need to create dedicated service accounts credentials
Go to the GCP console
Choose a project
Go on APIs & Services -> Credentials
Choose + CREATE CREDENTIALS -> Service Account
Choose a Service account name and click on Create
If desired, you can select a role (optional)
Click on Create key and select JSON (p12 is also possible, but you will need to build GoogleCredential differently
The correct json file will be downloaded to your computer
It will look as following:
{
"type": "service_account",
...
The json file you were using was not the right one for service accounts, it did not have the field type specified - thus the error 'type' field not specified.

logging in to ableCommerce via commerceBuilder api

i am trying to log in and authenticate with able Commerce?
i am using their DLLs (commerceBuilder)
i have tried
dim user as new commerceBuilder.users.user
user.username = "ABC"
user.password = "PASS"
user.adress = "www.websider.com"
does anyone know how to do this?
AbleCommerce makes use of ASP.NET Forms Authentication with custom membership provider. First validate the user and then if credentials are passed switch context user and set authentication cookie
if (Membership.ValidateUser(username, password))
{
var user = UserDataSource.LoadForUserName(username);
AbleContext.Current.User = user;
FormsAuthentication.SetAuthCookie(user.UserName, false)
}

Google Gmail API - Auth

I already have code which works fine, but for security reason I want to make other way of Auth.
In this case, user writes his username and password, but I want to make like "Allow demo.com to access your information's" click button.
How to change this code:
//Provide Login Information
Google.GData.Client.RequestSettings rsLoginInfo = new Google.GData.Client
.RequestSettings("", txtEmail.Text, txtPassword.Text);
rsLoginInfo.AutoPaging = true;
// Fetch contacts and dislay them in ListBox
Google.Contacts.ContactsRequest cRequest = new ContactsRequest(rsLoginInfo);
Google.GData.Client.Feed<Google.Contacts.Contact> feedContacts = cRequest
.GetContacts();
foreach (Google.Contacts.Contact gmailAddresses in feedContacts.Entries) {
Console.WriteLine("\t" + gmailAddresses.Title);
lstContacts.Items.Add(gmailAddresses.Title);
foreach (EMail emailId in gmailAddresses.Emails) {
Console.WriteLine("\t" + emailId.Address);
lstContacts.Items.Add(" " + emailId.Address);
}
}
It seems like you're trying to do 3-Legged OAuth. .NET samples for performing 3-Legged OAuth 1.0a are documented here:
http://code.google.com/apis/gdata/docs/auth/oauth.html#Examples

Active Directory Authentication

I am have made one web application in asp.net.In my project Authentication was done by matching the username and password in database.But now client ask me for the auto login in application with the help Of Active Directory authentication. Client ask suggest me to use the Email Id of user in AD for the authentication.
I tried to fetch the records in the AD, I could fetch the Fullname of user but I couldn't get the Email id,
I tried the code:
System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
string[] a = Context.User.Identity.Name.Split('\\');
System.DirectoryServices.DirectoryEntry ADEntry = new System.DirectoryServices.DirectoryEntry("WinNT://" + a[0] + "/" + a[1]);
string Name = ADEntry.Properties["FullName"].Value.ToString();
Further more I Use DirectorySearcher but it genterates Error that Coulnot search the record in the client server..
I had the exact same situation while making a portal for a company.
If they dont want you to get into their AD then what you can do is to request for the NTLogins of the people who will be given access to the portal. make a simple table which have their NTLogin and simply authenticate using the system from which the portal is being accessed.
Check out the sample code i used.
// Checking if the user opening this page is listed in the allowed user list against their NT login.
String sUser = Request.ServerVariables["LOGON_USER"].ToLower();
sUser = sUser.Replace("wt\\", "");
//Authentication using a custom auth method.
DatabaseOperations authenticateUser = new DatabaseOperations();
if (!authenticateUser.authenticate(sUser))
{
//unauthorized users will be redirected to access denied page.
Server.Transfer("AccessDenied.aspx", true);
}
And making sure that you have authentication mode to windows in your web.config file
<authentication mode="Windows"></authentication>
Hope this helps.
For reading AD data, i use this class. It is setup for our AD, but basically you can just pass in all the "fields" you want to find, in the params.
But you need to know what field holds the email address. Sysinternals made a pretty good tool for browsing AD, to figure out what you are looking for, called ADExplorer.
But I don't understand why you need to look in the AD? Can you not assume that the user is already authenticated, if they are on the network, and then rely on the windows identity?
public static Hashtable GetAttributes(string initials, params string[] Attribute)
{
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://ADNAME");
DirectorySearcher ADSearcher = new DirectorySearcher(directoryEntry);
ADSearcher.Filter = "(sAMAccountName=" + initials + ")";
foreach (string para in Attribute)
{
ADSearcher.PropertiesToLoad.Add(para);
}
SearchResult adSearchResult = ADSearcher.FindOne();
Hashtable hshReturns = new Hashtable();
foreach (string para in Attribute)
{
string strReturn = "";
if (adSearchResult.Properties[para].Count == 0)
strReturn = "";
else
strReturn = ((ResultPropertyValueCollection)adSearchResult.Properties[para])[0].ToString();
hshReturns.Add(para, strReturn);
}
return hshReturns;
}

Resources