Welcome

You have reached the blog of Keith Elder. Thank you for visiting! Feel free to click the twitter icon to the right and follow me on twitter.

Securing Web Services With Username and Password

Posted by Keith Elder | Posted in .Net, Asp.Net, Programming | Posted on 06-01-2007

32

I was going through my news feeds this morning and stumbled across this article about securing web services.  The article is short and doesn’t give any examples of one of the methods I use a lot.  I thought I would elaborate on one of the topics it touches on which is securing a web service with a Username and a Password.  While there are other ways to secure web services I find this particular method works really well when dealing with internal systems that may not speak .Net.  It is also simple to implement on both sides.  These systems could be in Java, PHP or even 4GL.  If you are a .Net developer and want to secure a web service with a username, password, or even other information, here is what you need to get going.

1.  Create an object that extends SoapHeader

The first thing you need to do is create an object that extends the built-in SoapHeader object.   The object can be simple or complex. Add the tokens you want to authenticate against.  Here is a sample:

    1 /// <summary>

    2 /// Extends from SoapHeader and provides a username / password

    3 /// for web methods that need authentication.

    4 /// </summary>

    5 public class ServiceAuthHeader : SoapHeader

    6 {

    7     public string Username;

    8     public string Password;

    9 }

2.  Add a property to your service class that uses the class above

Once you’ve created your base soap header class, add it as a property to your service class.

    // SoapHeader for authentication

    public ServiceAuthHeader CustomSoapHeader;

3.  Attribute the method you want to secure

Add the SoapHeader attribute to each or certain methods you wish to secure pass in the name of the property that is defined as the SoapHeader object in step 2.

    1     [WebMethod]

    2     [SoapHeader(“CustomSoapHeader”)]

    3     public int AddTwoNumbers(int x, int y)

    4     {

    5        

    6         return x + y;

    7     }

4.  Create a method to process your SoapHeader for authentication

The last big step is to create a static method that will take in your custom soap header class and process it for validation.  The first thing we want to do is make sure that some type of credentials were passed in the SoapHeader and that the properties we are looking for are not null.  Finally we want to validate each property contains the information we are looking for. This could be read from the web.config file, database, or other places.

 

    1 public class ServiceAuthHeaderValidation

    2 {

    3     /// <summary>

    4     /// Validates the credentials of the soap header.

    5     /// </summary>

    6     /// <returns></returns>

    7     public static bool Validate(ServiceAuthHeader soapHeader)

    8     {

    9         if (soapHeader == null)

   10         {

   11             throw new NullReferenceException(“No soap header was specified.”);

   12         }

   13         if (soapHeader.Username == null)

   14         {

   15             throw new NullReferenceException(“Username was not supplied for authentication in SoapHeader.”);

   16         }

   17         if (soapHeader.Password == null)

   18         {

   19             throw new NullReferenceException(“Password was not supplied for authentication in SoapHeader.”);

   20         }

   21 

   22         if (soapHeader.Username != “myusername” || soapHeader.Password != “mypassword”)

   23         {

   24             throw new Exception(“Please pass the proper username and password for this service.”);

   25         }

   26         return true;

   27     }

   28 }

5.  Add validation to service method

 

    1     [WebMethod]

    2     [SoapHeader(“CustomSoapHeader”)]

    3     public int AddTwoNumbers(int x, int y)

    4     {

    5         // Test to see if the proper credentials were passed in.

    6         ServiceAuthHeaderValidation.Validate(CustomSoapHeader);

    7 

    8         // If we get this far the user has been validated.

    9         return x + y;

   10     }

 

That’s it. You now have all the pieces of the puzzle to process a request and validate the credentials of the calling client via a username and or password.  If we launch the solution we will see that our XML for our service has been updated and now contains an XML Node called ServiceAuthHeader which contains two sub nodes: username, password.

Passing SoapHeader Credentials To Your Service

