Using the facebook c# sdk in asp.net without a canvas application - asp.net

Im trying to use the sdk without a canvas application, so have followed steps 1-7 in the quickstart guide up to adding the facebookSettings property in the Web.config.
I have added an image to my page and an onclick event that contains the below code. but when I click the button, it just takes me to the home page (CancelUrlPath).
Changing the Authorizer to a CanvasAuthorizer results in FB loading the login screen, but I get an error 404 not found on the call (even after inserting the handlers into the config)..
fbApp = new FacebookApp();
authorizer = new Authorizer(fbApp) {Perms = requiredAppPermissions};
authorizer.ReturnUrlPath = "http://localhost/User/UserRegister.aspx";
authorizer.CancelUrlPath = "http://localhost/";
if (authorizer.Authorize(this.Context))
{
Response.Write("hello");//never gets here
}
Can anyone help please?
Note: I've set the canvas and site url to http://localhost/ on the FB app settings.

If you are just building a simple connect website you really don't want to use the server side authentication tools to authenticate your user. Just use the Javascript SDK to athenticate the user. If you need to do anything on the server side, the FacebookApp class will automatically pick up the user's session from the values stored in the cookies.
See the Facebook documentation for more details: http://developers.facebook.com/docs/guides/web/#registration

Related

Close browser window with specific url (opened by different browser)

I am doing an application where when the user click on social login it opens a new window. Let's say my application is running on Chrome and my default browser was set to Edge; the URL is getting opened in Edge. After successful token generation it is redirecting to the application without closing the browser window/tab.
I am using azure AD authentication as follows
IPublicClientApplication app = PublicClientApplicationBuilder
.Create(azMapping.ClientId)
.WithAuthority(authority)
.WithRedirectUri("http://localhost:44342/Default.aspx")
.Build();
result = app.AcquireTokenInteractive(scopes)
.WithSystemWebViewOptions(new SystemWebViewOptions())
.ExecuteAsync(CancellationToken.None)
.GetAwaiter().GetResult();
The authority URL opens in the default browser. Is there a way to open the URL on the application running or can we close once we got back the response?
You can use the destinationpageurl property
The DestinationPageUrl property specifies the page that is displayed when a login attempt is successful.
Or
You can use the JavaScript to achieve this window.location.href returns the href (URL) of the current page
Response.Redirect should work if you just want to navigate to the same window page.
refer here for Open url in same window
You can have a look to how to handle it see here

Tabs opened via Hyperlinks in Excel/Word not recognizing session cookies

