Facebook OAuth + AppHarbor workaround on random port - asp.net-mvc

I a have a sample app, hosted on AppHarbor and now want to integrate authorization through facebook. So i downloaded nugget Facebook.Web.Mvc package to implement it.
After reading tutorial, in controller i have method:
public ActionResult Login(string returnUrl)
{
var oauthClient = new FacebookOAuthClient(FacebookApplication.Current) { RedirectUri = GetFacebookRedirectUri() };
if (!string.IsNullOrWhiteSpace(returnUrl))
{
returnUrl = Url.Action("Index", "Facebook");
}
dynamic parameters = new ExpandoObject();
parameters.scope = ExtendedPermissions;
var state = new { csrf_token = CalculateMD5Hash(Guid.NewGuid().ToString()), return_url = returnUrl };
parameters.state = Base64UrlEncode(Encoding.UTF8.GetBytes(JsonSerializer.Current.SerializeObject(state)));
SetFacebookCsrfToken(state.csrf_token);
string s = oauthClient.GetLoginUrl(parameters).AbsoluteUri;
ViewBag.FacebookLoginUrl = s;
//new LogEvent(s).Raise();
return View(new AccountModel());
}
View:
<a href="#ViewBag.FacebookLoginUrl" id="lUrl">
<div class="fblogin"></div>
In localhost this works for me.
But when i upload it to appharbor, i see, that generated link indicates to address + port 16013 (as support told always random port). So clicking it shows me facebook login window, than blank page.
I manually configured my app settings in facebook to this port but it did not helped.
Also i tried to access my site through this port - nothing.
Then i changed port number through jquery to 80, its also did not help.
you have had such problems?

I'm not familiar with the Facebook api, but I've had a similar problem.
I suspect that the returnUrl value being passed in is incorrect. It probably contains a port number that AppHarbor uses internally for load balancing.
See this article on how to create a public url for AppHarbor:
http://support.appharbor.com/kb/getting-started/workaround-for-generating-absolute-urls-without-port-number
Then make sure that the value in your returnUrl is publicly available.

You can now set the aspnet:UseHostHeaderForRequestUrl appSetting to true which effectively solves this problem. This can be done by adding a Configuration Variable to your application with the corresponding key and value.
Source on AppHarbor

Related

Sustainsys SAML2 Sample for ASP.NET Core WebAPI without Identity

