WCF TransportCredentialsOnly Configuration

by Rob Cooke 7. September 2010 05:18

For future self-reference (mostly)…

WCF in Framework 3.5 allows you to use a custom user name / password based authentication mechanism to authenticate individual service requests. This is nice.

This functionality (as with seemingly everything else in WCF) involves a tiny amount of code and a ton of configuration. This is less nice.

Note: These steps just allow you to do pretty much the most primitive authentication. Everything sent is still in the clear. So for the love of all things pure (and some that are not) don’t use this in production without with some kind of encryption.

That said, here’s how to set it up…

First, create a class deriving from System.IdentityModel.Selectors.UserNamePasswordValidator. Note, you’ll have to add a reference to System.IdentityModel.dll not System.IdentityModel.Selectors.dll. The SecurityTokenValidationException is in System.IdentityModel.Tokens.

using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using NDL.Data;

namespace NDL.DataService
{
    public class BasicAuthenticationValidator : UserNamePasswordValidator
    {
        private static UserDataManager mUserDataManager;

        /// <summary>
        /// Performs static initialization for the BasicAuthenticationValidator.
        /// </summary>
        static BasicAuthenticationValidator()
        {
            mUserDataManager = XmlDataManager.Instance.UserDataManager;
        }

        /// <summary>
        /// Performs validation using the given user name and password.
        /// </summary>
        /// <param name="userName">The user name supplied.</param>
        /// <param name="password">The password supplied.</param>
        public override void Validate(string userName, string password)
        {
            //Let the lower layer handle the authentication.
            if (mUserDataManager.AuthenticateUser(userName, password) == false)
            {
                throw new SecurityTokenValidationException("Authentication failed.");
            }
        }
    }
}

With the easy part out of the way, you now have to set up the service’s configuration to start using it.

In the binding section on both the server and client, modify the security configuration to enable TransportCredentialsOnly security mode.

<security mode="TransportCredentialOnly">
    <transport clientCredentialType="Basic" proxyCredentialType="None" realm="" />
    <message clientCredentialType="UserName" algorithmSuite="Default" />
</security>

Next, in the behavior section, set the validation mode and specify the type we created to handle the authentication.

<serviceCredentials>
    <userNameAuthentication 
        customUserNamePasswordValidatorType="NDL.DataService.BasicAuthenticationValidator,
 NDL.DataService" 
        userNamePasswordValidationMode="Custom"/>
</serviceCredentials>

Finally, you can set the credentials on the UserName property of the service client’s ClientCredentials property.

//Set up the service proxy.
DataServiceClient client = new DataServiceClient();
client.ClientCredentials.UserName.UserName = "user";
client.ClientCredentials.UserName.Password = "supersecret";

//Execute some service calls....
client.RetrieveCustomerList();

That’s it! I guess it’s really not that bad. (Ask me again in a few months when I’ve forgotten it all again…)

References:

Tags:

Been Busy!

by Rob Cooke 7. September 2010 05:13

The last month or so has been a bizarre whirlwind of real life for me. Here are some of the highlights:

  • Back to school
  • New team at work
  • More work at work
  • Apartment lease negotiations
  • Best friends moved across the country
  • New fitness cram plan
  • New personal projects
  • Turning 30…

With longer days, I’ve been pretty sapped by the time I have any free time and haven’t been able to write much. Hopefully, I’ll be able to break that cycle this week!

Tags:

Stack Overflow

by Rob Cooke 28. July 2010 05:50

If you've been coding with any kind of newish technology recently, you've undoubtedly ended up on Stack Overflow at some point or another. For the uninitiated, Stack Overflow is a site for programmers helping programmers. More than just a question-answer forum dedicated to specific technologies, Stack Overflow has a global board that allows anyone who knows about any question to post an answer without having to drill down to dedicated boards. This lets each question hit a much larger audience than a question to a specific board might otherwise receive. To further encourage responses, there is a reputation system in place that allows users to build reputation for asking particularly good questions or giving particularly good responses. As users gain more reputation, they gain more rights in the system to the point where users with very high reputation have moderator-like rights such as editing or removing posts by other users. Additionally, users can use their reputation to place bounties on difficult to answer questions or to down-vote poor questions or responses. Beyond the reputation system, there is a badge system that give badges to users for achieving certain "in-game" goals.

