Category Archives: Authorization

Authorization

[RESOLVED]Custom Authorization MVC

I have the following scenario

Controller with following methods

GetDocument(id)
GetBenefit(id)

I want to be able to authorize access to this methods based on the id. (a user can open a document or benefit when he has been granted access by ad administrator)

As I read authorizationFilter info on MVC it only support authorization on method level. (define which role or user that can access a given operation on a MVC controller)

What is the best approach for MVC for doing stuff like this?

In my current aspx site i use a HttpModule that handle AutorizeEVent inn IIS pipeline that reads request parameters and have rules based on url which parameters to look for. 

(the decision to grant access or not is handled by a seperate component, i just need something to check and enforce authorization)

 

HomeCinemaGuy

What is the best approach for MVC for doing stuff like this?

It’s not MVC , it is business logic. What if you have an application console that does the same thing?

If you want to do with mVC, you have derive from ActionFilter , intercept on ActionExecuting, see the current user and the id parameter and grant ( or not ) access by redirecting to a nonrights action

[RESOLVED]Creating custom authorization attribute using AuthorizeCore method Versus OnAuthorization method

I am reading the Pro asp.net mvc 5 book, and it mentioned the following paragraph  :-

KEEPING AUTHORIZATION ATTRIBUTES SIMPLE
The AuthorizeCore method is passed an HttpContextBase object, which provides access to information
about the request, but not about the controller or action method that the authorization attribute has been applied to. The main
reason that developers implement the IAuthorizationFilter interface directly is to get access to the
AuthorizationContext passed to the OnAuthorization method, through which a much wider range of
information can be obtained, including routing details and the current controller and action method.
I do not recommend this approach, and not just because I think writing your own security code is dangerous. Although
authorization is a cross-cutting concern, building logic into your authorization attributes which is tightly coupled to the
structure of your controllers undermines the separation of concerns and causes testing and maintenance problems. Keep your
authorization attributes simple and focused on authorization based on the request. Let the context of what is being authorized
come from where the attribute is applied.