I have an ASP.Net application with authentication using Cookie session variables. Once the user logs in, they can open new browser tabs for the same application and these are logged in automatically as the session cookie is present.
Clicking on a hyperlink on another web page pointing to a specific page within the application also works fine - there is no login required as the user is already logged in.
However, when a hyperlink to the application is in a Word/Excel document, this link does not open the page directly and gets bounced to the Login page instead. If I copy/paste the Url from Word/Excel and paste it in the Url bar on the browser, it works fine.
Any explanation to this behaviour? Does the browser open a isolated session when a link is clicked in Word/Excel?
Edit: It also seems Word/Excel perform their own check before opening a browser tab. If I use a non-existent link, it doesn't open the tab.
We ran into this at my place of work a while back, and found that like you mentioned, MS Office applications indeed do some mysterious stuff behind the scenes. Details on what it actually does are in this article: https://learn.microsoft.com/en-us/office/troubleshoot/office-suite-issues/click-hyperlink-to-sso-website
Toward the bottom of that article, they suggest a workaround involving a meta refresh, which is what worked for us. In our case, we added a method to our request pipeline that checks for a Microsoft product in the User-Agent header. If found, it sends a meta refresh that triggers the browser to use an existing session rather than trying to start a new session (which is why you're being redirected to a logon page). Here's more or less the code:
private static string MSUserAgentsRegex = #"[^\w](Word|Excel|PowerPoint|ms-office)([^\w]|\z)";
protected void Application_OnPostAuthenticateRequest(object sender, EventArgs e)
{
if (!Request.IsAuthenticated)
{
if (System.Text.RegularExpressions.Regex.IsMatch(Request.UserAgent, MSUserAgentsRegex))
{
Response.Write("<html><head><meta http-equiv='refresh' content='0'/></head><body></body></html>");
Response.End();
}
}
}

in Xamarin/App how do I Secure Files on ASP.NET Restful Server in folders from other users and general public

I have an APP using restful server. I want to store PDF's, images, etc. in folders on my server. How can I make the folders private on server, yet allow App to access only certain folders depending on their app access.
I have different users in app and security/tokens established, etc. But if they upload an image for their avatar (and now PDF's), they get stored in folders on the server, and I just display with image source=https://blahblah.com/org1/images/user232.jpg.
How can I make that not accessible to outside (like just going to browser), yet make accessible to app if they have correct login privilege's for that organization/user? And then further extend that logic to more sensative PDF's, and other docs uploaded through app. I didn't want to store in SQL since then harder to use simple image display tools and I already have upload and media managers using folders structures.
I can see how to secure if logging onto server through browser (credentials), but can't see how you connect App with that security level and maintain it for the session.
For future readers. Most of the work was done on the restful (ASP.NET) side. I first tried using authorization/Authentication in web.config and having Allow and deny. This allowed a redirect of a user to a login page; however, it didn't do it if they entered an image exactly correct on website.
Found HTTPHandlers (adding in webconfig ) where I could write code that would be executed once the user entered the specific Image address xyz/abc/image.png. I found this a bit feeling like a hack.
So lastly modified my
routes.MapRoute(
name: "staticFileRoute",
url: "publicstor/{*file}",
defaults: new { controller = "Home", action = "HandleStatic" }
And add a function like this to home controller.
[System.Web.Http.HttpGet]
public ActionResult HandleStatic(string file)
{
if (Session["OrgId"] == null) //todo need to add full security check.
{
return View("Login");
}
else //Either coming from app or coming from web interface
{
string mimeType = MimeInfo.GetMimeType(Path.GetExtension(file));
return File(file, mimeType);
}
}
The final bit is on the Xamarin side to now pass security when getting an image. Since just a simple Xamarin.Forms.Image doesn't have a way to pass login info or tokens/authentication I used
https://forums.xamarin.com/discussion/145575/image-from-url-needing-auth
And established an appwide webclient that logged in generally once forcing my restful to go through security validation, then just accessed the images/documents through out my app from that webclient. So far so good. Hopefully there are no holes.
This gives the gist to a future reader.

Xamarin Forms Azure App Service ADAL Logout not working as expected

We are currently writing a Xamarin Forms Azure Mobile application, using client flow, AAD authentication, refresh tokens etc.
Most of this is working as expected. However, logging out of the application does not work properly. It completes the logout process for both Android and iOS - but upon redirection to the login screen, hitting sign in will never prompt the user with the Microsoft login as expected, it will sign them straight back into the app.
To add a little bit of background, this app has been implemented as per Adrian Hall's book,
current link: https://adrianhall.github.io/develop-mobile-apps-with-csharp-and-azure/
with the above described options and configurations.
I have also read through the 30 days of Zumo (also by Adrian Hall) blog on this, and every single post I can find on here relating to this.
My current logout code is as follows:
public async Task LogoutAsync()
{
var loginProvider = DependencyService.Get<ILoginProvider>();
client.CurrentUser = loginProvider.RetrieveTokenFromSecureStore();
var authUri = new Uri($"{client.MobileAppUri}/.auth/logout");
using (var httpClient = new HttpClient())
{
if (IsTokenExpired(client.CurrentUser.MobileServiceAuthenticationToken))
{
var refreshed = await client.RefreshUserAsync();
}
httpClient.DefaultRequestHeaders.Add("X-ZUMO-AUTH", client.CurrentUser.MobileServiceAuthenticationToken);
await httpClient.GetAsync(authUri);
}
// Remove the token from the cache
loginProvider.RemoveTokenFromSecureStore();
//Remove the cookies from the device - so that the webview does not hold on to the originals
DependencyService.Get<ICookieService>().ClearCookies();
// Remove the token from the MobileServiceClient
await client.LogoutAsync();
}
As far as I can tell, this includes everything I have found so far - i.e. calling the /.auth/logout endpoint, removing the token locally, clearing the cookies from the device (as we log in inside a webview) and lastly calling the LogoutAsync() method from the MobileServiceClient.
Am I missing anything? Or is there a way we can force log out from this environment? As I know you can't "invalidate" an OAuth token, you have to wait until it expires - but to my mind, the /.auth/logout endpoint is supposed to handle this within the Azure environment? Though I'm just not sure to what extent.
Any help is appreciated.
We are currently writing a Xamarin Forms Azure Mobile application, using client flow, AAD authentication, refresh tokens etc. Most of this is working as expected. However, logging out of the application does not work properly.
I assumed that if you use the server flow for logging with AAD, the logout processing may works as expected. As you described that you used client flow, since you have clear the client cache for token, I assumed that the issue may caused by the LoginAsync related (ADAL part) logic code, you need to check your code, or you could provide the logging related code for us to narrow this issue.

WIF cross-domain on one IIS site, dynamically setting of realm

We have a lot of domains running on one IIS WebSite/AppPool.
Right now we are in the process of implementing SSO with Windows Identity Foundation.
in web.config the realm has to be set with
<wsFederation passiveRedirectEnabled="true" issuer="http://issuer.com" realm="http://realm.com" requireHttps="false" />
My problem is that the realm is dependent on which domain the user accessed the website on
so what I did is that I set it in an global action filter like this
var module = context.HttpContext.ApplicationInstance.Modules["WSFederationAuthenticationModule"] as WSFederationAuthenticationModule;
module.Realm = "http://" + siteInfo.DomainName;
My question is. When I set the realm like this, is it set per user instance
or application instance.
Scenario.
User A loads the page and the realm get set to domain.a.com.
User B is already logged in on domain.b.com and presses login.
Since user A loaded the page before User B pressed login, user A will hit the STS
with the wrong realm set.
What will happen here?
If this is not the way to set the realm per user instance, is there another way to do it?
I have already solved the problem.
I set PassiveRedirectEnabled to false in web.config
I set up the mvc project to use forms authentication, eventhough I dont.
I do that so that I will get redirected to my login controller with a return url everytime a controller with [Authorize] is run.
In my login controller I do
var module = HttpContext.ApplicationInstance.Modules["WSFederationAuthenticationModule"] as WSFederationAuthenticationModule;
module.PassiveRedirectEnabled = true;
SignInRequestMessage mess = module.CreateSignInRequest("passive", returnUrl, false);
mess.Realm = "http://" + Request.Url.Host.ToLower();
HttpContext.Response.Redirect(mess.WriteQueryString());
This is definitely not really how it should be, for me it feels like Windows Identity Foundation is lagging behind, both in documentation and microsoft technology wise, no examples for MVC.
For other MVC people i recommend them to not use the fedutil wizard, and instead write the code and configuration themself

Resources