Glimpse for DotNetOpenAuth 1.3

Finally I got a chance tonight to update my DotNetOpenAuth extension for Glimpse. I’ve pushed the update out to Nuget so go ahead and update now.

Install-Package DCCreative.DNOA4Glimpse

 

What does it do?

This extension attaches to the internal logging of DotNetOpenAuth and provides you with a view directly within your browser.

Example of Glimpse for DotNetOpenAuth

The source code and test MVC4 web app have been published to GitHub here

https://github.com/DavidChristiansen/DNOA4Glimpse

Glimpse

The guys at Glimpse have put some really amazing work into Glimpse as of late. Check it out if you haven’t already http://getglimpse.com

Posted in Development (General), DotNetOpenAuth, Glimpse | Leave a comment

How simple is a OpenID Connect Basic client? (C#)

John Bradley has just posted a great entry demonstrating how simple life is going to be for a Relying Party when it comes to OpenID Connect. I highly recommend you go and read it.

OpenID Connect provides a lot of advanced facilities to fulfill many additional features requested by the member community. It is full of features that go beyond basic Authentication. However, that does not mean that it cannot be used for the simple case for “Just Authentication”.

The sample code in John’s post is in PHP so I thought I would quickly provide the same samples in C#. here we go.

Making an OpenID Connect request

In order for the client to make an OpenID Connect request, it needs to have the following information about the server:

  • client identifier – An unique identifier issued to the client (RP) to identify itself to the authorization server. (e.g. 3214244)
  • client secret – A shared secret established between the authorization server and client used for signing requests.
  • end-user authorization endpoint – The authorization server’s HTTP endpoint capable of authenticating the end-user and obtaining authorization. (e.g., https://server.example.com/authorize )
  • token endpoint – The authorization server’s HTTP endpoint capable of issuing access tokens.

In the simplest cases, this information is obtained by the client developer, having read the server’s documentation and pre-registered their application.

Then, for a bear bone authentication request you would put a link like this in the HTML page:

<a href="https://server.example.com/authorize?grant_type=code&scope=openid&client_id=3214244&state=af1Ef">Login with Example.com</a>

The user initiates login by clicking on the “Login with Example.com” link, and is taken to the server where she is asked username/password etc. if she is not logged into example.com yet. Once she agrees to login to  the RP, the browser is redirected back to the call back URL at the RP by 302 redirect. The PHP Server side code may look like:

Response.Redirect("https://client.example.com/cb?code=8rFowidZfjt&state=af1Ef",true);

Note: state is the parameter that is used to protect against XSRF.  It binds the request to the browser session.  It is recommended but not required in OAuth and has been omitted to make the example static.

That should be simple enough?

Calling the Token endpoint to get id_token

Now that the RP has the ‘code’, you need to get the id_token from the token endpoint. The id_token is the user login information assertion.  What do you do? Just GET it with HTTP Basic Auth using client_id, client_secret, and the code you got in the first step. Using C#, it would look like:

var code = Request.Form[”code”];
var client = new WebClient();
NetworkCredential credentials = new NetworkCredential("testuser", "testpass");
client.Credentials = credentials;
client.Headers.Add("Content-Type","application/json; charset=utf-8");
var responseJson = client.DownloadString(new Uri("https://server.example.com/token?code="+code));

The result, responseJson, will contain a JSON like this (line wraps for display purposes only):

{ 
"access_token": "SlAV32hkKG",
"token_type": "Bearer",
"refresh_token": "8xLOxBtZp8",
"expires_in": 3600,
"id_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.
eyJpc3MiOiJodHRwczovL3NlcnZlci5leGFtcGxlLmNvbSIsInVzZXJfaWQiOiIyND.
gyODk3NjEwMDEiLCJhdWQiOiJodHRwOi8vY2iwiZXhwIjoxxpZW50LmV4YW1wbGUuY29tIMzExMjgxOTcwfSA.
eDesUD0vzDH3T1G3liaTNOrfaeWYjuRCEPNXVtaazNQ”
}

For simple authentication we will ignore “access_token”, “token_type” etc. What you only care about is the “id_token”.

“id_token” is encoded in a format called  JSON Web Token (JWT). JWT is the concatenation of “header”, “body”, “signature” by periods (.). Since you are getting this directly through TLS protected channel that is verifying the identity of the server certificate, you do not need to check the signature for integrity, so you just take out the second portion of it and base64url_decode it to get the information out of the id_token. So in PHP you may do something like:

JObject o = JObject.Parse(response);
var token = o.id_token;
var id_array = token.split('.');
var id_body = Convert.FromBase64String(id_array[1]);

The resulting assertion, id_body in the above example,  about the user (after pretty formatting)  is:

{
"iss": https://server.example.com,
"user_id": "248289761001",
"aud": "3214244",
"iat": 1311195570,
"exp": 1311281970
}

“iss” is showing the issuer of this token, in this case, the server.example.com. The issuer must match the expected issuer for the token endpoint, if it is different you must reject the token. the ‘iss” is the name space of the  user_id, which is unique within the issuer and never reassigned.

When the client stores the user identifier, it MUST store the tuple of the  user_id and iss.

“aud” stands for “audience” and it shows who is the audience of this token. In this case, it is the RP’s client_id. If it is different, you must reject the token.

“iat” stands for the time the token was issued.  This can be ignored in this flow as the client is talking directly to the token endpoint.

“exp” is the expiry time of the token. If the current time is after “exp”, e.g., in PHP, if  $exp < time();  the RP should reject the token as well.

So, that is it. Now you know who is the user, i.e., you have authenticated the user.

All of the above in the form of code would be:

private bool checkID(idBody, issuer, clientID){
    JObject o = JObject.Parse(idBody);
    if (o.iss != issuer)
        return false;
    if (o.aud != clientID)
        return false;
    if (o.exp < DateTime.UtcNow)
        return false;
    return true;
}

Once again, be sure to go read John’s post (http://www.thread-safe.com/2012/07/how-simple-is-openid-connect-basic.html)

Posted in OAuth, Security | Comments Off

Solved: Chrome v18, self signed certs and “signed using a weak signature algorithm”

So chrome has just updated itself automatically and you are now running v18 – great. Or is it…

If like me, you are someone that are running sites using a self-signed SSL Certificate (i.e. when running a site on a developer machine) you may come across the following lovely message;

WAT? Try explaining what a weak signature algorithm means to a non-tech!

Fear not, this is likely as a result of you following instructions you found on the apache openssl site which results in a self signed cert using the MD5 signature hashing algorithm.

Using OpenSSL

The simple fix is to generate a new certificate specifying to use the SHA512 signature hashing algorithm, like so;

openssl req -new -x509 -sha512 -nodes -out server.crt -keyout server.key

Simples!

Now, you should be able to confirm the signature algorithm used is sha512 by looking at the details tab of certificate

Confirming the signature algorithm

Notes

  • If you change your certificate, be sure to reapply any private key permissions you require – such as allowing access to the application pool user.
Posted in Development (General) | Comments Off

DotNetOpenAuth: Debugging and Tracing OpenID and OAuth on ASP.NET (or MVC) using Glimpse

Synopsis: Understanding exactly what is happening under the hood when it comes to working with OpenID and OAuth can be challenging even for the seasoned IDM developer. What I have found to help, is being able to see the communications between all the parties involved. Fortunately the DotNetOpenAuth library can be told to expose a plethora of information to the developer via integrated logging. In this post I will talk about a project called Glimpse that exposes a whole host of information to you, the developer, directly within the browser and then I will introduce a Glimpse plugin I have written that exposes all that lovely juicy information directly from DotNetOpenAuth.

In Short

  1. Get DNOA4Glimpse:
    NuGet Command: PM> Install-Package DCCreative.DNOA4Glimpse

What is Glimpse?
(http://getglimpse.com/About)

WhatIsGlimpseGlimpse is a very cool set of utilities that provide developers with a massive array of how requests go about being served, as well as a host of other information about the server itself.

At its core, Glimpse allows you to debug your web site or web service right in the browser. Glimpse allows you to “Glimpse” into what’s going on in your web server. In other words what Firebug is to debugging your client side code, Glimpse is to debugging your server within the client.

Glimpse is available via NuGet at http://nuget.org/List/Packages/Glimpse.

Exposing DotNetOpenAuth to Glimpse

CropperCapture[2]

Writing a plugin for Glimpse is childsplay. Glimpse exposes a friendly Plugin interface

public interface IGlimpsePlugin
{
	string Name { get; }
	object GetData(HttpContextBase context);
	void SetupInit();
}

Simply inherit from IGlimpsePlugin then implement the members in your plugin.

[GlimpsePlugin]
public class DotNetOpenAuthPlugin : IGlimpsePlugin {
	public void SetupInit() {
	//...
	}
	public string Name {
		get { return "DotNetOpenAuth"; }
	}
}

After adding a reference to the assembly containing your plugin, Glimpse will automatically pick up your plugin (thanks to the wonderful powers of MEF).

Demo

I quickly threw together a sample application to test the plugin.

  1. Create a new ASP.NET MVC site based on the DNOA MVC relying party sample.
  2. Add the DNOA4Glimpse package (Install-Package DCCreative.DNOA4Glimpse)
  3. Done (Get the source here)

CropperCapture[2]

Glimpse has been turned on (by visiting //yourwebsiteurl.example.com/glimpse.axd) which results in a panel being displayed at the bottom of your screen. As you can see, there is a DotNetOpenAuth tab. Awesome!

Right, now – let’s do an OpenID Authentication

CropperCapture[4]

What’s really cool is the Glimpse’s handling of complex objects.

CropperCapture[5]

The presentation of complex objects such as the YADIS services detailed above will improve in a version I am currently working on, thanks for some new presentation features coming to Glimpse soon. Watch this space.

So the plugin is still in beta but hopefully you will find it useful.

DNOA4Glimpse and Demo Source is available at https://github.com/DavidChristiansen/DNOA4Glimpse

Posted in DotNetOpenAuth, Security | Comments Off

New Poll : Which .NET Service Bus have you used and recommend.

Posted in Development (General) | Comments Off

An afternoon with Glenn Block – Leith, Edinburgh 12th March 2011

CropperCapture[1]

Exciting news.

I am proud to announce that Glenn Block from Microsoft will be coming all the way from Seattle to Scotland on the 12th March to talk to you!. Glenn is a PM on the WCF team working on Microsoft’s future HTTP and REST stack and has been involved in some pretty exciting and ground-breaking Microsoft development mind-shifts in recent times.

Don’t miss the chance to hear him speak and ask him questions. The day will be split into two parts.

Favourite subjects from The Block
The first couple of hours will see Glenn focus on talking about his current work basket – expect to see him talking about Windows Communication Foundation, web APIs, HTTP, REST, MEF, Patterns & Practices and his experiences at the recent mvcConf 2 event!

Block unblocked chalk talk – your chance to ask Glenn anything he can answer
The second half of the afternoon will be “yours” – a chalk’n'talk if you prefer. It will be your chance to have an open and frank conversation with Glenn, to ask him questions, to challenge him and to get answers to those questions that you’ve been saving for such a celebrity!

Book your for ticket here (Tickets are Free!)

Brief history of Glenn

Glenn is a PM on the WCF team working on Microsoft’s future HTTP and REST stack. Prior to WCF he was a PM on the new Managed Extensibility Framework in .NET 4.0. He has experience both inside and outside Microsoft developing software solutions for ISVs and the enterprise. He has also been active in involving folks from the community in the development of software at Microsoft. This has included shipping products under open source licenses, as well as assisting other teams looking to do so.

Glenn is a featured blogger over at CodeBetter, read what he’s writing about here: http://codebetter.com/glennblock/author/glennblock/

His official Microsoft blog can be found here: http://blogs.msdn.com/b/gblock/

Glenn Block on the web

Sponsored by

stormid
Storm ID is an award winning full service digital agency in Edinburgh

Posted in Development (General) | Comments Off

LogParser–Graphing PING results

Here is a nifty little example of how to pipe console output to Microsoft LogParser, in this case the results of a ping against Google.

ping -n 15 www.google.co.uk | "%pathTologparser%\LogParser"
"SELECT TO_INT(REPLACE_STR(EXTRACT_VALUE (Text,'time',' '),'ms',''))
AS Response INTO Ping.gif FROM stdin WHERE Text LIKE '%%Reply%%'
GROUP BY Response" -i textline -legend off -chartTitle "Ping Times" -view

Note: I have inserted line breaks for readability, this should be written as one line.

Replace %pathTologparser% with the path to your local LogParser installation, typically c:\Program Files\Log Parser 2.2 or c:\Program Files (x86)\Log Parser 2.2 on x64 installations.

Posted in Development (General) | Comments Off

FIX: nHibernate/log4net in windows service. FileNotFoundException

When using nHibernate in a windows service you may find that you encounter FileNotFoundExceptions when trying to load assemblies or external configuration files. Typically this is in scenarios where you are running your service under a user context such as NetworkService.

If you hunt around long enough you will find that it is trying to locate said files in the %WINDIR%\system32 folder (for example c:\windows\system32), and not from the services own directory.

By default window services set the default directory to the %WINDIR%\system32.

Simply change your service’s default directory to wherever your service is running.

Here’s a sample:

// Set current directory to assembly folder
// Need to to this so can find the configuration file for the logger
// default is %WINDIR%\system32 for window services
static void Main(string[] args) {
	Environment.CurrentDirectory = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetEntryAssembly().Location); ///... }
Posted in Development (General) | Comments Off

(Solved) ID6035: Cannot create a HashAlgorithm / “Object Identifier (OID) is unknown”

Implementing the Windows Identity Foundation of Windows Server 2003 and experiencing errors such as the following?

Exception:
System.NotSupportedException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Error Message:
ID6035: Cannot create a HashAlgorithm with name ‘
http://www.w3.org/2001/04/xmldsig-more#rsa-sha256′using the ‘System.IdentityModel.Tokens.X509AsymmetricSecurityKey’ crypto provider. SHA256 may require a minimum platform of Windows Server 2003 and .NET 3.5 SP1.

The same error can be experienced if you try to use FedUtil.exe on Windows 2003. Attempts to do so will result in the following error message;

Object Identifier (OID) is unknown

No doubt you have ensured that you are indeed on Windows Server 2003 (doh!) and indeed have .NET Framework v3.5 with Service Pack 1.

This error is due to, in some cases, the HashAlgorithm not being registered on Windows 2003.

The Fix

Microsoft have published a HotFix that solves this issue. I have found that the hotfix requires a server restart upon installation.

Posted in Development (General) | Comments Off

HOWTO: Creating a Dummy/Mock Webservice (ASMX) from a WSDL File

Sometimes it is helpful to mock a xml webservice for the purpose of testing against it without invoking the actual service. There are several reasons why this can be a good idea, such as when the service is not hosted by you and therefore not under your control or in situations where calls to the service incur some kind of cost.

In my case, I wanted to mock out a service so that the scope of my unit testing was just my integration. I also wanted control over the service response to emulate a range of scenarios.

I would typically have developed a mock implementation using WCF however using an ASMX seemed the simplest method at the time, and I like the (Keep It Simple Stupid) KISS methodology.

So, here are the steps.

Step 1 – Create the ASMX file to host the service

In my case I already have a Test web application from which I host several test service stubs and other things, so it is simple for me to Right Click > New Item > Web Service.

Change the filename to something meaningful, such as <ServiceName>Mock.asmx

Step 2 – Generate a service stub from WSDL

Open a console window, I typically use the console that comes with Visual Studio (Available from start menu) and navigate to the folder containing the ASMX file you generated.

Type the following;

wsdl <URL of WSDL file> /language:CS /server

The URL is the full URL of the service you are wishing to stub out. In particular, I ensure the URL is that of the WSDL file.

/language can be your language of choice, in my case CS for C#.

/server specifies that you are wishing to generate code that would host such a service

A full list of options can by obtained by simply typing wsdl from the command line.

Step 3 – Modify your ASMX to ‘host’ the generated code.

By default the code behind for your ASMX will derive from

System.Web.Services.WebService

You want to change the code behind to derive instead from the code you generated in step 2. To find out which class to derive from, search your generated code for the class decorated with the System.Web.Services.WebServiceAttribute.

Once you have done this, compile your project. If things are as they should be the build should fail because you have not implemented the expected methods of the service.

Implement the services, throwing a

 throw new NotImplementedException();

for now if you like – we just want it to compile.

Once you have done this, compile your project and open your ASMX in Internet Explorer (or your browser of choice)

If all is well, you should see a web page, with the name of the service at the top in a blue panel.

Step 4 – Customise your service logic (Optional)

As i mentioned, I wanted to be able to manage the responses I received from my service. This is done by modifying my implementation of the service that I have just created in the previous steps. Simples.

Posted in Development (General) | Comments Off