Is there a way to capture the LogIn event on SustainSys.Saml2 - sustainsys-saml2

In an ASPNet Webapplication, we currently use Sustainsys.Saml2 for our authentication against Okta.
This works well, however we would like to keep track of our users-login's inside the application.
So far we tried multiple eventhandlers HttpApplication.PostAuthenticateRequest, or the events on SessionAuthenticationModule but we cant seem to find the spot to capture the event.
Solution is ASP.Net MVC 5, with framework 4.7.2 and SustainSys.Saml2 1.0.2, with the Identitymodel implementation.
Any thoughts on this, apart from 'Upgrade' ?
TIA
I ended up with using the AcsCommandResultCreated.
For future reference, i added this to Application_Start :
// Capture the Login Event
Sustainsys.Saml2.Configuration.Options.FromConfiguration.Notifications
.AcsCommandResultCreated = (commandResult, response) =>
{
var username = commandResult.Principal.FindFirst(c => c.Type ==
ClaimTypes.NameIdentifier).Value;
System.Diagnostics.Debug.Write($"{username} logged in at {DateTime.Now}");
};

Use the AcsCommandResultCreated notification. The name is maybe not that clear, but it is called right after the Saml2 message is validated and before the call to the ?SessionAuthenticationModule

Related

Asp .Net Core 5 Identity - How to fetch a user?

In the new SPA (react and angular) web templates for .Net core 5. I'd like to fetch the current logged in User. However, when I try to get a user in the controller the User doesn't have anything populated.
Does anyone know how to achieve this with the new Identity Classes?
I've made a repo of the vanilla reactJS template, the only thing I changed is the line highlighted in my screenshot below to show there's no user set.
I've done a bit of googling and these pages are all I could find on the topic, unfortunately, they don't give enough detail for me to be able to implement anything practical.
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-api-authorization?view=aspnetcore-5.0
https://learn.microsoft.com/en-us/aspnet/core/security/authorization/claims?view=aspnetcore-5.0
Backend:
ClaimsPrincipal currentUser = this.User;
var currentUserName = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
ApplicationUser user = await _userManager.FindByNameAsync(currentUserName);
On the frontend if you need yo access it
//with UserManager
UserManager<ApplicationUser> UserManager
#{
var user = await UserManager.GetUserAsync(User);
}
// with SignInManager
SignInManager<ApplicationUser> SignInManager
#if (SignInManager.IsSignedIn(User))
To answer my own question.
In order to populate the User detail in the HttpContext you have 1 of 2 routes. Either change
services.AddDefaultIdentity<IdentityUser>();
to
services.AddIdentity<IdentityUser, IdentityRole>();
or you can continue to use the Core Identity
services.AddIdentityCore<IdentityUser>();
but then you also need to implement your own Microsoft.AspNetCore.Identity.ISecurityStampValidator and add it as transient services.AddTransient<ISecurityStampValidator, MyValidator>();
Your MyValidator implementation will be responsible for validating the cookie. You can see the default implementation here on github
Edit: Under the hood services.AddDefaultIdentity<IdentityUser>(); uses services.AddIdentityCore<IdentityUser>();. I feel like its importatnt to know this.

handling the The CSRF token in symfony's forms when in public REST context

I'm developer my first symfony (3) app. it is a REST service publicly accessible.
I'm doing this using FOSRestBundle.
I'll have to ad some admin forms soon or later, and I'll probably want to create them directly (without passing by the extra work of consuming my own web services)
I wonder how to handle the CSRF token in this case. I see different solutions:
globally deactivate the CSRF token : I don't want to do this
create two set of forms, one with the token activated : form my admin forms, the other one for the REST API. => in this case, the rest API can't have a fallback _format=html
find a way to give the api consumer an auth, with an API_GROUP, and disable the token for this group
it seem to me the best solution, but I don't know how to do it transparently, without affecting the auth of my future admin, and without needing to give credentials in the REST request.
use an event listener in order to hack symfony's auth mechanism and give an auth if a call is made to the REST API (all but _format=html)
Which one of this (or other) solution seem the best to you, and how would you code it?
I found a way, perhaps not the best one, but it works :
$_format = $request->attributes->get('_format');
if ('html' == $_format) {
$form = $this->createForm(ItopInstanceUserType::class, $itopInstanceUser);
} else {
$form = $this->createForm(ItopInstanceUserType::class, $itopInstanceUser, ['csrf_protection' => false]);
}
For me, forget CSRF token managed by yourself, check subjects like Oauth authentication.
Take a look here: https://github.com/FriendsOfSymfony/FOSOAuthServerBundle/blob/master/Resources/doc/index.md
FOSOAuthServerBundle works perfectly with FOSRestBundle.

Zend Framework 2 Doctrine ORM Authentication

I'm developing my first real project with ZF2 and Doctrine ORM. And I cannot find any good example of user authentication through doctrine orm authentication adapter. Now I'm using standard Zend Db Adapter authentication. In addition, I use
$adapter->setIdentityColumn(filter_var($request->getPost('useremail'),FILTER_VALIDATE_EMAIL) ? 'useremail' : 'userlogin');
in my login controller to login either via email and login.
But I want to perform all job through doctrine ORM. Could someone show me a similar example with doctrine.authentication.orm_default and storing user identity data in session/storage to access in any controller or module.php? Is it possible to use two fields - userlogin or email for login?
Thank you in advance for your help.
Updated: I kept seaching and as a result this and this helped me so much
One problem, that i haven't solved yet. How can I check user status (activated or not) with doctrine adapter?
Like
$authAdapter = new AuthAdapter($dbAdapter,'user','username','password','MD5(?) AND status = 1');
You can use credential_callable option (Doctrine Module doc.). It can be any callable (PHP Manual), for example with closure:
'credential_callable' => function(User $user, $passwordGiven) {
return md5($passwordGiven) == $user->getPassword() && $user->isActive();
},
or with static class method:
'credential_callable' => 'Application\User\UserService::verifyUser'
What about an external module idea? If you are OK with that you can take a look at https://github.com/ZF-Commons/ZfcUser and https://github.com/SocalNick/ScnSocialAuth or the whole modules repositories http://modules.zendframework.com/?query=user. Even if you don't install just download and see what other people do stuff.

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

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.

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