Does anyone have a working sample for Sustainsys Saml2 library for ASP.NET Core WebAPI only project (no Mvc) and what's more important without ASP Identity? The sample provided on github strongly relies on MVC and SignInManager which I do not need nor want to use.
I added Saml2 authentication and at first it worked fine with my IdP (I also checked the StubIdP provided by Sustainsys) for first few steps so:
IdP metadata get properly loaded
My API properly redirects to sign-in page
Sign-in page redirects to /Saml2/Acs page, and I see in the logs that it parses the result successfully
However I don't know how to move forward from there and extract user login and additional claims (my IdP provided also an e-mail, and it is included in SAML response which I confirmed in the logs).
Following some samples found on the web and modyfing a little bit the MVC Sample from GitHub I did the following:
In Startup.cs:
...
.AddSaml2(Saml2Defaults.Scheme,
options =>
{
options.SPOptions.EntityId = new EntityId("...");
options.SPOptions.ServiceCertificates.Add(...));
options.SPOptions.Logger = new SerilogSaml2Adapter();
options.SPOptions.ReturnUrl = new Uri(Culture.Invariant($"https://localhost:44364/Account/Callback?returnUrl=%2F"));
var idp =
new IdentityProvider(new EntityId("..."), options.SPOptions)
{
LoadMetadata = true,
AllowUnsolicitedAuthnResponse = true, // At first /Saml2/Acs page throwed an exception that response was unsolicited so I set it to true
MetadataLocation = "...",
SingleSignOnServiceUrl = new Uri("...") // I need to set it explicitly because my IdP returns different url in the metadata
};
options.IdentityProviders.Add(idp);
});
In AccountContoller.cs (I tried to follow a somewhat similar situation described at how to implement google login in .net core without an entityframework provider):
[Route("[controller]")]
[ApiController]
public class AccountController : ControllerBase
{
private readonly ILog _log;
public AccountController(ILog log)
{
_log = log;
}
[HttpGet("Login")]
[AllowAnonymous]
public IActionResult Login(string returnUrl)
{
return new ChallengeResult(
Saml2Defaults.Scheme,
new AuthenticationProperties
{
// It looks like this parameter is ignored, so I set ReturnUrl in Startup.cs
RedirectUri = Url.Action(nameof(LoginCallback), new { returnUrl })
});
}
[HttpGet("Callback")]
[AllowAnonymous]
public async Task<IActionResult> LoginCallback(string returnUrl)
{
var authenticateResult = await HttpContext.AuthenticateAsync(Constants.Auth.Schema.External);
_log.Information("Authenticate result: {#authenticateResult}", authenticateResult);
// I get false here and no information on claims etc.
if (!authenticateResult.Succeeded)
{
return Unauthorized();
}
// HttpContext.User does not contain any data either
// code below is not executed
var claimsIdentity = new ClaimsIdentity(Constants.Auth.Schema.Application);
claimsIdentity.AddClaim(authenticateResult.Principal.FindFirst(ClaimTypes.NameIdentifier));
_log.Information("Logged in user with following claims: {#Claims}", authenticateResult.Principal.Claims);
await HttpContext.SignInAsync(Constants.Auth.Schema.Application, new ClaimsPrincipal(claimsIdentity));
return LocalRedirect(returnUrl);
}
TLDR: Configuration for SAML in my ASP.NET Core WebApi project looks fine, and I get success response with proper claims which I checked in the logs. I do not know how to extract this data (either return url is wrong or my callback method should work differently). Also, it is puzzling why successfuly redirect from SSO Sign-In page is treated as "unsolicited", maybe this is the problem?
Thanks for any assistance
For anyone who still needs assistance on this issue, I pushed a full working example to github which uses a .Net Core WebAPI for backend and an Angular client using the WebAPI. you can find the example from here:
https://github.com/hmacat/Saml2WebAPIAndAngularSpaExample
As it turned out, the various errors I've been getting were due to my solution being hosted inside docker container. This caused a little malfunction in internal aspnet keychain. More details can be found here (docker is mentioned almost at the end of the article):
https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?tabs=aspnetcore2x&view=aspnetcore-2.2
Long story short, for the code to be working I had to add only these lines:
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo("/some/volume/outside/docker")); // it needs to be outside container, even better if it's in redis or other common resource
It fixed everything, which includes:
Sign-in action to external cookie
Unsolicited SSO calls
Exceptions with data protection key chain
So it was very difficult to find, since exceptions thrown by the code didn't point out what's going on (and the unsolicited SSO calls made me think that the SSO provider was wrongly configured). It was only when I disassembled the Saml2 package and tried various code pieces one by one I finally encoutered proper exception (about the key chain) which in turned led me to an article about aspnet data protection.
I provide this answer so that maybe it will help someone, and I added docker tag for proper audience.

ASP.Net MVC application access to other servers

We have an ASP.Net MVC application (website), just a straight web app. The URL it needs to connect to is an ASP.Net WebAPI2 web service on port 14015. The MVC application is calling the Web service anonymously using a WebClient class; the web service is secured by limiting which IPs can connect to it. There is no authorization mode to access except by IP.
using (WebClient client = new WebClient())
{
//****************************
// We make the web service call like this:
//****************************
string url = #"http://secure.example.com:14015/lms/SSOKey/1158341";
string key = client.DownloadString(url);
//****************************
// Then we append the returned key to build the full URL. This URL is used
// in the View to build a link button.
//****************************
string login_url = #"http://192.168.1.1/tc/login.do?uid=" + key;
login_url = login_url.Replace("\"", string.Empty);
//****************************
// Pass the URL to the view to build the link button
//****************************
ViewBag.LoginURL = login_url;
}
I can access the URL from a browser on the server where the MVC application is published, however, the call is unsuccessful. Any ideas how I may find out why this won't connect??
If you are calling the code inside of a controller and the users have to logon to your web app, than this code should give you what you need:
string currentUser = User.Identity.Name;
If your users use your web app anonymously currentUser will be blank.
Adding this code solved the problem.
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
Since we limit access by IP Addresses, very low security risk.

