App with no DB: You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class - facebook

First things first. I'm a complete OAuth newbie. This will be my first stab at it, and things are getting hairy...
I'm writing a single page application using Durandal & Web API.
The user needs to be able to login using any social network.
I don't have access to a database whatsoever, I have to call an unprotected 3rd party web service which I consume server-side, and need to protect using OAuth.
So I've managed to add the files to my solution which generates the login using facebook contol/button (created a new MVC4 web application, and did a manual copy and paste of all the auth related files, updated bootstrappers etc..), and the code seems to work for the most part.
When facebook redirects back to
[AllowAnonymous]
public ActionResult ExternalLoginCallback(string returnUrl)
{
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(this.Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
if (!result.IsSuccessful)
{
return this.RedirectToAction("ExternalLoginFailure");
}
if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
{
return this.RedirectToLocal(returnUrl);
}
//code removed for brevity ....
}
I get the error specified once the following line tries to execute.
OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false)
I've removed the [InitializeSimpleMembership] attribute from the controller, as I don't have a database.
Please forgive me if this is the dumbest question ever, but...
Why does the login fail? I mean at that point, isn't the app trying to log into facebook, why does it need a databse? Or am I correct in saying I can remove/replace that code section, with a login/authorise call on the web-service I'm using?

Not the dumbest question ever. Not by a long shot. But you are getting the error because your membership provider is still set to use the SimpleMembershipProvider and OAuthWebSecurity will use the default membership provider. If you don't want to use a database you will have to create or find a different membership provider to use.
EDIT:
I know you said you don't have access to a DB but if you can use SQL Compact you can just stick with the default SimpleMembershipProvider(check out Hanselman's blog) or DevArt has a SQLLite provider. Also the MemFlex Project has a RavenDb provider. If none of those work I think you might just have to write your own.

Related

.HttpContext.User is null after successful login from SAML Identity Provider?

Trying to retrofit an old webforms application.
Got my configuration working so that it's prompting for login and successfully redirecting back to the application. The folks that manage the IP can see the response is generated.
However in the callback to my application the User is null. I'm told if it's configured correctly it should be populated.
We have a custom IHttpModule and that is where I can see getting hit with the call to /Saml2/Acs with the User not populated. I think this may be expected as the handler for that is supposed to populate the User, I think? However the following call (the returnUrl configured in sustainsys.Saml2) still has no User and I don't see any sort of error or anything.
Anyone with experience have an idea how to debug this?
The call to /Saml2/Acs should be taken care of by the Sustainsys.Saml2.HttpModule. It will process the response and then call the SessionAuthenticationModule to set a cookie that preservers the User across calls.
To get some more information about what's happening in the library, you can assign an implementation of ILoggerAdapter to Sustainsys.Saml2.Configuration.Options.FromConfiguration.SPOPtions.Logger to get some logging output from the library.
My issue turned out to be that I had another authentication module loaded before SessionAuthenticationModule and Saml2AuthenticationModule in the web config.
The comment in the example was
Add these modules below any existing. The SessionAuthenticatioModule
must be loaded before the Saml2AuthenticationModule
However in my case with I had another authentication module involved that needed to go last.

How to use new enhanced sessions in Parse with users created on cloud code?

I was trying out the new enhanced revocable sessions in Parse on my Android app. It works well when logging in or signing up via email password or facebook but doesn't work well for custom authentication, e.g. google+.
I'm currently logging in the user using the cloud code which also creates the new user when signing up. This does not create a new Session object, that means the new enhanced sessions are not used and it still uses the legacy sessions.
I pass the session token back to client where using the become method the user logs in but it's the legacy sessions.
This feels like the feature is not complete but I would really like to move to the new enhanced sessions with my app. Has anyone worked with them yet? Are there any workarounds using the REST API or by creating the sessions manually and handling them manually? I looked into the JS API but it says it's only read only.
Here's the Blog post on Enhanced Sessions.
Where should I go next?
Yes, I found a solution but it's a workaround, works for my case because I don't support signing up with user/password.
Basically, the solution (cloud code) in semi pseudo-code is:
Fetch the user with master key
Check if user.getSessionToken() has value
if it has, return the session token and do a user.become() in the client as usual
if it's not, here the workaround, do the following:
yourPreviousPromiseInOrderToChainThem.then(function(user)
password = new Buffer(24);
_.times(24, function(i) {
password.set(i, _.random(0, 255));
});
password = password.toString('base64')
user.setPassword(password);
return user.save();
}).then(function(user) {
return Parse.User.logIn(user.get('username'), password)
}).then(function(user) {
var sessionToken = user.getSessionToken();
// Return the session token to the client as you've been doing with legacy sessions
})
That means, I'm changing the user password each time in order to make a remote login and, of course, I know thist can't be applied to all cases, it's enough for app because I don't support login with user/password (only third party logins) but I understand that maybe it's not for all cases.
I got the idea from this official Parse example.
I don't like this solution because I think is not a workaround, it's a mega hack but I think there is no other way to do it currently (either Parse.com or Parse-Server)
If you find other workaround, please, share it :)