Now that we have our service secured, we need to now call the service and pass the credentials expected from a client.  Based on the example above, once you add a web reference to the service and instantiate the service in code, the thing you want to look for is a new property of your service proxy called ServiceAuthHeader. This is converted into a property called ServiceAuthHeaderValue.  This property needs to be an instantiation of the ServiceAuthHeader class where you set the username and password properties.  Here is an example of a console application calling our service and passing the required information to authenticate.

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Text;

    4 

    5 namespace ConsoleApplication1

    6 {

    7     class Program

    8     {

    9         static void Main(string[] args)

   10         {

   11             localhost.Service service = new ConsoleApplication1.localhost.Service();

   12             localhost.ServiceAuthHeader header = new ConsoleApplication1.localhost.ServiceAuthHeader();

   13             header.Username = “myusername”;

   14             header.Password = “mypassword”;

   15             service.ServiceAuthHeaderValue = header;

   16             int x = service.AddTwoNumbers(1, 1);

   17             Console.WriteLine(x);

   18             Console.ReadLine();

   19         }

   20     }

   21 }

 The return result will be 2 of course and from the client side it is rather trivial to pass the credentials as you see.   That’s it.   Happy authenticating!

[Related Link]
To take authenticating one step further with a custom SoapExtension read this follow up article.
http://keithelder.net/blog/archive/2007/01/09/Take-Securing-Web-Services-With-Username-and-Password-One-Step.aspx

 

Redirecting Old WordPress Articles to SubText Articles After Migrating Blogs

Posted by Keith Elder | Posted in Programming | Posted on 03-01-2007

1

Since I recently migrated all of my blogs to SubText, I wanted to make sure that anyone visiting the old links on my WordPress blog were automatically redirected to the new location of all the past articles.  I have been blogging “on record” since April of 2000.  By “on record” I mean that I still have the posts going back that far within this blog.  That’s almost seven years!  Obviously there is a lot of content and things are linked from all over the Internet.  Trying to minimize the move damage here is what I did to redirect the old blog URLs to the new location in SubText.

If you are migrating from WordPress to SubText, add the code below to the top of your index.php file and of course change the URL to match your own.  It should be fairly simple to understand.  The code takes the incoming REDIRECT_URL server variable and checks to see if it ends in a slash or is just a slash.  Depending on state, a URL string is built up which points to the new location of the article within the SubText blog. 

In order for this to work flawlessly, when you import your WordPress articles into SubText, be sure you save the data in the database column called “post_name”.  This is the column that takes the titles and replaces spaces with dashes and so on.  Otherwise you’ll never get a match via the title.  As a result of adding this to WordPress anyone visiting an old link will be redirected.

Example

http://blog.zorka.com/2001/03/18/priceless-for-everything-else-there-is-mastercard

will now redirect the user to:

http://keithelder.net/blog/archive/2001/03/18/priceless-for-everything-else-there-is-mastercard.aspx

 

As a side benefit that I didn’t think about when I originally wrote this is it allows links that view postings by date to be redirected as well. 

Example

http://blog.zorka.com/2001/04

will be redirected to:

http://keithelder.net/blog/archive/2001/04.aspx

Apple Leopard Talks Roaming The US, but what’s the point?

Posted by Keith Elder | Posted in Programming | Posted on 07-11-2006

0

