Claims-based authentication in MVC4 with .NET4.5 C# part 3: claims based authorisation

In the previous post we discussed how to the save the authentication session so that we didn’t need to perform the same auth logic on every page request. In this post we will look at how authorisation can be performed using claims in an MVC project.

Introduction

There are two main approaches to authorisation in an ASP.NET web application: pipeline authorisation and Intra-app authorisation.

Pipeline auth means performing coarse grained, URL-based authorisation. You may require the presence of a valid auth header in every request that comes to your server. Or the authenticated user must be in a certain Role in order to reach a certain protected URL. The advantage with this approach is that authorisation happens very early in the application lifecycle so you can reject a request very early on. In this scenario you will typically have little info about the user and what resource they are trying to access but these can be enough to reject a large number of users.

An example of pipeline auth in our simple MVC4 web we’ve been working on this series can be found in CustomClaimsTransformer.Authenticate. This is the stage where you can check the presence of a certain claim that your auth logic absolutely must have in order to make an early decision. If it’s missing, then you may not care about what the user is trying to do, the request will be rejected.

Another example of pipeline auth comes from the good old ‘location’ elements in an ASP.NET web forms config where you could specify URL-based auth:

<location path="customers">
    <system.web>
      <authorization>
        <allow roles="IT"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>

This is an acceptable approach in web-forms projects where the URL has a close affinity to the project file system, i.e. the value of the ‘path’ attribute represents an .aspx file. In MVC /Customers will of course not lead to an aspx page called Customers. In MVC urls and resources are unlikely to have a one-to-one match. You don’t call physical files the same way as in a web-forms app. If the routing mechanism is changed then the path attribute will be meaningless. So all of a sudden people will have access to previously protected parts of your web app. Generally try to avoid this approach in an MVC application as it creates a tight coupling between the routing table and the project file structure.

Yet another example of pipeline auth is the ClaimsAuthorisationManager which can be registered in the web.config. This will sound familiar to you if you looked at the post on the very basics of claims. This is also a URL based approach, but it’s based on Claims and not Roles.

Intra-app auth on the other hand means fine-grained checks within your code logic. The benefit is that you have the chance to collect as much information as possible about the user and the resources they are trying to use. Then you can tweak your authorisation logic on a wider information basis. In this scenario you will have more info on the user and make your reject/accept decision later in the app lifecycle than in the Pipeline auth scenario.

A definite advantage of this approach is that it is not URL based any more so it is independent of the routing tables. You will have more knowledge about the authorisation domain because you’ll typically know exactly what claims the user holds and what they are trying to achieve on your site.

PrincipalPermission and ClaimsPrincipalPermission

You can follow a declarative approach using the ClaimsPrincipalPermission attribute or an imperative one within the method body. Either way you’ll work with Claims and not Roles as in the ‘old’ days with the well-known ‘Role=”IT”‘ and .IsInRole(“Admin”) type of checks:

[PrincipalPermission(SecurityAction.Demand, Role="IT")]

The old way of performing authorisation is not recommended now that we have access to claims in .NET4.5. Roles encouraged you to mix authorisation and business logic and they were limited to, well, Roles as the way of controlling access. However, you might have required more fine-grained control over your decision making. Then you ended up with specialised roles, like Admin, SuperAdmin, SuperSuperAdmin, MarketingOnThirdFloor etc. Decorating your methods with the PrincipalPermission attribute also disrupts unit testing as even the unit testing thread must have a User in the Role specified in the attribute. Also, if the current principal is not in the required group then an ugly security exception is thrown which you have to deal with somehow.

In this post we saw a detailed discussion on the ClaimsPrincipalPermission which replaces the PrincipalPermission. Here comes an example to refresh your memory:

[ClaimsPrincipalPermission(SecurityAction.Demand, Operation="Show", Resource="Code")]

In short: we don’t care which group or role the user is in any longer. This attribute describes the method it decorates. It involves a ‘Show’ operation on the ‘Code’ resource. If the current user wants to run this method then they better make sure that they have these claims. It will be the ClaimsAuthorizationManager that decides if the current principal is allowed to call the action ‘Show’ on the resource ‘Code’. The principal still must have certain claims, just like they had to be in a certain Role before. However, the authorisation logic is now separated out to a different part of the application. You can even have that logic in a web service on a different machine so that the auth logic can be handled entirely separately from your application.