I've known about Stack Overflow for a couple of years now, but my involvement had been mostly limited to reading questions and responses that showed up in a Google result list. I had given a few responses anonymously, but I had never asked anything on the site and I generally didn't browse questions outside of what I was currently researching. It wasn't that I wasn't interested in the content or community, it was just that I was usually able to find my own answers with a pretty good certainty. In the last few months, however, I found myself hitting the site more and more and whenever I'd look up a specific question, I would inevitably visit the main page just to see what other people were asking about. Finally, at some point or another, I started running into questions to which I had good responses and I broke down and made a login. This has really changed my perspective on the site!

First, I was taken back by how addictive the site is. You start getting reputation and badges right off the bat and it very quickly becomes a game and you'll find yourself refreshing the site every few minutes trying to catch good questions to answer.

The technology agnostic format of the site really provides for developing a broader awareness of technologies. I may be an expert C# developer, but I know next to nothing about Ruby or Objective C. Reading questions about Ruby and Objective C adjacent to questions about C# increases my awareness of these technologies -even if I'm not actively using them in project. Moreover, it may inspire me to take a closer look due to the "I didn't know you could do that..." and "That's a cool language feature..." effect.

Gaining reputation is easier than I expected. You get a fairly good serving reputation for every up vote your question or response receives.

Answering questions is harder than expected. Easy questions are typically answered in seconds by other posters. Even if you are quick enough to get one of the first responses, there is a chance that a particularly easy question will be closed as a duplicate or down voted for being too trivial. Questions that have been open for more than a couple of hours are often difficult and may require deep research or coding before you can even get an answer. It's kind of frustrating to spend an hour digging up something obscure only to refresh the post and find that someone else just posted your exact response. At that point you just hope that you have something more to add to it!

Even questions in your area of expertise can be difficult to answer. With so many experts swimming in the pool, anything that hasn't been snatched up is likely to be something obscure or extremely deep. These kinds of questions can do a lot to improve your understanding even of technologies you've been using every day for years.

All said, participating in Stack Overflow is a surprising amount of fun. It's great mental exercise and provides amazing opportunities to deepen your knowledge about technologies both in and outside of your area of use.

Tags: ,

Programming

Comment Spam

by Rob Cooke 15. July 2010 01:43

Apparently, the latest thing in internet shenanigans is to have a bot post complementary comments to random blogs. (Speculatively to raise the search engine score of the author or the author’s website.) I guess the theory is that anyone narcissistic enough to have their own blog is less likely to delete a positive comment no matter how random and unwarranted.

“I’m glad I chose to read this one. Nice work!”

While some of these are subtle, some are simply over the top.

“Superbly written material, if only all website owners offered the same quality information as you, the internet would be a far better place. Please keep it up! Cheers.”

/blush –Okay, not even I am that narcissistic…

Then there is the out of touch…

“I just thought I would drop by and see what's happening. I've read this blog before and wanted to come back to see what's going on. Looks great.“

I just started this blog three days ago… …not to mention the comment was on the very first post!

Here’s some more of the same combined with lazy grammar / English…

“What's happenin, I'am a long time reader but first time poster.Please keep up the good stuff.  Your avid reader, <name omitted>”

…and, finally, the just plain bizarre…

“By visiting your webpage, the first impression for me is strong. I can’t imagine when and why you share this great topic but don’t spread it with social bookmarking. This information can be published as reference in online journal, or even in press release site. An early improvement in your site is great, can give us more time in your website. Would you mind if I capture several screenshot as my collection, because I’ve joined several researches? General purpose for me is to tell you about this discussion. My critical question for us is the resource that you have used to manage this site. In order to make great discussion, you are great because you post new topic in several areas. But, I suggest in giving personal opinion, please refer to big or authority sites, I am sure you will be fine in giving past or future experiences. In my environment, I am sure your capability to enrich people can be strong advantage for your future.”

Okay, so maybe that last one isn’t complementary –or is it… I can’t really tell. In any case, I’ll be moderating heavily for a while to see if the automatic spam filter starts catching these. If not, I’ll probably have to restrict or pre-approve comments. If you post something and I over-moderate it, use the contact form and let me know!

Tags:

Code Test

by Rob Cooke 13. July 2010 02:33

As part of getting my blog back up and running I’ve been trying out some code formatters. After trying out the formatter at http://www.manoli.net/csharpformat/ and being a bit disappointed, I found a good stackoverflow response suggesting Windows Liver Writer with Paste From Visual Studio plugin. This seems to work far better than I had expected and it isn’t specific to C#!

The rest of this post is just showing off the code formatting on a generic priority queue I wrote this weekend for a Traveling Salesman demo.

Start by adding the relevant namespaces.

using System;
using System.Linq;
using System.Collections.Generic;

In order to make our priority queue completely generic, we create a generic queue node type to associate each data item with its priority score.

/// <summary>
/// A basic generic priority queue node.
/// </summary>
/// <typeparam name="T">The data type to be wrapped by associated instances.</typeparam>
internal class PriorityQueueNode<T>
{
    /// <summary>
    /// Gets or sets the item associated with this instance.
    /// </summary>
    public T Item { get; set; }

    /// <summary>
    /// Gets or sets the integer priority associated with this instance.
    /// </summary>
    public int Priority { get; set; }

    /// <summary>
    /// Creates a string representation of this PriorityQueueNode instance.
    /// </summary>
    /// <returns>A string representation of this PriorityQueueNode instance.</returns>
    public override string ToString()
    {
        return String.Format("[{0}:{1}]", Item, Priority);
    }
}

Next, we build the priority queue class itself. Note that we are using the new SortedSet<> class from .NET 4.0. I’ll have to get into that in a future post. (For the impatient, here’s a pretty good Code Project article on it.) Essentially, all this code is doing is setting up the queue around the SortedSet<> instance and associating an IComparer instance with it.

/// <summary>
/// Represents a simple generic priority queue.
/// </summary>
/// <typeparam name="T">The data type to use with the associated instances.</typeparam>
internal class PriorityQueue<T>
{
    private SortedSet<PriorityQueueNode<T>> mItems;
    private IComparer<PriorityQueueNode<T>> mComparer;

    /// <summary>
    /// Initializes a new instance of the PriorityQueue class.
    /// </summary>
    public PriorityQueue()
    {
        mComparer = new PriorityComparer<T>();
        mItems = new SortedSet<PriorityQueueNode<T>>(mComparer);
    }

Next, we implement the basic queue operations. For this queue we are defining the three most common queue operations:

  • Enqueue() – Add a node with its priority.
  • Dequeue() – Remove the first node.
  • Peek() – Get the first node without removing it.
    /// <summary>
    /// Enqueues the given item with the given priority.
    /// </summary>
    /// <param name="item">The item to enqueue.</param>
    /// <param name="priority">The priority to associate with the given item.</param>
    public void Enqueue(T item, int priority)
    {
        PriorityQueueNode<T> node = new PriorityQueueNode<T>()
        {
            Item = item,
            Priority = priority
        };

        mItems.Add(node);
    }

    /// <summary>
    /// Removes the lowest priority valued item and returns it.
    /// </summary>
    /// <returns>The lowest ranked item from the queue.</returns>
    /// <exception cref="InvalidOperationException">
    /// An InvalidOperationException is thrown if the queue is empty.
    /// </exception>
    public T Dequeue()
    {
        if (mItems.Count == 0)
        {
            throw new InvalidOperationException("Queue is empty.");
        }

        //Grab the first node, remove it, and return it.
        PriorityQueueNode<T> node = mItems.First<PriorityQueueNode<T>>();
        mItems.Remove(node);
        return node.Item;
    }