It seems Apple has started to reach out more to its developers by putting together what they are calling “Leopard Tech Talks“. A lot of you may be surprised by me posting something about Apple since I write .Net code during work hours but I am a customer of theirs (1 iPod, 2 Notebooks, 1 Airport). However, I still play with an enormous amount of technologies from all walks of life (Microsoft, Apple, Open Source, Linux, etc). I’m a geek, live with it. 🙂 I started writing this post to say, cool, Apple is finally reaching out to the developer community. Then reality set in and went, wait, they are doing what for who? I would LOVE to go to this and give ’em my $.02 about their platform (the good and the bad). The closest talk near me is Atlanta but I have friends who are closer to the talks than me. Maybe they’ll go for me and tell them just how bad their development environment for Enterprise application developers is on their platform. Beyond Apple having a lot of “look at me developers” (the guys that write one off cool plugins) and “small dev shops” (that fill the gap where Apple left off) can anyone point to a single Enterprise using all Apple technology? Ummmm, no. The reason is Apple doesn’t care about the Enterprise. They care about selling more iTunes, iPods and dual core Powerbooks to the Left Wing Open Source club (of which I am a founding member). Yes I like using Macs at home, but honestly, that doesn’t pay the bills. When I go to work, I need several things to get my job done, of which Apple provides zero infrastructure. Sure I can listen to iTunes while coding on their iPod and dual boot their Powerbook into Windows but what does that really buy me other than, “hey, watch this, this is cool, haha”. Here is a list of things I need to develop in an Enterprise that Apple is missing the boat on:

  1. Update-to-date Language – Sorry Apple, but I don’t call Objective-C an update-to-date language. I read the first several pages on why you chose the language on your developer site and honestly, the reason you chose it is because it did objects, big whipty doo. Get a life. Why not at least something newer? You sorta embrace Java but yet you don’t. I don’t get it.
  2. IDE – Yes, I need an IDE to write applications with. While Xcode is what you tout as the end all be all IDE, it is lacking in a lot of areas (just search the internet, there has been plenty said already on this topic of Visual Studio vs XCode so I’m not going to repeat it).
  3. No MSDN – One day Apple will wake up and realize that what Microsoft has started that is called MSDN blows away ANYTHING they have (I thought Apple was user friendly?). The MSDN documentation, samples, downloads, tutorials and more make it extremely easy to find what you need. There is always communication from MSFT to the developers. Here is what is coming in version X.X. Apple you are so secretive you don’t even tell your employees what is coming next! How is a business suppose to plan? How is a developer suppose to ready his applications on the next release? The big factor of MSDN is subscribers can download almost all of the Microsoft platform and run it on up to 10 computers. All of the tools to develop with are there at your finger tips.
  4. Lack of community – While I may not be able to solve all my developing problems on the .Net platform by staring at intellisense, there are communities where I can derive help from ( newsgroups, msdn.microsoft.com, MS sponsored forums, etc.). Apple, where is yours?
  5. No Biztalk – Sorry but you don’t have anything anywhere close to a Biztalk for routing messages and having different systems talk to one another. Oh, sorry, I forgot you sell hardware, I’ll move on (then why are you having this developer thing then?)
  6. Web Services – Ever try to write a web service in Objective C or XCode? Good luck with that.
  7. Database – Where is your enterprise database? I can get SQL Server from Microsoft and you know what, it is pretty damn good. What cha got for me? How about: null.
  8. Exchange – While I am at work I have a question. How will I send and receive messages while scheduling meetings, tasks, and todos? Are you going to force me into using qmail as an MTA? Fair enough then. Next question, how do I schedule meetings with my co-workers, with iCal? Are you kidding me?
  9. Portal – I tried to install your non-existent portal so co-workers could find internal information but failed.

Honestly I could keep going but it is Monday Night during November and that means Monday Night Football so I am not going to bother. I think you get my tone. These are the reasons Apple hasn’t cracked the Enterprise and the reasons why it will not. I hear people say things like, “Well, why don’t you use Apple for everything?” or “I think we should use all Macs.”. The bottom line is WTF are they thinking? Beyond this person spilling their personal feelings for which “hardware” they think a company should buy, they feel that buy using Apple products in the Enterprise it will make everyone’s lives magically easier. To these people I say, thank God, you aren’t the decision maker(s) in corporate America. And, if you are, there is this place called http://www.dice.com and http://www.monster.com to look for jobs online. The bottom line is this. I wouldn’t mind developing for the Apple platform being a developer, the problem is A) only a hand full of people have them at work, B) I’m not keen on learning on unmanaged language like Objective-C and C) they are missing some important pieces surrounding their platform for the Enterprise. Until those things are resolved I’ll buy an occassional product from you Apple if it fits my “iLife” but that is about it.

Seriaizing Objects in web.config

Posted by Keith Elder | Posted in Asp.Net, Programming | Posted on 31-08-2006

0

Jeff Atwood posted an article about serializing objects in the web.config file a few weeks ago on his blog.  I recently gave a presentation on creating custom configSections in web.config by creating custom SectionHandlers.  One day I’ll write it up and post it to here how its done.  Until I get time to write that up, you may want to check out what Jeff has going on with creating an object, then serialzing it, and then storing it in the web.config file.  Of course you could use app.config as well.

The most interesting nugget that came out of the comments was a reference to the ConfigurationPropertyAttribute that Jarrod Dixon pointed out.   I hadn’t heard about this but it is a nice thing to know because it declartively instructs the .Net framework to instanatiate a configuration property.

Codesmith and .NetTiers thoughts

Posted by Keith Elder | Posted in .Net, Programming, Smart Clients | Posted on 27-07-2006

2

I was catching up on some blog reading tonight and saw where Daniel had posted about using Codesmith and .NetTiers to generate code.  I’ve been using this for several months myself but hadn’t gotten around to blogging about it.