Another benefit is the following: what constitutes a certain Role can change over time. What is ‘IT’? Who belongs to that group? So later on you may have to come back to every method with the attribute ‘Role=”IT”‘ and change it to e.g. “Geeks” because ‘IT’ has changed its definition at your company. On the other hand a method that has the function to ‘Show’ a resource called ‘Code’ will probably have that function over a long time, possible over the entire life time of the finalised production version of the application.

So, this attribute solves some of the problems with the PrincipalPermission. However, it does not solve all of them. It still gets in the way of unit testing and it still throws a SecurityException.

The Authorize attribute

The MVC ‘equivalent’ of the ClaimsPrincipal attribute is the Authorize attribute. It is still limited to roles:

[Authorize]
public ActionResult ShowMeTheCode()

[Authorize(Roles="IT")]
public ActionResult ShowMeTheCode()

It does not use the action/resource properties of the method and you still mix your auth logic with the ‘real’ application code leading to the same Separation of Concerns problem we mentioned above. However, this attribute is not invoked during unit testing and it does not throw Exceptions either. Instead, it returns a 404 which is a lot nicer way of dealing with unauthorised access.

We are only one step from the MVC4 claims-based authorisation nirvana. It would be great to have an Authorize attribute where you can specify the Resource and the Action just like in the case of ClaimsPrincipalPermission. You could derive from the existing Authorize attribute and implement this kind of logic there. The good news is that this has been done for you and it can be downloaded from NuGet. The NuGet package includes the imperative equivalent of the declarative attribute as well. So if you need to check if the user has access rights within a certain method, then there’s a claims-enabled solution in MVC4. We’ll use this attribute in the demo.

Demo

The initial steps of building the authorisation module have been outlined in this blog post. I will not repeat all of the details here again.

Open up the project where we left off in the previous blog post. If you remember then we included a CustomClaimsTransformer class to implement our own claims transformation logic. This is our claims based authentication module. We would like to extend the project to include authorisation as well.

First add a new class to the web project called CustomAuthorisationManager. It will need to derive from ClaimsAuthorizationManager in the System.Security.Claims namespace:

public class CustomAuthorisationManager : ClaimsAuthorizationManager
    {
        public override bool CheckAccess(AuthorizationContext context)
        {
            return base.CheckAccess(context);
        }
    }

Recall that you can extract the Resource, the Action and the Principal from the AuthorizationContext object parameter.

Now let’s say we want to make sure that only those with the name Andras who live in Sweden are allowed to view the code. I would do it as follows:

public override bool CheckAccess(AuthorizationContext context)
        {
            string resource = context.Resource.First().Value;
            string action = context.Action.First().Value;

            if (action == "Show" && resource == "Code")
            {
                bool livesInSweden = context.Principal.HasClaim(ClaimTypes.Country, "Sweden");
                bool isAndras = context.Principal.HasClaim(ClaimTypes.GivenName, "Andras");
                return isAndras && livesInSweden;
            }

            return false;
        }

Set a breakpoint at the first row of the method body, we’ll need it later.

This should be straightforward: we extract the Action and the Resource – note that there can be multiple values, hence the ‘First()’ – and then check where the user lives and what their given name is. If those claims are missing or are not set to the required values then we return false.

Next we have to register this class in the web.config under the claimsAuthenticationManager we registered in the previous part:

<system.identityModel>
    <identityConfiguration>
      <claimsAuthenticationManager type="ClaimsInMvc4.CustomClaimsTransformer,ClaimsInMvc4" />
      <claimsAuthorizationManager type="ClaimsInMvc4.CustomAuthorisationManager,ClaimsInMvc4"/>
    </identityConfiguration>
  </system.identityModel>

The type attribute is formatted as follows: [namespace.classname],[assembly].

Next we want to make sure that this logic is called when a protected action is called. We will try the claims-enabled version of the MVC4 Authorize attribute. Right-click ‘References’ and select ‘Manage NuGet Packages…’. Search for ‘Thinktecture’ and install the below package:

Thinktecture auth package NuGet

This package will give you access to a new attribute called ClaimsAuthorize where you can pass in the Action and Resource parameters.

Imagine that our About page includes some highly sensitive data that can only be viewed by the ones specified in CustomAuthorisationManager.CheckAccess. So let’s decorate the About action of the Home controller. Note that the attribute comes in two versions: one for MVC4 and one for WebAPI. If you haven’t heard of Web API, then it is a technology to build RESTful web services whose structure is very much based on MVC. You can read more about it here.

Reference the version for Mvc:

Two versions of claims authorize

…and decorate the About action as follows:

[ClaimsAuthorize("Show", "Code")]
        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

