Symfony2 how to pass parameters to auth success handler - authentication

when symfony2 authenticates user by login form, an event security.authentication.success is fired and is handled by DefaultAuthenticationSuccessHandler. Constructor of this object takes two arguments HttpUtils $httpUtils and array $options. Variable $options is not empty and contains configuration options from security.yml like:
login_path => pkr_blog_admin_login
user_referer => false
...
I created a service AuthenticationSuccessHandler that extends DefaultAuthenticationSuccessHandler but can't find a way to pass values from security.yml as $options to constructor of my object. How can I do this?
I had tried using xdebug step by step debugging to see how those options are passed to DefaultAuthenticationSuccessHandler but couldn't find exact place in code :/
//EDIT
I found out that this configuration is set in src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.php and only for default handler.
Here are some comments about not getting configuration from security.yml in custom handler:
https://github.com/symfony/symfony/issues/5432
https://github.com/symfony/symfony/issues/5488
Anyone know a way to get configuration parsed and ready to use by default handler from within my handler?
I suppose that it might be done by passing service container to my handler. I'll try this when I'll be back from work.

It seems that only way to make it work is to use compiler pass and change default handler class. See my similar question:
Better way of doing this is to use service as event handler:
Symfony2 extending DefaultAuthenticationSuccessHandler

Related

ASP.NET MVC intercepting route handling

So I am facing this little problem. In my route config I have configured two routes. One default route, which handles controller/action request and one custom route which is basically website.com/my_route where my_route is received by some controller's action as an argument. the problem is that whenever I want to give that action a parameter which contains a '/' in it, the route handler resolves request to controller/action route config, so if looks like this website.com/my_route/my_subroute, you get what happens. the my_routeController is searched and of course it does not exist, now the number of '/' in url can be more than one as you see and I want to do such thing. if the appropriate controller with appropriate action does not exist I want this request to be handled but that one controller which's action will recieve my_route/my_subroute as an argument. What is the best practice in this situation. If need I can provide the route config.
Try following way in your route.config
routes.MapRoute(
"my_route",
"my_subroute/x/y/z",
new { controller = "controllername", action = "actionname" }
);
Let me know if this fixed your issue. :)

How do I simply set the ModelStateError from the HandleUnauthorizedRequest method?

So what is happening is that I have a condition within my override of the HandleUnauthorizedRequest method in my custom authorize attribute. Up to this point, I've been throwing a 403 which gets picked up and redirects to a custom error page. Well now, that's not really what I want. What I actually want is to show the same login page but add a message to the validation summary "You do not have access to this resource.", that way it's a bit more user friendly. It'll indicate that your creds were good, but you don't belong here.
I thought something like this would work:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// passed authentication, failed authorization
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Controller.ViewData.ModelState.AddModelError("", "Not Authorized");
return;
}
base.HandleUnauthorizedRequest(filterContext);
}
But this isn't working. What's happening is that the login page simply reloads. So this makes me feel like I'm close, but I need that model error to show up.
Any ideas?
UPDATE:
It would seem that the Controller that I'm adding an error to here is actually controller of whichever action had the attribute that led to here. I need to somehow add the error to the login controller. Not sure if that's even possible.
You are calling the base method here:
base.HandleUnauthorizedRequest(filterContext);
If you are using Forms Authentication this base method simply redirects you to the login page. And a redirect means a new HTTP request from the client. The current context and whatever you stored in it is lost. Well, to be more precise, the base method is returning a 401 HTTP status code which is then intercepted by the FormsAuthenticationModule which redirects to the login page defined in your web.config. But this implementation details is not important.
What you could do is perform the redirect yourself to the login page instead of leaving it to the base method. You could do this by setting the filterContext.Result property to a RedirectToRouteResult instance. In this case you could pass the error message as a query string parameter.
UPDATE:
According to your updated question it seems that you are calling return; after setting the ModelState value and not calling the base method and thus no redirect will happen to the login url. You could in this case return some error view by setting the filterContext.Result to an instance of a ViewResult in which view you could use the value you stored in the ModelState.

Add Action Message In Struts 2 Interceptor After Action Invocation

I have a unique problem with passing an action message in a JSON result.
Right now, if I add an action message within my action (in a JSON action), I will pick that up in JavaScript and capture the action message and alert the user via JGrowl. However, I don't want the logic of adding an action message in each action. I have an underlying service project with a request context that is shared among the request, and I am able to add warning messages there. What I'd like to do is to transform those warning messages to action messages for use on my front end, but the action will never have to be aware of them. This is useful because I can insert warnings when accessing databases, or if there are hairy business rules, etc.
As I mentioned before, it already works when adding them directly in the action so I know the JSON result works fine and passes along the action messages correctly. We have an interceptor that is hit every time for managing this request context already, so I'd like to append on the action messages in this interceptor to the action being called.
However, the problem I'm finding is that I need to call actionInvocation.invoke() first as any warning messages will be generated as a result of that. After that, I check for the messages and attempt to apply them as action messages. These action messages never show up in my JSON response, so I'm wondering if it's possible to add those messages into the response in the interceptor AFTER the invoke() call. Here's the bulk of my intercept method:
try {
// Invoke the action.
String result = actionInvocation.invoke();
//add all warning messages as an action message to be displayed on that front end
if (CollectionUtils.isNotEmpty(context.getWarningMessages())) {
ActionSupport action = (ActionSupport) actionInvocation.getAction();
for (String s : context.getWarningMessages()) {
action.addActionError(s);
}
}
return result;
I tried adding the logic to add the action messages in the finally block instead of after the call to invoke() to no avail.
Thanks,
Andy
The result has been rendered by the time invoke returns.
You need to implement a PreResultListener as discussed in the "Writing Interceptors" docs.

Yii generate errors from parent controller

I just started using Yii, coming from Codeigniter (CI). I'm trying to set up a situation where the application will check a users credentials before they can even access the site. In CI, I would create a parent controller, put my checks in there, and then inherit that parent controller. I've been trying to do the same thing with Yii, but with no luck.
I first created an init() method (for some reason I can't put the code in a __construct() method). I then perform my check, which works fine. I can throw a new CHttpException, but that looks ugly. How do I use Yii's built in error handling to accomplish what I want to do?
For simple login rules you should just implement the 'accessControl' filters from Yii see Yii documentation on authorizations.
Another way would be to throw the Exception like you already did, and write custom Http error views, place it in the yerfolder/protected/views/system/ (see the yii/framework/views directory for examples)
I solved this by sending the error to the site/error view and then calling Yii::app()->end() to keep the child controllers from loading.

Z_Form :: Adding a custom error message to zend_form inside Action Controller

I'm new to ZF and I'm discovering how to use Zend_Form and utilize it's capability like validating and filtering input values. I already know the basic of Zend_form like building a form and add element into it. My problem is that I want to add a custom error message to form element and I want to define that message inside the action controller that instantiated the form. I want to defined the error message inside the controller because I need to perform a validation against the database. For example checking if the username/email already exist in the database. I tried googling and that's leads me to setErrorMessage method of zend_form but when I try to use it, the error message is not showing at all... I also tried zend_form->setError and still no error displaying in the view script. Is my idea of setting custom error in the action controller correct or this should be done the other way?
Are you using Zend_Validate_Db_RecordExists?
Something like this should work:
$form->getElement('username')->getValidator("RecordExists")->setMessage('This username exists',
Zend_Validate_Db_RecordExists::ERROR_RECORD_FOUND
);
This works for me:
$form->getElement('username')->addError('This username exists.');