How to prevent from user to delete all the data when using backbone.js

Lets suppose that I have some web app that using backbone.js in the client side, and on the server side some RESTful API that support the DELETE method.
The database of the app contains some categories and posts, and on the client side I have collection that called "categories" that using fetch() to retrieve all the categories from the server using GET method.
How can I prevent from any user to just open his console in chrome or firebug in Firefox, explore my JavaScript files, figuring the structure of my backbone models and just run collections.destroy() from his console and delete all my database....
Am I missing something here?
I've googled it but didn't find an answer...
You have to put up some validation on your server side since you cannot trust what came from the client.
For example you could write some security checks that run before execute the database's calls, like these (PHP pseudo-code):
$model = Posts;
if($model->checkUserRights('read')) {
$model = Posts->findById($_GET['id']);
echo json_encode($model);
} else {
echo "You have not the require rights to access ".$model->tableName;
}
And in Posts's model:
public function checkUserRights($op){
// Run some code for each possible operations's type
}
You could also add some rules to filter the values you will return to the clients or the values they will post to your server, before process an update request.
It's really up to you and what technology you will use on your server.
You can easily prevent this on the server side by not doing anything when the DELETE method is received from the client.
If you're using rails, your delete method would look like this
def destroy
#not allowing deletions through the REST api
end

ASP.NET Web API Authorization with AuthorizeAttribute

Using the new ASP.NET Web API beta. I can not seem to get the suggested method of authenticating users, to work. Where the suggested approach seems to be, to add the [Authorize] filter to the API controllers. For example:
[Authorize]
public IEnumerable<Item> Get()
{
return itemsService.GetItems();
}
This does not work as intended though. When requesting the resource, you get redirected to a login form. Which is not very suitable for a RESTful webapi.
How should I proceed with this? Will it work differently in future versions?, or should I fall back to implementing my own action filter?
Double check that you are using the System.Web.Http.AuthorizeAttribute and not the System.Web.Mvc.AuthorizeAttribute. This bit me before. I know the WebAPI team is trying to pull everything together so that it is familiar to MVC users, but I think somethings are needlessly confusing.
Set your authentication mode to None:
<authentication mode="None" />
None Specifies no authentication. Your application expects only anonymous users or the application provides its own authentication.
http://msdn.microsoft.com/en-us/library/532aee0e.aspx
Of course then you have to provide some sort of authentication via headers or tokens or something. You could also specify Windows and use the built in auth via headers.
If this site is mixed between API and actual pages that do need the Forms setting, then you will need to write your own handling.
All the attribute does is return an HttpUnauthorizedResult instance, the redirection is done outside of the attribute, so its not the problem, its your authentication provider.
Finally, I've found a solution at:
ASP.NET MVC 4 WebAPI authorization
This article shows how you can fix this issue.
You are being redirected to login page because forms authentication module does this automatically. To get rid of that behavior disable forms authentication as suggested by Paul.
If you want to use more REST friendly approach you should consider implementing HTTP authorization support.
Take a look at this blog post http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-membership-provider/
ASP.NET 5 Introduced the new Microsoft.AspNet.Authorization System which can secure both MVC and Web API controllers.
For more see my related answer here.
Update:
At that time 2 years ago it was Microsoft.AspNetCore.Authorization.
As #Chris Haines pointed out. now it resides on
Microsoft.AspNetCore.Authorization.
From .NET core 1.0 to 2.0 many namespaces have been moved i think.
And spread functionality between .net classic and core was obscure.
That's why Microsoft introduced the .net standard.
.net standard
Also, look at my answer for:
How to secure an ASP.NET Web API
There is a NuGet package I have created which you can use for convenience.
If you're using a Role, make sure you have it spelled correctly :
If your role is called 'Administrator' then this - for instance will not work :
[System.Web.Http.Authorize(Roles = "Administator")]
Neither will this :
[System.Web.Http.Authorize(Roles = "Administrators")]
Oops...
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Produces("application/json")]
[Route("api/[controller]")]
public class CitiesController : Controller
{
[HttpGet("[action]")]
public IActionResult Get(long cityId) => Ok(Mapper.Map<City, CityDTO>(director.UnitOfWork.Cities.Get(cityId)));
}
Use
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
Filter with authentication type

Impersonating user with Entity Framework

So we have our web app up and going with entity framework. What we'd like to do is impersonate the current user when we're accessing the DB. We're not interested in setting impersonation up in our web config.
Ideally using something like this: Link when we're about to access data.
UPDATED: I'm looking for a way to abstract this code out so I don't have to have it in every repository function call.
Your EF connection string is going to need to be set up for using a trusted connection.
You won't need to set up Impersonation in your web.config, but you do need to be using Windows Authentication.
Then just do this:
using (((WindowsIdentity)HttpContext.Current.User.Identity).Impersonate())
using (var dbContext = new MyEntityFrameworkContainer())
{
...
}
Any code inside the curly braces of the using statements will run as the authenticated user.