Asp.net mvc Authentication filter overide default reditect - asp.net

In my MVC 5 application I have applied some Role filters such as:
[Authorize(Roles = "ManageRoles")]
Now if a user does not have permission to access this role, it redirects me to the login page. This is incorrect in my application as I want to rather display an error message saying that you donot have permission to access.
Where do I change what happens if a user is not authorised to access a filter?
Do I have to implement custom filters? I would like to try and use the redirectTo action if possible so that I can have different error pages in different situations.

Use Custom Authorize Attribure - Ben Scheirman or Ben Cull's answer in this thread.
Also Check Mark's response to similar question, where he used HandleUnauthorizedRequest to redirect unauthorized users.
In the both the above approaches, you can redirect to any Route or Action of your interest and use HttpContent.Items[] or TempData to hold the specific error messages or values to be display on the destination page.

MVC5 has actually started to address this issue. They now include Authentication Filters in addition to Authorization Filters. These are pretty lightly documented, but my gut feeling is that this a first stab at separating authentication from authorization (up until now, ASP.NET has confused the two)
What i'm thinking is that Authentication filters will be used to control whether a user is logged in or not, and Authorization filters will be used to control what you have access to. However, it seems that this isn't yet fully realized.

In your Login view, you can add logic for:
Checking if the request is not authenticated
1.1. Display login form
Checking if the user is authenticated but not in the required role
2.1. Display error message
Since you'll be automatically redirected to the login page by your Web.config settings, you can take advantage of this mechanism.
if (!Request.IsAuthenticated)
{
//render login form
}
else
{
<p>Error: you do not have the necessary credentials to access this resource.</p>
}
Another option would be to create your own AuthorizationAttribute. This question is similar to yours. You might find it useful.

Related

Customizing CQ / AEM Authentication

What exactly do you have to do to authenticate users against an external source while accessing pages on a CQ publish instance?
From what I have read, a custom AuthenticationHandler can be used for this. The AuthenticationHandler can be configured to be called against the paths requiring authentication and inside the extractCredentials() method, the users will be authenticated against the external source and an AuthenticationInfo object will be returned.
If the supplied credentials are invalid, null would be returned from this method to indicate the same. The SlingAuthenticator will then call requestCredentials() where the user can be redirected to the login page.
Is this understanding correct? If so, what does SlingAuthenticator do with the AuthenticationInfo object returned from extractCredentials()?
In some places, having a custom LoginModule (by overriding AbstractLoginModule) is also suggested for the same purpose. Are these 2 different approaches (custom AuthenticationHandler and Loginmodule) for having custom authentication or are they used together somehow? If so, how do they interact?
And also, the concept of CUG (Closed User Group) can be used to redirect users to the login page if they don't have access to a page. Can CUG still be used with a custom auth mechanism or it only works if the users are present in CQ repository?
Any light shed on this would be much appreciated :)
Your understanding is correct. The AuthenticationInfo object ultimately contains a JCR user id -- but rather than having to use the JCR password for the user, a 3rd party service basically says "this user has authenticated successfully and can access the repository as X".
Example: you're using OpenID or SAML to verify a user is X. user X is then mapped to a user Y in the repository.
I haven't used LoginModule but from what I'm reading, that's just extending login processing for the JackRabbit repo. So, rather than using AuthenticationHandler to redirect a user to some other place and processing the response, you're plugging further down into the chain where there's already AuthenticationInfo (or something like that) being given to JackRabbit to verify and return a session for a user.
So, let's say you did successfully authenticate with OpenID but the user you're mapped to doesn't exist. You could write a login module to create the user in this case (and assign user to a default group). For instance, if user came in with a gmail id, the JCR user could be gmail_$id. And the login module, seeing the name starts with gmail, will know it's ok to create that user automatically.
As far as CUG, yes, all the above can be used in conjunction with it. Basically, if a request doesn't have access to a resource and the request hasn't been authenticated, the authentication handling system kicks in. If a user has authenticated but still doesn't have access to the resource (e.g. not part of a group that can read it), a 403 will be generated.

Adding flash message when the user is redirected to login page in Symfony2

