• May 2024
    M T W T F S S
     12345
    6789101112
    13141516171819
    20212223242526
    2728293031  
  • Latest Posts

  • Latest Comments

  • Archives

ClaimAuthorizeAttribute

Headline: Here is what I use for authorizing controller and actions in an MVC application that uses the new Claims based authorization.

Some Great Resources

Before I even begin, let me point people to some great resources I found today on this topic. The first has so many posts on the topic and they are well written. Check out the Claims based security section:

http://dotnetcodr.com/security-and-cryptography/ by Andras Nemes (Stockholm, Sweden)

The second has quite a few resources too.

http://leastprivilege.com/2012/10/26/using-claims-based-authorization-in-mvc-and-web-api/ by Dominick Baier (Heidelberg, Germany)

Motivation

I spent lots of time looking at claims based security as the new WIF (Windows Identity Foundation) 4.5 has rolled out.

There is an attribute called ClaimsPrincipalPermission that I thought would do the trick. However, I’m not impressed. I’d love to delete this post if someone can show me what I’m doing wrong.

So the usage would be something like:

[ClaimsPrincipalPermission(SecurityAction.Demand, Resource = “Salary”, Operation = “Edit”)]

Now, suppose you have a claims system where you have addresses and salaries as resources. And some people can view both, but only edit the address.

I thought that you had name/value pairs like you do with the System.Security.Claims.Claim which has Type and Value. But it seems that if you add Resources of Address and Salary, and Operations of View and Edit there is no pairing.

So while I might give someone 1) Address/Edit, and Salary/View expecting them to not be able to edit Salary information it will let them.

What I’ve seen is it work this way: Look in all the Resources – do they have Salary? Good, now look in all the Operations – do they have Edit? Great, let them do it!

That’s not what I expected, wanted, and frankly I’ve not yet come up with a scenario where I think it would be useful.

ClaimAuthorize

So what I did instead was create a new attribute called ClaimAuthorizeAttribute.

So now if I have a ClaimIdentity with Claims of new Claim(“Address”, “Edit”) and new Claim(“Salary”, “View”) and place this on the action or controller:

[ClaimAuthorize(ClaimType=”Salary”, ClaimValue=”Edit”)]

The user would not get through.

So here is the code for that. If someone really wants it, I also have all the unit tests for it.

ClaimAuthorizeAttribute
  1. /// <summary>
  2. /// Specifies that access to a controller or action method is restricted
  3. /// to users who meet the claims requirement.
  4. /// </summary>
  5. [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
  6. public class ClaimAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
  7. {
  8.     /// <summary>
  9.     /// Called when a process requests authorization.
  10.     /// </summary>
  11.     /// <param name="filterContext">The filter context, which encapsulates for information
  12.     /// using Ccr.Web.Mvc.ClaimAuthorizeAttribute.</param>
  13.     /// <exception cref="System.ArgumentNullException">The filterContext is null.</exception>
  14.     public void OnAuthorization(AuthorizationContext filterContext)
  15.     {
  16.         if (ReferenceEquals(filterContext, null))
  17.             throw new ArgumentNullException("filterContext");
  18.         if (!IsAuthorized(filterContext.HttpContext, ClaimType, ClaimValue))
  19.             HandleUnauthorizedRequest(filterContext);
  20.     }
  21.  
  22.     // Optional parameters to make unit testing easier.
  23.     internal static bool IsAuthorized(HttpContextBase httpContext, string claimType = "", string claimValue = "")
  24.     {
  25.         if (ReferenceEquals(httpContext, null))
  26.             throw new ArgumentNullException("httpContext");
  27.         var user = httpContext.User;
  28.         if (!user.Identity.IsAuthenticated)
  29.             return false;
  30.  
  31.         var claimsPrincipal = user as ClaimsPrincipal;
  32.         if (ReferenceEquals(claimsPrincipal, null))
  33.             return false;
  34.  
  35.         if (claimsPrincipal.HasClaim(claimType, claimValue))
  36.             return true;
  37.  
  38.         return false;
  39.     }
  40.  
  41.     /// <summary>
  42.     /// Gets or sets the claim type required for access to the controller or action.
  43.     /// </summary>
  44.     public string ClaimType { get; set; }
  45.  
  46.     /// <summary>
  47.     /// Optionally gets or sets the claim value required for access to the controller or action.
  48.     /// If not specified, then "True" will be used. The convention for most claims is that the
  49.     /// value is set to True.
  50.     /// </summary>
  51.  
  52.     private string _claimValue = true.ToString(CultureInfo.InvariantCulture);
  53.     public string ClaimValue
  54.     {
  55.         get { return _claimValue; }
  56.         set { _claimValue = value; }
  57.     }
  58.  
  59.     /// <summary>
  60.     /// Processes HTTP requests that fail authorization.
  61.     /// </summary>
  62.     /// <param name="filterContext">Encapsulates the information for using Ccr.Web.Mvc.ClaimAuthorizeAttribute.
  63.     /// The filterContext object contains the controller, HTTP context, reqest context,
  64.     /// action result, and route data.</param>
  65.     protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext)
  66.     {
  67.         if (ReferenceEquals(filterContext, null))
  68.             throw new ArgumentNullException("filterContext");
  69.         filterContext.Result = new HttpUnauthorizedResult();
  70.     }
  71. }