This is telling us that the About action will perform a ‘Show’ action on the resource called ‘Code’.

Run the application now. Click on the ‘About’ link without logging in first. You should be redirected to the Log-in page. Enter the username and password and press the ‘Log in’ button. If everything went well then code execution should stop at our breakpoint within CustomAuthorisationManager.CheckAccess. Step through the method using F11 to see what happens. You can even inspect the AuthorizationContext object in the Locals window to see what it contains:

AuthorizationContext object

If the logged on user has the correct claims then you should be redirected to the About page. I will here again stress the point of getting away from the traditional Roles based authorisation of ASP.NET. We are not dealing with Roles any longer. We do not care who is in which group. Instead we describe using the Action and Resource parameters of the ClaimsAuthorize attribute what the logged on user is trying to achieve on our website. Based on that information we can make a better decision using the claims of the user whether to allow or deny access. The auth logic is separated away from the ‘real’ application in a class on its own which is called automatically if it is registered in web.config. The auth logic can even be ‘outsourced’ to a web service which can even be the basis of a separate user management application.

You can specify multiple Resource values in the attribute as follows:

[ClaimsAuthorize("Show", "Code", "TvProgram", "Fireworks")]
        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

…i.e. you just pass in the names of the Resources after the Action.

You can achieve the same imperatively within the method body as follows:

public ActionResult About()
        {
            if (ClaimsAuthorization.CheckAccess("Show", "Code"))
            {
                ViewBag.Message = "This is the secret code.";
            }
            else
            {
                ViewBag.Message = "Too bad.";
            }

            return View();
        }

The CheckAccess method has an overloaded version which accepts an AuthorizationContext object, which gives the highest degree of freedom to specify all the resources and actions that are needed by the auth logic.

In case you wish to protect the entire controller, then it’s possible as well:

[ClaimsAuthorize("Show", "Everything")]
    public class HomeController : Controller

If you want to apply the attribute to the entire application you can do it by adding the attribute to the global filters in App_Data/FilterConfig as follows:

public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new ClaimsAuthorizeAttribute());
        }
    }

This discussion should be enough for you to get started with Claims-based authentication and authorisation in an MVC4 internet application. In the next post we’ll start looking at separating out the login mechanism entirely: Single SignOn and Single SignOut.

You can view the list of posts on Security and Cryptography here.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

