Zend Framework 2 Doctrine ORM Authentication - zend-framework

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.

Related

Is there a way to capture the LogIn event on 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

How to check drupal user role in module written by Zend Framework

I have written a web application using Zend framework, and I convertered it to the drupal module using ".module" file.
But I need to authorize current drupal user in that module.
How could I check the drupal user role in Zend?
By the way I find out Drupal has its own session handler to store data in database and zend use default handler which store sessions data into file system.
So it make them separate.
Any solution?
It's considered bad practice to check the roles array itself in Drupal, the correct method is to assign an appropriate permission to that role, and check for that permission with user_access(), e.g.
if (user_access('an appropriate permission')) {
// User is authorised.
}
So you actually have a Drupal module.
Try
<?php
global $user;
if (in_array('administrator', array_values($user->roles))) {
}

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

How to load or save Doctrine associated entity into Zend_Auth session

I am looking for some good solutions for a problem.
I am usig Doctrine 2.1 integrated to Zend Framework. I am using Zend_Auth with Zend_Auth_Storage_Session where I have stored User's entity. But entity of User is associtad to other Entity => AclRole. Each User has one AclRole.
For the first time, when I load user throught EntityManager, the AclRole is loaded as soon as call it in User. But when other page is loaded and entity of User is loaded from session, her 'locale' attribute is NULL.
Is there any good solution of this?
I have an excellent solution, that i am using in my project, i will send you the github link when i've checked in my code today ;)

How can I authenticate when using the Bugzilla Perl API in a script?

Working from the Bugzilla API, I've written a quick Perl script to clone a Bugzilla Product (recreating all the Components under their new Product). The Bugzilla Perl API is quite easy to use from the command line. I could have just worked on the database directly, but I wanted a longer-term solution. Another option was the webservice, but I thought I'd try using the API directly this time.
The one problem I'm running into is authenticating as my Bz admin user so I can create the new components. Looking at Bugzilla's Bugzilla.pm file, I see that they just run login() from a Bugzilla::Auth object. I'm not sure how to get the username and password in there. I suppose I could just add the script to the Bugzilla admin interface...
Can any of you point me in the right direction?
Oh, I'm being rather ignorant today, I focused on "web services" and didn't understand what you really wanted.
If you're just using the API to communicate with the database (as opposed to manipulating the database directly), do you really need to authenticate as any user at all?
In the 3.2 source tree, look at merge-users.pl for instance, which uses Bugzilla::User objects. Couldn't you do the same with Bugzilla::Component?
You should also look at sanitycheck.pl, which uses Bugzilla->set_user.
There's been some significant upgrades in the web services capabilities since 3.2, can you upgrade?
In 3.6 at least, check out contrib/bz_webservice_demo.pl for how to use the User.login method.
http://www.bugzilla.org/docs/tip/en/html/api/Bugzilla/WebService/User.html
The following code snippet might enter the question.
Here we check also that the user has the correct "editcomponents" credential.
my $user = new Bugzilla::User({ name => $login })
|| ThrowUserError('invalid_username', { name => $login });
# Authenticate using this user account.
Bugzilla->set_user($user);
$user->in_group('editcomponents')
|| ThrowUserError("auth_failure", {group => "editcomponents",
action => "add",
object => "products"});