If someone sees something I’m doing with the ClaimsPrincipalPermission attribute, please let me know.

Thanks – Karl

Team Building

This is an excellent post by Christopher Avery that I frequently use when building a software development team:

5 Easy Steps That Will Make Any Team Better

The “WIIFM” or What’s In It For Me is always interesting.

UPPERCASE Menu Items in Visual Studio

I felt the tension go out of my shoulders today when I found this option!

image

Not sure what caused them to think all caps for the menu options would be a good idea.

My Daily Scrum Routine

Headline: This describes my daily routine as I participate on a virtual team scattered about the globe as we work on a project using the Scrum template.

The Situation

Currently I’m working with a team where no two people are in the same time zone!

We’re using Visual Studio Online (VSO) with the Scrum process template. We also use Visual Studio for our IDE (Integrated Development Environment). The tools are actually quite helpful for virtual teams. I point that out as I describe my daily routine.

Clear Things Out

There are all the non-development tasks. I try to clear those out of the way first. Handle the email on various topics it probably the biggest thing. Then I’m ready to begin.

Visit the Team Room

VSO has the concept of Team Rooms now. I wish I could filter out certain messages about people entering and leaving, but I still find the room valuable. This is where we each do our Daily Standup. Since we’re are scattered all over the globe there isn’t a good time for us all to talk in person each day. So instead, we write out a slightly modified version of the daily standup. Most do “what I did yesterday” and “what I plan to do today” since the daily standups tend to be in the morning.

We modify that and do it at the end of our day stating:

  1. What I did today
  2. What I plan to do tomorrow
  3. Blocking issues

We move pretty fast and by doing it at the end of our day, then the people in the other time zones have the benefit of what we did as soon as we completed it rather than waiting until the next day.

I visit the room at the beginning of the day to read everyone’s daily standup information. That allows me to not work on something if they are and also let’s me get an early start on resolving blocking issues (since I’m sort of the Scrum Master).

Visit the Task Board

In my last post I showed an image of the task board. Each row is either a PBI (Product Backlog Item) or a Bug that the team committed to do in this sprint. These are all in priority order.

Then there are three columns:

  1. To do
  2. In progress
  3. Done

At the beginning of the day I have no tasks in the In progress column, all are either To do or Done. I start at the top of the PBI/Bug list and work my way down. I look for a story I can really help with and prefer items at the top of the list over those further down. Sometimes I don’t have the skill or others have a story handled so I work my way down the list.

I then think about the day and perhaps a few more ahead. If tasks don’t exist yet I’ll create them. I’ll try to make sure that I have at least enough tasks for today. I want to change this so that we have all the tasks identified at the beginning of the sprint, but we’re just not there yet. I also try to break the tasks down into something that can be done in less than a day. I hate having a task go between To do and In progress for days on end.

Next I drag over the Task I plan to work on next and begin.

Develop

Now the fun begins! I strive to do test driven development, but it doesn’t always happen. But I work on the task until I have it done.

Definition of Done