so as i understand that i writer prefer using AuthorizeCore method when creating custom authorization attribute because it will use the default asp.net security , rather than creating new security mechanism from scratch when using OnAuthorization method,
which can have security holes. Also the writer mentioned that the AuthorizeCore method will not allow accessing the AuthorizationContext. but inside my current application, i define a new custom authorization attribute using AuthorizationCore method and i
still can access the AuthorizationContext as follow:-

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]

    public class CheckUserPermissionsAttribute : AuthorizeAttribute
    {

        public string Model { get; set; }
        public string Action { get; set; }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
              if (!httpContext.Request.IsAuthenticated)
               return false; if (!repository.can(ADusername, Model, value)) // implement this method based on your tables and logic { return false; } } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; filterContext.Result = new HttpStatusCodeResult(403, "Sorry, you do not have the required permission to perform this action."); } else { var viewResult = new ViewResult(); viewResult.ViewName = "~/Views/Errors/_Unauthorized.cshtml"; filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; filterContext.HttpContext.Response.StatusCode = 403; filterContext.Result = viewResult; } // base.HandleUnauthorizedRequest(filterContext); } }

can anyone advice what is meant in the above paragraph ?

Hi john,

What’s the writer mean is that in AuthorizeCore method, we can’t access
AuthorizationContext.

For your code, you get AuthorizationContext in HandleUnauthorizedRequest. There isn’t anything to limit to access
AuthorizationContext in other method if we are override AuthorizeCore method.

There are some links that may benefit you:

# AuthorizeAttribute.cs

http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/1acb241299a8#src/System.Web.Mvc/AuthorizeAttribute.cs

# Why is onAuthorization executing before authentication?

http://stackoverflow.com/questions/9366085/why-is-onauthorization-executing-before-authentication

Best Regards

Starain

ok i understand , thanks for clarifying this..

but i have one more question , now inside the AuthorizeCore method i am checking if the request IsAuthenticated as follow:-

  if (!httpContext.Request.IsAuthenticated)

but since i am overriding the Authrizecore method, so does this mean that checking if the request IsAuthenticated will be done out of the box ,and i do not need to write this be myself?

Hi john,

That’s base on the detail requirement, to override we could have the additional conditions, such as special role. We also could call parent
AuthorizeCore method in it (base.AuthorizeCore)

There is a link that may benefit you:

# Extending the behavior of MVC AuthorizeAttribute for activity-based authorization

http://www.codeproject.com/Articles/533989/ExtendingplustheplusbehaviorplusofplusMVCplusAutho

Best Regards

Starain

Starain chen – MSFT

Hi john,

That’s base on the detail requirement, to override we could have the additional conditions, such as special role. We also could call parent
AuthorizeCore method in it (base.AuthorizeCore)

There is a link that may benefit you:

# Extending the behavior of MVC AuthorizeAttribute for activity-based authorization

but the way i am overriding the AuthorizeCore will still check if the user is authenticated even if i do not explicitly check this…is this correct?

Hi john,

It won’t check whether user is authenticated unless call base.AuthorizeCore. To override AuthorizeCore method is used for our own local.

Best Regards

Starain

Starain chen – MSFT

Hi john,

It won’t check whether user is authenticated unless call base.AuthorizeCore. To override AuthorizeCore method is used for our own local.

Best Regards

Starain

so in this case what will be the features that i will benefit from , if i define my custom authorize attribute as a sub class of the AuthorizeAttribute and override the  AuthorizeCore method (as i am currently doing) ? i though that
i will be benefiting from the features that the defualt Authorize attribute provide including checking if the request is authenticated or not , but seems this will not be the case? can you advice further on this please?

As i recently read a book which talks about creating custom authorization attributes and it mentioned the following regarding this :-

A much safer approach is to create a subclass of the AuthorizeAttribute class which takes care of all of the tricky stuff and makes it easy to write custom authorization code. The best way to demonstrate this is to create a custom filter and, to this end, I have added an Infrastructure folder to the example project and created a new class file within it called CustomAuthAttribute.cs. You can see the content of this file in Listing 18-10.
I have used the simplest approach to creating an authorization filter, which is to subclass the AuthorizeAttribute class and then override the AuthorizeCore method. This ensures that I benefit from the features built in to AuthorizeAttribute. The constructor for the filter takes a bool value, indicating whether local requests are permitted.

so i am not sure what built-in features i will be benefiting from ?

Thanks

Hi,

The return type of AuthorizeCore method is Boolean instead of void, so we need return true or false. Since we override that method, the validate local is by ourselves, it won’t check whether user is authenticated but we could check.

We could have the additional validation conditions for current user even though he has already authenticated, for example, special roles.

In my previous reply, there is the
link
and for that sample it says:

This overridden method gives us the following:
1.if the httpContext is null, error out.
2.If the activity list isn’t empty and the user doesn’t have permission for that activity, return false.
3.If we made it this far, check the base method (the steps above).

In the example above the SiteActionsComponent is a business component that provides the lists of roles that the user could be in to satisfy the need for the listed actions. The example comes from a project that uses activities in combination with WebSecurity, and I wanted to avoid additional complication such as custom security providers / principals. You will need a similar provider in order to use this method.

Best Regards

Starain

so just to clear things out , now in my situation i have the following:-

I am NOT calling the

base.AuthorizeCore(httpContext) , instead of that i explicitly if
  if (!httpContext.Request.IsAuthenticated)
               return false;

so currently i have these questions:-

1. what will calling the base.AuthorizeCore method provide , other than checking if the request IsAuthenticated or not ?

2. since i am explicitly checking if the Request.IsAuthenticated instead of calling the base.authorizeCore ,so  can this be considered a security hole inside my application ?

3. should i modify my code in this way :-

protected override bool AuthorizeCore(HttpContextBase httpContext)
        {

base.AuthorizeCore(httpContext);//i add this
 if (!repository.can(ADusername, Model, value)) // implement this method based on your tables and logic { return false; } }

instead of my current code:-

protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
              if (!httpContext.Request.IsAuthenticated)
               return false;
            if (!repository.can(ADusername, Model, value)) // implement this method based on your tables and logic
            {

                return false;
                
            }
           

          
        }

Regards

Hi john,

johnjohn123123

1. what will calling the base.AuthorizeCore method provide , other than checking if the request IsAuthenticated or not ?

As far as I know, for Request.IsAuthenticated, it just identity whether there is the authentication token in the request, it not check the specify users and roles. In the
AuthorizeCore method, it will check whether current user is the specify user and role.

We could do our additional validations, then call base.AuthorizeCode method if needed.

johnjohn123123

2. since i am explicitly checking if the Request.IsAuthenticated instead of calling the base.authorizeCore ,so  can this be considered a security hole inside my application ?

That isn’t enough, you also need to check user and role condition.

johnjohn123123

. should i modify my code in this way :-

protected override bool AuthorizeCore(HttpContextBase httpContext)
        {

base.AuthorizeCore(httpContext);//i add this
 if (!repository.can(ADusername, Model, value)) // implement this method based on your tables and logic { return false; } }

instead of my current code:-

protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
              if (!httpContext.Request.IsAuthenticated)
               return false;
            if (!repository.can(ADusername, Model, value)) // implement this method based on your tables and logic
            {

                return false;
                
            }
           

          
        }

You could call base.AuthorizeCore method at last, if you don’t have to validate the specify user and role any more, you don’t need call it.

Best Regards

Starain

[RESOLVED]create users using web API

<div class="post-text" itemprop="text">

I have built a web application using MVC5 now I’m building the web api’s for that project. I want to build an api that allows the creation of users and save them in the membership database. how could that happen?what should I do?

</div>

lolo512

I want to build an api that allows the creation of users and save them in the membership database. how could that happen?

How users are created in your application until now? Do the same…

shouldn’t there be a javascript code that gets the data and send them by ajax to the server side?

Hi lolo512,

You could use JavaScript to post the data to server (e.g. get username and password, then post to the server through AJAX)

# jQuery.ajax()

http://api.jquery.com/jquery.ajax/

About Web API authentication, please refer to:

# Security, Authentication and Authorization

http://www.asp.net/web-api/overview/security

Best Regards

Starain

[RESOLVED]RequireHttps – redirection error

I am using RemoteRequireHttps attribute on my action and this is resulting in following error. When i remove the attribute and manually go to https page, it shows up just fine.

The page isn't redirecting properly

    Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

    This problem can sometimes be caused by disabling or refusing to accept cookies.

RemoteRequireHttps Attribute

public class RemoteRequireHttpsAttribute : RequireHttpsAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentException("Filter Context");
            }

            if (filterContext != null && filterContext.HttpContext != null)
            {
                if (filterContext.HttpContext.Request.IsLocal)
                {
                    return;
                }
                else
                {
                    string val = ConfigurationManager.AppSettings["RequireSSL"].Trim();
                    bool requireSsl = bool.Parse(val);
                    if (!requireSsl)
                    {
                        return;
                    }
                }
            }

            base.OnAuthorization(filterContext);
        }
    }