Quick intro to what it is.  Codesmith is a client app that users templates to generate code.  .NetTiers is an open source projected that provides templates to generate a n-tiered architecture.  If you watched my video cast of building a three tiered architecture in Visual Studio, using these two tools can quickly create the business and datalayer for a project.  Obviously it isn’t going to write business objects for you with all of your validation rules, but it does provide a start (if you think business objects are database records, which I don’t fully agree with).  On the Codesmith site you’ll find a nice 15 minute tutorial which can explain better how they work together.

The thing I use the most with .NetTiers is validating business entities.  Let’s say you have a Contact table in a database.  After .NetTiers runs, it will create a business object called “Contact”.  This object is generated into two partial class files typically called:

  • Contact.cs
  • Contact.generated.cs

The generated file shouldn’t be modified, the other you can modify.  Typically you will add a new method called “AddValidation()” to the Contact.cs object called from the constructor which adds all of your business rules.  For example, FirstName and LastName are required fields.  First and Last name much pass a regular expression validation before saving.  There is a folder in the businesslayer that .NetTiers generates called Validation where there are several generic objects to assist you with common validation rules. You can also add your own.  For example, you could write a method to have the database check to make sure no one else has the first and last name in the database before saving it.  The validation rules use delegates so you can write any method or logic you need to do validation.  Here’s some sample validation code:

    1 Validation.CommonRules.CompareValueRuleArgs<int> schemaValidationArgs =   new Validation.CommonRules.CompareValueRuleArgs<int>(“SchemaValidationId”, 0);

    2             schemaValidationArgs.Description = “Schema Validation is a required field and must be greater than 0.”;

In the example above the property SchemaValidatoinId must be great than 0.   The way the validation in .NetTiers is setup is based on a collection of validation rules.  Once your list of rules is established you simply need to invoke the Validate() on the object.  Validate then processes all of the rules in the list, making calls out to each delegate as it needs to.  What gets created as a result of this is a BrokenRulesList which is a property of your business entity.  Since I don’t have a contact table handy to generate actual code, here is some sudo code as to how things fit together.

    1 using System;

    2 

    3 /// <summary>

    4 /// Summary description for Contact

    5 /// </summary>

    6 public class Contact : ContactBase

    7 {

    8     public Contact():base()

    9     {

   10         AddValidation();

   11     }

   12 

   13     private void AddValidation()

   14     {

   15         Validation.ValidationRuleArgs nameArgs = new ValidationRuleArgs(“FirstName”);

   16         nameArgs.Description = “First Name is a required field.”;

   17         this.ValidationRules.AddRule(Validation.CommonRules.StringRequired, nameArgs);

   18     }

   19 }

   20 

   21 public class Test

   22 {

   23     Test()

   24     {

   25         Contact contact =  new Contact();

   26         contact.Validate();

   27         if (contact.BrokenRulesList.Length > 0)

   28         {

   29             // whoops, you have errors

   30         }

   31     }

   32 }

 

If you are like me and are writing Smart Clients with web services, the BrokenRulesList gives you an easy way to let user’s know what is wrong.  As a typical pattern, I pass the BrokenRulesList (which contains brokenRule objects) as an out parameter on the web service.  This way I can easily display or handle the errors in the Smart Client so it is friendly to the user.

 

Since you know the property in the BrokenRule object that is causing the problem, along with the description of the error, a quick foreach loop through your input controls on your windows form and you can automatically set ErrorProviders on your controls (same could apply for asp.net).  This could all be automated as well with enough time I think too. 

 

One thing I’ve noticed about some developers using .NetTiers is once they start using it, they want to use it for everything!  This is just wrong.  If you think of it from the standpoint of being able to put business rules and validation on information before it hits the database, you’ll be ok.  It isn’t the swiss army knife of developing apps though. 

 

Here is something else to consider about .NetTiers.  What if you only need to display one record with limited data, one or two columns?  This is where .NetTiers doesn’t help at all because given a primary key or a search filter it will always load the entire record.  To my knowledge there is no way to tell it what to load or not to load into the object.  Which logically speaking makes sense because if you updated the information you wouldn’t be able to pass the business rules of the object to save it.  It’s a catch 22 really.  In this case it is easier to just write your own query.  Sometimes you may not care, but in the enterprise where speed counts, you just can’t afford to be lazy.