On thing that is important is the Definition of Done. My current project is still ramping up so we don’t have everything “done” just yet, but I think we’ll get there soon (this month). Here is my definition of done for developers on the team:

  • New code has unit tests
  • There are no code analysis warnings using the Microsoft All Rules
  • All public members have XML documentation (///<summary> type)
  • There are no strings in the code – they are all in the Resources file.
  • The code builds
  • There are no failing unit tests
  • When the code is checked in it is associated with 1 PBI and 1 Task
  • The CI (Continuous Integration) build was successful (built and had no failing unit tests)

Now there is a broader definition for the team regarding, “Is the PBI done?” Usually the story is sufficient, but many times we discover something someone didn’t think about up front. These might become new PBIs.

Iterate

Once I check in code, I go back to the task board again, drag something into the In progress column and keep moving.

Close Out The Day

At some point I’m ready to call it a day. I will do this after a check in. I never leave code sitting on my machine overnight. Venkat Subramaniam taught that in a course he taught in 2008. He said if you don’t check it in at night (and it better be good), then delete it all the next day and start again. I’ve been practicing that since then and it’s really help. The day I liked the most was when I spent 9 hours the day before and probably had 800 lines of code. I threw it all away and that day I realized I could do it with about 70 lines of code! The day before just taught me what the real problem was and once I knew it the solution was quite simple.

When I check in, I always associate that with one PBI and one Task (see my previous post).

Next I visit the task board and move any In progress tasks either to Done (but the check in process usually moves those) or more likely, back to In progress.

The final step is to go into the Team Room and write my Daily Standup Report.

When things are moving well (See Super-sonic Software Development) it’s not uncommon for me to have 3 to 6 check ins per day.

Related Work Items to Reinforce Good Process

Headline: Always associate related work items to your changesets upon check-in. This post shows an easy way to do that using a Query that also reinforces the process.

Scrum Sprint Board Overview

Most projects I work on with Visual Studio and Team Foundation Server use the Scrum process template. I also do some work using what is now called Visual Studio Online or VSO. This used to be called Team Foundation Service, but I’ll call it VSO from now on. The Scrum template has a nice flow. I won’t go into too much detail, but below I show what the Sprint Task Board looks like. On the left you have Product Backlog Items (PBIs) with blue left margins (or Bugs with red left margins) and in the three other lanes of To do, In progress, and Done you have Tasks which have yellow left margins.

image

It’s really nice for team members to see what your working on. So I like to make sure that any task I’m working on I move into the In progress column. I make a habit of doing that before I begin working on the task.

Changeset Related Work Items

In my role many times I’ve had to go back and review what work was done for a particular PBI or Bug. If someone says the bug was fixed but there is no associated changeset for the bug I have to ask myself, “Was it closed as not reproducible? Did they ask the right people? How do you fix a bug without changing code?” It is possible, but I hope there’s at least  a comment.

The easiest way to associate Work Items is at the time of checkin.

The Query

So, I said I had a query that made this easy. When you are trying to checkin, in Visual Studio (I’m using 2013 for this post) you see the Related Work Items section that has Queries and Add Work Item by ID.

image

I find it much easier to use a query and then just highlight the PBI (select with a mouse click) and the Task (select with Ctrl+Click so both are now selected) and drag them into that area just as the gray text says, “Drag work items here to link them to the check-in.”

Here is the query I use:

image

There are some groupings there, but they are very faint in the image, so I highlighted that in red. It is a simple query, but you’ll notice that it reinforces good process.

  • A PBI must be committed before it shows up.
  • A Task must be in progress.
  • A Bug must be committed.

You shouldn’t be working on a Bug or PBI if they’re not committed. And Tasks should obviously be In progress and not just in “To do”.

Note: If I’m working on a large team (which I seldom do) then I might change the task section to be Work Item Type = Task And State = In Progress And Assigned To = @Me

@Me is a special placeholder so that you can share the query with others and they don’t need to change that. It can figure out who “Me” is.

For a nicer query I should not that I have a tree view:

image

With these settings:

image

Summary

DO associate work items at the time of check-in.

DO  associate both the Product Backlog Item (or User Story if your using the Agile template) as well as a Task, not just one or the other.

And as you can see, this query forces you to move tasks into the In progress column so that you can easily drag it over into the Related Work Items area of Pending Change when you’re checking in code.

What is a phone?

Headline: Seems the old telephone is going by the wayside… Some observations.

Calling from the desktop

For several years now I’ve not used a phone in the office. Instead I used other audio communications like Microsoft’s Lync or Skype. I have an excellent microphone and speaker setup… Or, if needed, I have some good headphones that I tend to use for more sensitive conversations or if I need to be a bit more quiet.

I can do this because I have the Skype plan that will let me make phone calls to cell phones and landlines.

Just this week a friend of mine told me that at their company they pulled out all the phones and in place of them gave everyone a headset to plug into their computer for making phone calls.

… pulled out all the phones and gave everyone headsets…

Smart Phone or Mini Tablet

I don’t think I’m alone when I say I use my phone for many things, but calling is one of the least used features. I had a phone stolen recently, and since I got my new phone 4 days ago, I’ve still not made a single phone call with it. And when I watch most people, they text rather than talk. Sometimes they text so much I think, “Wouldn’t it be faster to just pick up the phone?” But they don’t.

So today’s cell phones do seem much more like miniature tablets. And some, no so miniature with many phones today having 7” screens! That wasn’t true just a few years ago.

Batching Items with EF 6.0

Headline: It’s not too hard to batch items with or without async capabilities in Entity Framework (EF) 6.0.

Here I have a large number (ok… not in the sample test, but in real life) of items and I’d like to pull them in as in batches rather than wait for all of them to be returned. I’ll go ahead and use async here, even though I know I’m not using it properly…

So here is my sample. It reads 3 items at t time and adds them to the collection. With a little rearranging of the code you could have a decent solution.

Batch Sample
  1. [TestMethod]
  2. public void Batching_Items()
  3. {
  4.     // Arrange
  5.     const int expected = 7;
  6.     var take = 3;
  7.     var skip = 0;
  8.     var locations = new Collection<FieldLocation>();
  9.     using (var repository = new MyRepository())
  10.     {
  11.         repository.Context.Database.Log = Console.Write;
  12.         var count = repository.Items.Count();
  13.         var remaining = count;
  14.  
  15.         // Act
  16.         while (remaining > 0)
  17.         {
  18.             var task = repository.Items.OrderBy(f => f.ReservoirId).Skip(skip).Take(take).ToListAsync();
  19.             foreach (var result in task.Result)
  20.                 locations.Add(result);
  21.             skip += take;
  22.             remaining = count – skip;
  23.             if (take > remaining) take = remaining;
  24.         }
  25.  
  26.         // Assert
  27.         var actual = locations.Count;
  28.         Assert.AreEqual(expected, actual);
  29.     }
  30. }

You can see that the key is the use of the Skip and Take items (and Skip requires the OrderBy). If that code is isolated in a different method then you could use the async to better advantage.

And here’s what happened in the SQL Server:

Test Name:    Batching_Items
Test Outcome:    Passed
Result StandardOutput:   
Opened connection at 3/14/2015 2:36:37 PM -06:00
SELECT
    [GroupBy1].[A1] AS [C1]
    FROM ( SELECT
        COUNT(1) AS [A1]
        FROM (SELECT
    [FieldLocationView].[ReservoirCodeId] AS [ReservoirCodeId],
    [FieldLocationView].[Latitude] AS [Latitude],
    [FieldLocationView].[Longitude] AS [Longitude]
    FROM [dbo].[FieldLocationView] AS [FieldLocationView]) AS [Extent1]
    )  AS [GroupBy1]
— Executing at 3/14/2015 2:36:38 PM -06:00
— Completed in 158 ms with result: SqlDataReader

Closed connection at 3/14/2015 2:36:38 PM -06:00
Opened connection asynchronously at 3/14/2015 2:36:38 PM -06:00
SELECT
    [Extent1].[ReservoirCodeId] AS [ReservoirCodeId],
    [Extent1].[Latitude] AS [Latitude],
    [Extent1].[Longitude] AS [Longitude]
    FROM (SELECT
    [FieldLocationView].[ReservoirCodeId] AS [ReservoirCodeId],
    [FieldLocationView].[Latitude] AS [Latitude],
    [FieldLocationView].[Longitude] AS [Longitude]
    FROM [dbo].[FieldLocationView] AS [FieldLocationView]) AS [Extent1]
    ORDER BY [Extent1].[ReservoirCodeId] ASC
    OFFSET 0 ROWS FETCH NEXT 3 ROWS ONLY
— Executing asynchronously at 3/14/2015 2:36:38 PM -06:00
— Completed in 145 ms with result: SqlDataReader

Closed connection at 3/14/2015 2:36:38 PM -06:00
Opened connection asynchronously at 3/14/2015 2:36:38 PM -06:00
SELECT
    [Extent1].[ReservoirCodeId] AS [ReservoirCodeId],
    [Extent1].[Latitude] AS [Latitude],
    [Extent1].[Longitude] AS [Longitude]
    FROM (SELECT
    [FieldLocationView].[ReservoirCodeId] AS [ReservoirCodeId],
    [FieldLocationView].[Latitude] AS [Latitude],
    [FieldLocationView].[Longitude] AS [Longitude]
    FROM [dbo].[FieldLocationView] AS [FieldLocationView]) AS [Extent1]
    ORDER BY [Extent1].[ReservoirCodeId] ASC
    OFFSET 3 ROWS FETCH NEXT 3 ROWS ONLY
— Executing asynchronously at 3/14/2015 2:36:38 PM -06:00
— Completed in 76 ms with result: SqlDataReader

Closed connection at 3/14/2015 2:36:39 PM -06:00
Opened connection asynchronously at 3/14/2015 2:36:39 PM -06:00
SELECT
    [Extent1].[ReservoirCodeId] AS [ReservoirCodeId],
    [Extent1].[Latitude] AS [Latitude],
    [Extent1].[Longitude] AS [Longitude]
    FROM (SELECT
    [FieldLocationView].[ReservoirCodeId] AS [ReservoirCodeId],
    [FieldLocationView].[Latitude] AS [Latitude],
    [FieldLocationView].[Longitude] AS [Longitude]
    FROM [dbo].[FieldLocationView] AS [FieldLocationView]) AS [Extent1]
    ORDER BY [Extent1].[ReservoirCodeId] ASC
    OFFSET 6 ROWS FETCH NEXT 1 ROWS ONLY
— Executing asynchronously at 3/14/2015 2:36:39 PM -06:00
— Completed in 161 ms with result: SqlDataReader

Closed connection at 3/14/2015 2:36:39 PM -06:00

So, with this approach you could easily build an application that will progressively load your items.

Cheers,

Karl

Bugs–Cradle to Grave

Headline: If you wrote the bug, you should fix the bug.

A friend of mine (Duane) years ago said, “Bugs should be cradle to grave.” And by that, he meant just what I said. If you wrote the bug then you should fix the bug. Why?

Cost

The original developer can almost always find and fix a bug in their code because they understand it. Having someone else do it will take longer and can result in more bugs.

Morale

How would you feel if someone walked into your office and said, “Joe’s moving to the new really cool project. You get to take over his code base and fix all his bugs.” That doesn’t help morale. But if Joe has not bugs, or if he can quickly fix them while also working on the new project people are much happier.

Quality

Obviously if developers know this is my philosophy, they’ll write better code. If they don’t they at least know they will be fixing the bugs. I’ve found over time that this approach leads to much higher quality code.

A True Story

Many years ago I had a developer walk into my office to present me with his resignation letter. I wasn’t particularly distraught over their departure, but I was curious why he was leaving. If there was something in the environment that might cause good developers to leave, I wanted to know it.

He said, “All I ever do is fix bugs. I never get to work on the new projects.”

I said, “We only asked you to fix the bugs you wrote – no one else’s.”

We completely rewrote the software on his departure.

Summary

When you write code, write it with the attitude that no one else on this planet is going to be available to fix the bugs. I take that philosophy which is probably one reason I put so much stock in automated tests. If you do this you, your fellow developers, your managers, and your customers will all be happy.

Our Asynchronous Lives

Headline: There’s something to be said for synchronous…

What is Asynchronous (async for short)?

This is where you ask for something but you continue on and don’t let that block your next action. You fire off a message but you process other actions rather than sit idly by waiting for a response.

This is great for programming, but I now realize how much of my life is async. Facebook is a stellar example. We fire off a series of random activities and if a response is returned great. If not, oh well. On with my life I go. And frankly, this blob post is no different! (Oh that angers me)

Minimize Async in Real Life

But… When in real life I minimize async activities. I’ve been with people that say, “unh huh…” as they text while we’re eating dinner or having a drink. There are entire comedy routines about this sort of thing… Example, “I have 500 friends but I’ve not seen anyone in person all week.”

I’ve been doing async programming for a long time but tonight was the first time I really saw how that has impacted so many personal interactions.

I will have to say that some activities can only be done synchronously… And some of those are the most fun Smile

Bring a little synchronicity back into your life.

A Better PredicateBuilder

Headline: If you are trying to dynamically create queries then Pete Montgomery’s post on A universal PredicateBuilder is a must read.

I found lots of references to PredicateBuilder but there was a lot of code and as this post says that original PredicateBuilder “…requires an unnatural call to… AsExpandable…”

I’m just putting this post here for future reference.

Thanks Pete!