Our production site is

The same attribute works just fine on the dev site:

  • it is NOT load balanced
  • https binding is in place

What do i need to do so that my RemoteRequireHttps attribute works with the load balancer?

I have updated the RemoteRequireHttps attribute and it is working now per
this post
.

public class RemoteRequireHttpsAttribute : RequireHttpsAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentException("Filter Context");
            }

            if(filterContext.HttpContext != null)
            {
                if (filterContext.HttpContext.Request.IsSecureConnection)
                {
                    return;
                }

                var currentUrl = filterContext.HttpContext.Request.Url;
                if (currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase))
                {
                    return;
                }

                if (string.Equals(filterContext.HttpContext.Request.Headers["X-Forwarded-Proto"], "https", StringComparison.InvariantCultureIgnoreCase))
                {
                    return;
                }

                if (filterContext.HttpContext.Request.IsLocal)
                {
                    return;
                }
                
                var val = ConfigurationManager.AppSettings["RequireSSL"].Trim();
                var requireSsl = bool.Parse(val);
                if (!requireSsl)
                {
                    return;
                }
            }

            base.OnAuthorization(filterContext);
        }
    }

Hi,

It seems ok.

Regards

Updating master page then redircting to log in page

I have seen different behavior of asp .net if I update content in master page,and I browse application some time it redirect to log in page and some not.

Why it happening explain if any one having clear idea.

Thanks,

What kind of authentication/authorization do you have?

ignatandrei

We are authenticating against database.

most likely you did not define a machine key in your web.config. if not defined a new key is generated on application start. as the authentication cookie is encrypted with this key, aft a recycle the cookie can not be decoded, so its as if it was not sent.
asp.net does a auto recycle after x number of code changes. just define a machine key in the web.config, and authentication will survive a recycle. change session to sql session, and session also will survive a recycle.

bruce (sqlwo…

as you said

just define a machine key in the web.config, and authentication will survive a recycle

Without defining machine key in the web.config in web config the app is recycling.

Hi krajmehra,

It seems that your app recycling results into missing authorization header. You can try using fiddler to see if the response header when redirecting to log in page.

And If you are using IIS as webserver, you can check the recycle event log.

For more information, please refer to the similar discussion:

 http://webmasters.stackexchange.com/questions/17630/which-event-log-file-does-iis-7-app-pool-log-to

Pengzhen Son…

This is happening in development env not in published.So the website is running on development server not on IIS.