Get Error (error=access_denied) while logging in MVC5 application with facebook SDK

I have developed an application with ASP.NET MVC5. I have used Facebook external authentication in my application.
When I debug this application with the "Locallhost" domain, the Facebook login works well but when I publish the application in the main server,the AuthenticationManager.GetExternalLoginInfo() returns null and it gives me an error like this in the url:
http://xxxxx.com/Account/ExternalLoginCallback?ReturnUrl=%2Fen&error=access_denied#_=_
I have set the "Site URL" as "http://xxxx.com" and "Valid OAuth redirect URIs" as "http://xxxx.com/signin-facebook" in the Facebook development console.
My setting in the Startup.Outh.cs file is:
var FacebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions();
FacebookOptions.AppId = ConfigurationManager.AppSettings["Facebook_User_Key"];
FacebookOptions.AppSecret = ConfigurationManager.AppSettings["Facebook_Secret_Key"];
FacebookOptions.Provider = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationProvider()
{
OnAuthenticated = async context =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
foreach (var claim in context.User)
{
var claimType = string.Format("urn:facebook:{0}", claim.Key);
string claimValue = claim.Value.ToString();
if (!context.Identity.HasClaim(claimType, claimValue))
context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
}
}
};
FacebookOptions.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
app.UseFacebookAuthentication(FacebookOptions);
I don't know why the external login does not work only in the server with my main domain name. please help me about this problem.
I encountered pretty much the same symptoms you describe:
shortly:
A Facebook authentication worked well on localhost, and after uploading the project to another server (and changing the site URL on Facebook console), authentication did not succeed.
I would recommend you roll back to the MVC template code, and if that works - notice any changes you have made to the middleware code (Startup.Auth.sc).
In particular pay attention to code that interacts with LOCAL configuration, such as Disk I/O and OS permissions for local services.
My particular case:
Starting from the Owin/Katana supported Visual Studio template of a WebAPI project, external login was working perfectly with Facebook, Microsoft and Google OAuth middleware, when testing on localhost.
Later I added come code to Startup.Auth.sc because I needed further authentication activity.
So this was the original code:
public void ConfigureAuth(IAppBuilder app)
{
// see WebAPI template of Visual Studio 2013/2015
...
app.UseFacebookAuthentication(
appId: 99999999,
appSecret: *******);
}
and this was replacement:
public void ConfigureAuth(IAppBuilder app)
{
// see WebAPI template of Visual Studio 2013/2015
...
app.UseFacebookAuthentication(GetFacebookAuth());
}
private FacebookAuthenticationOptions GetFacebookAuth()
{
string picRequest =
String.Format("/me/picture?redirect=false&width={0}&height={0}", ProfileInfoClaimsModel.PIC_SIDE_PX);
var facebookProvider = new FacebookAuthenticationProvider()
{
OnAuthenticated = async (context) =>
{
var client = new FacebookClient(context.AccessToken);
dynamic me = client.Get("/me?fields=id,name,locale");
dynamic mePicture = client.Get(picRequest);
// storing temporary social profile info TO A LOCAL FOLDER
// uploading the local folder to a service WITH A LOCAL CREDENTIAL FILE
...
}
};
var options = new FacebookAuthenticationOptions()
{
AppId = 0123456789,
AppSecret = ******,
Provider = facebookProvider,
};
return options;
}
You may notice that my comments will make the problem obvious - the code points to local resources.
Then I published the project to a virtual server (by Amazon EC2) running Windows Server 2012 with IIS 8.5.
From that moment I kept getting error=access_denied in the redirect from /signin-facebook.
I decided to follow this good old concept, and go back to the original template code. Pretty soon I figured out that I forgot to configure the new server. For instance, the folder the code refers to did not exist and the site had no permission to create it.
Obviously, that solved it.

asp.net identity 2.1 google authentication