I have a simple Symfony2 application that requires the user to be authenticated to see some pages.
When a protected page is visited while anonymous, the user is redirected to the login page. This is all working as expected, but I would like to add a flash message when the user is redirected to the login page for the first time (something like "Login to see this page").
I am not sure what would be the best approach. I think that the redirection is triggered by ExceptionListener::startAuthentication. The second argument of this method is an exception (AuthenticationException $authException), that is probably set to something when the user is trying to access a protected page while being anonymous.
Can I somehow override this behavior and add a flash message or is there a simpler way?
May be you can use "before and after" filters explained in the documentation : http://symfony.com/doc/current/cookbook/event_dispatcher/before_after_filters.html
I think this is a good approach for your case.

Execution order against authorization filter

Using Fluent Security, I have configured website access using DenyAnonymousAccess, DenyAuthenticationAccess and RequireRole. However, since HandleSecurityAttribute is not an authorization filter, all logic to handle DenyAnonymousAccessPolicyViolation only get executed after authorization filter, such as ValidateAntiForgeryToken.
This means that if current user's authentication ticket is timeout, any action decorated with ValidateAntiForgeryToken will throw exception since the token is not created for anonymous user.
So is there a way to work around this? I am currently looking at two solutions:
reate my own authorization filter to perform exact what HandleSecurityAttribute security does.
Use the global Authorize filer to handle authentication and leave role / other access policy to FluentSecurity.
Update:
I checked in a demo at github, the username and password for this is dev1 and devdev. I set the timeout forms authentication to 1 minute. So if you login, and wait for one minute, then click on logoff, you will get the token is not created for anonymous user. In normal MVC, this won't happen since [Authorize] runs before [ValidateAntiForgeryToken], which redirect user back to login screen.
I haven't had any problems with this. Make sure that you put the HandleSecurityAttribute first in the filters list!
GlobalFilters.Filters.Add(new HandleSecurityAttribute(), 0);

ASP.NET Membership - Two providers on site

Our site has got two ASP.NET membership providers. The built in one, and a custom one (SqlMembershipProvider.
I am able to log into both no problems, but I don't necessary require the ability to have both logged in at the same time.
The issue I have is as follows:
User "person_a#site.com" logs into the built in provider. They then navigate to the section of the site where we require the custom provider.
On this page, I can check if they are authenticated, and get their username. I can then get a MembershipUser object form the custom providers GetUser method. (HttpContext.Current.User.Identity.Name)
It is possible (and very likely) that the username "person_a#site.com" could also exist in the users for the custom provider.
But, I don't want them to be logged in here, as they haven't authenticated against the custom provider.
So, is it possible to check which proivider HttpContext.Current.User was generated from.
Hope this all makes sense!!
Yes, if you notice on the RolePrincipal there is a property called ProviderName.
Typically when people roll their own providers they omit usage of this field.
In your case, simply modify your custom provider to identify itself, if it does not already, and check that property of the user.

ASP.NET Login Control - Is it possible to extend it with custom data?

I'm currently developing an ASP.NET website, and I'm using ASP.NET's built-in Login control with client-side cookie generation for state management.
Unfortunately, as I didn't figure out how to append custom information (generated by other controls on my application) to the Login control self-generated cookie, my application generates an additional cookie to store that additional info. Basically, I have two cookies: one managed by the Login control and another managed by me, programatically.
What I would like to know is if it's possible to merge my additional information into the infrastructure's Login control self-generated cookie. This would prevent some issues with the "sliding timeout" feature that could result on my "custom cookie" expiring with the user being logged in - I could solve this one with a custom HTTP Module to prevent it, but that seems to me as an "inelegant" solution.
Any brilliant mind could help me out with this?
Thanks in advance for your attention and support.
Yes, you can store data in the UserData property of the authentication ticket. Please see the section "Storing the Username of the Admin User Who Logged On As Another User" at https://web.archive.org/web/20210304120451/https://www.4guysfromrolla.com/articles/102208-1.aspx
However, you might find the User Profile system to be more useful. https://web.archive.org/web/20211020111657/https://www.4guysfromrolla.com/articles/101106-1.aspx

Resources