44 Responses to Claims-based authentication in MVC4 with .NET4.5 C# part 3: claims based authorisation

  1. nickdarvey says:

    Another question, sorry >_< You seem to know a little about claims đŸ˜›
    I'm having an issue with enumerating on claims to find if it exists. This is both when using 'ClaimsPrincipal.HasClaim' and manually doing it with a .Any() LINQ expression.
    Whenever it's false, it'll hang at what should be the end of enumeration for ~10 seconds then throw me a 'HttpException' with details:
    "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 – Error Locating Server/Instance Specified) "

    I'm not trying to access SQL Server during this time (and it works fine when I actually want to access it) :/ (see below)

    private bool IsSchoolUser(ClaimsPrincipal principal)
    {
    if (principal.HasClaim(ClaimTypes.Role, "SchoolUser"))
    {
    return true;
    }
    else
    {
    return false;
    }

    }

    Just wondering if you'd ever come across anything similar?

    • Andras Nemes says:

      Hmm, you may try the following: open web-config and locate the system.webServer node. If you don’t have a modules section within system.webServer then add it. Within modules add the following: <remove name=”RoleManager” />

      Does it make any difference?

  2. nickdarvey says:

    Oh my god.
    You have no idea how much I love you.

    I am in tears I am so happy. Just… just- GAHHHH
    I’ve been stuck on this for days and I have a pitch coming up damn soon.
    Thank you so much Andras!

  3. lancelot says:

    Thank you so much for this tutorial.
    11 out of 10.
    You are legend.

    • Andras Nemes says:

      Thanks a lot for your comment. If you’re looking for a true legend within the topic of claims and security then check out Dominick Baier on http://leastprivilege.com/

      • Rachael says:

        The last 3 days, I’ve been going through Dominick’s content on this subject along with pluralsight videos he did. Although he’s extraordinary expert in this area, I could only wrap my head around portions of it. Reading through your articles in this series really provided the glue for those portions. Very well written and now I’m off and coding!!!! Thank you very much and I bow down to you, Andras. đŸ˜‰

  4. Tom Schreck says:

    I noticed in your CheckAccess method you are retrieving the first resource and action and then performing your check process based on the first values. You also demonstrate where we can pass in multiple resources to ClaimsAuthorizeAttribute eg: [ClaimsAuthorize(“Show”, “Code”, “TvProgram”, “Fireworks”)]. I’m trying to understand when you would want to pass in multiple resources. I’m working from an ASP.Net MVC perspective where the Action in the controller represents the resource and I suppose the HTTP verb would represent the action. Perhaps I’m letting ASP.Net MVC cloud my understanding, but I’m not seeing a reason or a scenario where you’d want to pass in multiple resources for a given action. Can you provide an example please?

    • Andras Nemes says:

      Hi Tom,

      Imagine that you have a domain with 3 objects: Code, TvProgram and Fireworks. You may as well have separate views for each of these resources, e.g. Index/TvProgram. Then you could have an admin page where you show all three in the same view using a joint viewmodel. You could take the old approach of checking the Role of the IPrincipal to make sure it’s an administrator. Instead, you declare that the person must have access to the three resources in a granular way – as opposed to creating some artificial “Everything”, or “CodeTvProgramAndFireworks” objects.
      //Andras

  5. Pingback: Claims Authorization | ynfiesta

  6. Khashman says:

    Hi Tom,
    your article is very good. I am willing to implement claim based authorization and i understand the benefits over the Role method. However, how can i limit access to some fields in the view returned by the Action without creating different views? For example, let’s assume i have a “Student” resource and he can only update some fields in the view where a “Professor” can update all fields. How do i implement such a logic with claim based authorisation?
    Thank you in advance.

  7. Thomas says:

    Hi Andras,

    I’m wondering what are the differences/benefits between

    [ClaimsAuthorize(“Show”, “Everything”)]

    and

    [ClaimsPrincipalPermission(SecurityAction.Demand, Operation = “Read”, Resource = “Testdata”)]

    • Andras Nemes says:

      Hallo Thomas,

      Check out this post.

      //Andras

      • Thomas says:

        I’ve already read all your posts and know it’s coming from an additional package. But still I don’t get the benefits of ClaimsAuthorizeAttribute vs. ClaimsPrincipalPermissionAttribute. As to me it seems they both do the same, except a difference in passed arguments?!

      • Andras Nemes says:

        Yes, they fulfil the same goal, but I thought I described the advantages of the MVC-style ClaimsAuthorize attribute in that post, maybe I wasn’t clear. I wrote the following about the ClaimsPrincipalPermission attribute:

        “So, this attribute solves some of the problems with the PrincipalPermission. However, it does not solve all of them. It still gets in the way of unit testing and it still throws a SecurityException.”

        And then write this about ClaimsAuthorize:

        “It would be great to have an Authorize attribute where you can specify the Resource and the Action just like in the case of ClaimsPrincipalPermission. You could derive from the existing Authorize attribute and implement this kind of logic there. The good news is that this has been done for you and it can be downloaded from NuGet.”

        So functionally they do the same thing but ClaimsAuthorize still wins overall. As far as I know the PrincipalPermission style of ensuring authentication is quite outdated precisely due to its shortcomings.

        Gruss,
        Andras

  8. Ovais says:

    By considering your example, I’m stuck in a CheckAccess method, where action variable has a value of my property name “About”, and not the attribute string “Show”. How can it be rectified?

  9. bartek4c says:

    Hi Andras, a quick question here. When you return false from CheckAccess method you end up with “HTTP Error 401.0 – Unauthorized” while the application should redirect you to back to the STS login page, shouldn’t it. How can it be achieved?

    • Andras Nemes says:

      Hi Bartosz,
      It depends on what you want your users to see. I as a visitor to a site would probably be confused if I were constantly redirected to the login page if my login fails for whatever reason. I think showing a clear messages such as “Unauthorized” helps me more.
      //Andras

      • bartek4c says:

        Where should I go from here then? Found this post: http://patrickdesjardins.com/blog/asp-net-mvc-http-error-401-0-unauthorized but seems to be rather complicated. Is there any simpler solution to redirect user to a custom view

      • Andras Nemes says:

        why not redirect the user to a generic error page using web.config? you can use the httpErrors section to achieve that, example:

        <httpErrors errorMode="Detailed" existingResponse="PassThrough" >
        	<error statusCode="404" path="/Error/NotFound" responseMode="ExecuteURL" />
        	<error statusCode="500"  subStatusCode="-1" path="/Error.aspx" responseMode="ExecuteURL" />
        </httpErrors>
        

        You can have an entry for a 401 response as well.
        //Andras

      • bartek4c says:

        Hi Andras. Thanks for your answer, not sure about it however. As I have read 401 error is handled only by IIS, and doesn’t reach ASP, therefore cannot be resolved using web.config settings?

      • bartek4c says:

        Yep, I’ve tested the “” solution and didn’t succeed. Have seen many approaches in how to solve this problem (like this one: http://patrickdesjardins.com/blog/asp-net-mvc-http-error-401-0-unauthorized), but all of the refer to Authorize attribute and do not take Claims authorization into account

      • Andras Nemes says:

        Have you tried deriving from ClaimsAuthorizeAttribute? You can override a number of methods, including HandleUnauthorizedAccess which sounds promising.

    • bartek4c says:

      I could probably set context.Principal.Identity.IsAuthenticated to false, but not sure if this is a right way of doing it?

  10. sunil aher says:

    Hi Andras ,

    Can you you explain how you define ClaimsAuthorize attribute and how you access the method checkaccess of ClaimsAuthorizationManager?

    • Andras Nemes says:

      Hi Sunil,

      ClaimsAuthorize is the claims-enabled equivalent of the standard MVC Authorize attribute. You can register your ClaimsAuthorizationManager in web.config as explained in the post. Your implementation of th CheckAccess method will be invoked automatically through the attribute.

      Is anything unclear from the explanations in the post?

      //Andras

  11. whitexacker says:

    Dude. You are Good. i wonder if you have written some books. if you didn’t you reaaaaaaaaaaaaaally should and write them the same way you Blog.No extra Theory. right to the point

    thank you so much for your effort.keeep up the beautiful work

  12. Aleksey Filippov says:

    How do you store the action-resource claims? Should they be hardcoded in the CheckAccess method? I thought that it was a right thing to do – to add claims like `action-resources` at authentication to the claims identity. I’ve found a similar question: https://social.msdn.microsoft.com/Forums/vstudio/en-US/78aa0a9b-b3ff-46b2-846e-32ac910e63c6/how-to-add-resourceaction-claim-pairs-to-claims-identity?forum=Geneva
    The op asks the same thing. But I don’t get the answer. Should I then harcode all variations of if-action-resources-are-like-that-and-principal-claims-are-like-that-then?

    • Andras Nemes says:

      Hi Aleksey,
      I think Dominick Baier means exactly what is shown in this post, i.e. use the CheckAccess method of the auth manager to check whether a user is allowed to carry out an action on a resource. I don’t think the action/resource pairs have anything to do in the claims list of a user. The action/resource pairs don’t describe a user like e.g. a Name claim does.
      You can hardcode the action/resource pairs like in the example but you can turn to more sophisticated OOP ways to encapsulate these magic strings.
      //Andras

      • Aleksey Filippov says:

        How that helps when you have a lot of resources and actions? I agree that permission claims don’t relate to a user identity directly. Is there any other less sophisticated way of implementing such a thing?

      • Andras Nemes says:

        The least sophisticated way of implementing that would be a kilometer-long if/else block that will quickly become unsustainable.
        Instead you can encapsulate your resources and actions in proper objects and pair them up using the decorator pattern. E.g. have a “View” action object and a “Code” resource and the View can decorate the Code object. Let the decorators encapsulate the logic of what’s allowed based on the claims list. You’ll still have to create a lot of new code but you’ll get rid of the ugly if/else block.
        //Andras

      • Aleksey Filippov says:

        Thank you for your answer! I understand this approach. But have dicided to do this another way.

        Yesterday I was reading the book about WebAPI security. When I was reading about claims I stumbled upon such a passage : “claims are used to make a claim about the identity. For example Jon’s email is… Jon is 25… Jon can delete users”. (`Badri can delete users.` originally).

        I’ve decided to follow this scenario:
        – the database model stays as it is;
        – at login I can add claims of type “http://app/claims/authorization/resource-permission” with value like: “view:blogs”;
        – to stay up with the semantics I can create custom authorization filter as [Can(“view”, “blogs”)]

        I just want to try it like that:)
        God bless you!

  13. Nemesis says:

    Hi,

    I am very new to Owin. I have created an MVC application with authentication type WsFederation.

    app.UseWsFederationAuthentication(
    new WsFederationAuthenticationOptions
    {
    MetadataAddress = “https://login.windows.net/45bcfffa-30c4-490f-a7a1-e55fa43a9002/FederationMetadata/2007-06/FederationMetadata.xml”,
    Wtrealm = “http://myApps/OwinWSFed”

    });

    In Home Controller I just decorated actionresult as below

    [ClaimsAuthorize(“IsAuthorized”, “CanView”)]
    //[HttpPost]
    public ActionResult About()
    {
    ViewBag.Message = “Your application description page.”;

    return View();
    }

    I am overriding the CheckAccess method

    public class AreWeAllowedToDoItManager : ClaimsAuthorizationManager
    {
    public override bool CheckAccess(AuthorizationContext context)
    {
    var resource = context.Resource.First().Value;

    switch (resource)
    {
    case “CanView”:
    {
    if (PrincipalCanPerformActionOnResource(context))
    return true;

    break;
    }
    default:
    {
    throw new NotSupportedException(string.Format(“{0} is not a valid resource”, resource));
    }
    }

    return false;
    }

    What is happening is if the user is not authorized, it just coming back to CheckAccess method and not throwing Not authorized error.

    Please help me

    • Andras Nemes says:

      Hello,

      I’m not an OWIN guru myself either so I’m not really sure where the problem lies. I have a series based on my tests with OWIN here but I’ve never gone any deeper than that.

      //Andras

  14. Wouter says:

    How can I use the ClaimsAuthorize to restrict users based on a route parameter?

    Suppose an action like this:
    ”’
    [ClaimsAuthorize(“Create”, “Course”)]
    public ActionResult Create(int departmentId, Course course)
    {
    //Logic to create a course for current department
    }
    ”’

    The user has a “Create” claim for the resource “Course”. But now I want to restrict the user to only create courses for some departments.
    And on top of that, someone could have just view access in one department and additinal create access in another and update access in a third department… How do you advise for handling such cases?

    • Andras Nemes says:

      Hello,
      I think you’ll need to dig deeper in the list of claims of the user. I don’t see any way to declare that in the claims authorize attribute, if that’s what you meant. There could be a special claim type listing the department IDs the user has access to. If they try to create a course for an ID that’s not in the claims list then access is rejected.
      You’ll need to create a separate View controller action with “View” and “Course” as resources. Then check the user’s claims list whether they have view access to the requested department.
      //Andras

      • Wouter says:

        Thanks for your answer.

        Thats what I thought. Only I think that’s not really a scalable option. Suppose a User has the following rights:

        for dept #1: Read only
        for dept #2: Read & update
        for dept #3: Read, create & update

        If I make a claim Departments with value [1,2,3] its not sufficient. I could adjust the claims to Course_1 – Course_3 but then I have to make claims from Course_1:Read to Course_3:Update. This gives me already 6 claims for one resource with 3 departments. In the system I’m building I have already 10 “departments” and 6 resources. If this extrapolates I need already 120 claims and I’ve barely started the real app.

        I’ll probably change my solution to use something less granular.

  15. KarlZ says:

    I hope I have this wrong and that you can correct me, but it seems that resource/operation doesn’t solve much.

    My Hope: A user might have two resources – address, and salary. They can view and edit address, but they can only view salary. I’d hoped there would be a constructor for a Claim that would take Claim(string resource, string operation). Then I could add these claims:
    new Claim(“Address”, “View”), new Claim( “Address”, “Edit”) new Claim(“Salary”, “View”)
    Then if I did [ClaimsPrincipalPermission(SecurityAction.Demand, Operation = “Edit”, Resource = “Salary”)] it would not permit access, because there was no Salary/Edit claim.

    Reality?: But it seems that a user ends up with Resources(Address, Salary) and Operations(Read, Edit) meaning that if did [ClaimsPrincipalPermission(SecurityAction.Demand, Operation = “Edit”, Resource = “Salary”)] it would return true? As long as it finds Edit in the list and Salary they’re good to go?

    I really hope I’m wrong and you can point me to a blog that sends me in the right direction.
    I thank your for all your posts as the others do. Very, very informative.

  16. Santosh Jha says:

    Hi Thanks for the series of tutorial – it very clear and to the point ..
    I have implemented the solution but at the time of debugging I am getting redirected to the page to show the source code of “ClaimsAuthorization.cs” and also have read the comments but did not found the way to redirect to the some page or open a pop up.
    And I also want to use the the method style to bypass some function or code snippet. but unable to find the way – like

    [ClaimsAuthorize(“CanCreateAdmins”, “TenantAdmin”)]
    public string CreateClient()
    {
    return “Client Created”;
    }

    Thanks

  17. dude says:

    that Thinktecture.IdentityModel is like 6 years old and said support mvc4 and webapi.. It has not been updated since 2014, Is there anything for an mvc5 application that is more current.

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.