I'm using trying to use Google authentication in an ASP.NET MVC application.
For testing purposes I'm using the template app generated by VS2013 Update 4
In Google settings the return URLs are properly set and Google+ API is turned on. The app works fine when I publish it to an azure website. I can login using Google accounts without any problems.
However I'd like to deploy it on premises but here we have a reverse proxy setup which works like this:
the server sees itself as server01.mysite.com but this is an
internal name
outside world sees it as www.mysite.com (certain paths are
reverese proxied to the server01.mysite.com
Essentially www.mysite.com/myapp is reverse proxied to server01.mysite.com/myapp
With this setup I can't seem to use Google authentication. GetExternalLoginInfoAsync returns null and the app redirects itself to the login page.
By default the system generates a redirectUri using the private hostname. I tried changing it to the public address but this does not solve the problem.
Below is what I did at startup.auth.cs
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
ClientId = "...",
ClientSecret = "...",
Provider = new GoogleOAuth2AuthenticationProvider
{
OnApplyRedirect = context =>
{
var redirectUri = context.RedirectUri.Replace("server01", "www");
context.Response.Redirect(redirectUri);
},
}
});
Is there anyway I can make Google authentication work in a setup like this?
Thanks
To achieve this one has to tell the app to use the outside URL earlier so that the relevant hashes are built taking that into account. So instead of changing the redirect URI at the OnApplyRedirect call this before UseGoogleAuthentication:
app.Use((context, next) =>
{
context.Request.Host = new HostString(
context.Request.Host.Value.Replace("server01", "www"));
return next();
}
);
and remove the Provider=... from UseGoogleAuthentication
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
ClientId = "...",
ClientSecret = "..."
});

ASP.NET MVC Facebook

I am trying to do a seemingly simple thing, but having trouble accomplishing it. I am trying to automate the posting on my Facebook wall. Basically I have a ASP.NET MVC website that I post updates on, and I want to automatically submit the post to my wall.
I see a lot of stuff on FB Connect and getting data, I just want to post.
Thanks for any help or guidance.
UPDATE: Just trying to resurrect and be a little more clear in my description as I am not getting anywhere.
I have a page that I want with a text box and a button. When I submit the form I want the message to post to my Facebook wall. I thought it was Facebook Connect, but I am getting no where as to how to automatically authenticate myself and post to my wall.
I would like to use C# rather than JavaScript.
private const string ApplicationKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
private const string SecretKey = "XXXXXXXXXXXXXXXXXXXXXXXXXX";
private Facebook.Rest.Api _facebookAPI;
private Facebook.Session.ConnectSession _connectSession;
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection form)
{
_connectSession = new Facebook.Session.ConnectSession(ApplicationKey, SecretKey);
if (_connectSession.IsConnected())
{
_facebookAPI = new Facebook.Rest.Api(_connectSession);
string response = _facebookAPI.Stream.Publish("This is a generated test");
}
return View();
}
}
The IsConnected() is returning false.
Any help is appreciated.
This code was right, the problem was that I had not added my application to my profile. Dumb miss, but my thought is that the whole thing is poorly documented. I have another issue with offline access, but that is for a different post.
string apiKey = "XXXXXXXXX";
string apiSecret = "XXXXXXXXXXXX";
Facebook.Session.ConnectSession._connectSession = new Facebook.Session.ConnectSession(apiKey, apiSecret);
if (_connectSession.IsConnected)
{
Facebook.Rest.Api api = new Facebook.Rest.Api(_connectSession);
string response = api.Stream.Publish("Test", null, null, null, api.Users.Session.UserId);
}
It could be that you tested your Website on your localhost. The Facebook Cookie is not written out, when you test your Website on localhost. See this link http://forum.developers.facebook.net/viewtopic.php?pid=247332
This might solve your problem:
Add "127.0.0.1 localhost.local" to your file
Update your FB application Connect settings to use "http://localhost.local/" URL and "localhost.local" domain.
Create an IIS Web site on port 80 with the name "localhost.local". I had to stop my default web site, which is also on port 80
Update my Visual Studio 2010 web application to use IIS with the "http://localhost.local/" url.
To see cookies, make sure to install FireCookies, along with FireBug.

Resources