    /// <summary>
    /// Returns the lowest priority valued item without removing it from the queue.
    /// </summary>
    /// <returns>The lowest ranked item from the queue.</returns>
    /// <exception cref="InvalidOperationException">
    /// An InvalidOperationException is thrown if the queue is empty.
    /// </exception>
    public T Peek()
    {
        if (mItems.Count == 0)
        {
            throw new InvalidOperationException("Queue is empty.");
        }

        //Grab the first node and return it.
        return (mItems.First<PriorityQueueNode<T>>()).Item;
    }

Really, there isn’t too much interesting going on here except for the use of LINQ to grab the first item. SortedList<> doesn’t implement indexers the way that other collection classes do so this was an easy way to grab the first item.

With the queue implemented, the last thing you need is just to implement an IComparer that can be used to compare two priority queue nodes when the SortedSet<> rebalances itself internally. Depending on how you implement the comparer, you can dramatically change the way the queue operates. (For example having it dequeue higher ranked items rather than lower ranked items as I implemented it.) For my implementation, I use the default CompareTo() methods to compare the integer priorities and then check on an equal priority to see if the items are actually the same item. This sorts the queue so that the lowest ranked elements are returned first –exactly what I needed for my Traveling Salesman demo.

/// <summary>
/// Compares two PriorityQueueNodes.
/// </summary>
/// <param name="x">The first node to compare.</param>
/// <param name="y">The second node to compare.</param>
/// <returns>An integer indicating the relative position of x to y.</returns>
public int Compare(PriorityQueueNode<T> x, PriorityQueueNode<T> y)
{
    int compareValue = x.Priority.CompareTo(y.Priority);
    return ((compareValue == 0) && (x.Item.Equals(y.Item) == false)) ? (-1) : compareValue;
}

Just a few footnotes…

  • If you feel so inclined, you can implement multiple IComparer classes and implement your queue to choose one at runtime. This is probably a better way to do it if you’re looking for reuse.
  • This particular implementation is certainly not thread-safe. Something to keep in mind.
  • Also, if you throw away thread safety, you can probably make the IComparer instance in the PriorityQueue<> class static to avoid having a new instance of the comparer for each priority queue instance. I didn’t bother for my demo because I was going to have exactly one instance of the queue, but it crossed my mind.

Tags: ,

C# | .NET

A Good Theme is Hard to Find

by Rob Cooke 12. July 2010 05:15

Out with the Old

I've been wanting to get back to posting for some time now, but time has been at a premium. Still somehow today I finally got the motivation to start looking at setting up my blogspace again. Last time around I tried using DotNetNuke with a blogging module that they provided. If you've never used it before, DotNetNuke is a very powerful content management system for .NETish environments. There are tons of modules, themes, and plugins available for it and it is backed by a very active community. Unfortunately, I ran into two issues with it.

First, my entire purpose for installing it was just to provide support for the blog module. The DotNetNuke blog module was still a fairly early version at that point and a lot of the features associated with more developed blogging tools like WordPress or MovableType were either absent or required some workarounds to reproduce similar features.

The second issue I ran into I attribute a bit to the popularity of DotNetNuke. Unfortunately, the internet is what it is and any software of sufficient popularity is going to come under attack from script kiddies. In my case, someone either used an exploit in DotNetNuke or managed to crack an admin account in the CMS and was able to create a text file in a content directory. From there they posted a link to the file on a brag site which Google conveniently enough decided to show as one of the top hits for my site.  (Isn't that awesome!) I really had nobody to blame except myself on this one. It had been probably close to a year since I installed DotNetNuke and I hadn't been diligent on updates. I have no idea whether being up-to-date would have prevented it, but certainly running old code with well-known exploits isn't the best way to keep your site off the hacked lists.

Ultimately, due to the combination of these two issues, I ended up uninstalling DotNetNuke and started rethinking what I wanted to do with this space.

In with the New

After a few months of being mostly too busy to even think about this, I accidentally found some motivation to put something back together. For rather boring reasons I needed to temporarily host a file for someone and that meant digging out all my connection information again and bringing myself back up to speed on the state of my site. Once I got into it though, I realized it might end up being less of a chore than I had worried about. So, yet again, I went shopping for blogging software, but this time around I’m trying out BlogEngine.NET.

This brings me to the title… I’ve been playing with themes to try to find something more or less professional, but not so stuffy. There are quite a few available out there, but just about everything I’ve found has had some little quirk (like bullet points that render out of frame or something similar) that makes me hold off committing to it. Right now, I’m sticking with one of the defaults, but expect it to change soon!

Oh… and this time I plan on keeping up-to-date with the updates. BlogEngine.NET isn’t as popular as DotNetNuke, but you can still Google up exploits on it in a few seconds.

Tags:

Blog | BlogEngine.NET

Powered by BlogEngine.NET 1.6.1.0
Theme by Mads Kristensen | Modified by Mooglegiant