Enable Basic Authetication in Asp.net web.api using Thinktecture.IdentityModel

by sunil ravulapalli /21. August 2013 04:55 /asp.net-web-api /Comments (0)

On Server

1. Install Thinktecture.IdentityModel from Nuget

2. In class WebApiConfig add the function CreateAuthenticationConfiguration() add Lines 1 and 2 like below

public static class WebApiConfig
{ 
    public static void Register(HttpConfiguration config) 
    {  
        var authentication = CreateAuthenticationConfiguration(); // Line 1 
        config.MessageHandlers.Add(new AuthenticationHandler(authentication)); // Line 2  
        config.Routes.MapHttpRoute(   name: "DefaultApi",   routeTemplate: "api/{controller}/{id}",  defaults: new { id = RouteParameter.Optional }  );         
        config.EnableSystemDiagnosticsTracing(); 
     }
     private static AuthenticationConfiguration CreateAuthenticationConfiguration() 
     {  
        var authentication = new AuthenticationConfiguration  
        {   
            RequireSsl = false,   EnableSessionToken = true  
        };  
        // Basic Authentication   
        authentication.AddBasicAuthentication((username, password) => username == "admin" && password == "password");  
        return authentication; 
     }
}

Lets say you have a ApiController like this

public class AccountsController : ApiController
{  
    [Authorize] 
    public AccountInformation Get(long id) 
    {  
         return new AccountInformation { AccountHolderName = "admin" }; 
    }
}

where

public class AccountInformation
{ 
    public string AccountHolderName { get; set; }
}

Run your Api project in visual studio and try to access
http://localhost:xxxxx/api/accounts/token

you should get dialog box asking for username and password. Here our username is "admin" and password is "password". You will then get the JSON response back which looks like this

{  
   "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...2KVb2HV3dP0tqN5NBzesdQhMc2J8Or-_RqaIRWLJpk4...........",  
   "expires_in": 36000.0
}

Now we know our Api stuff works.

How to call from a Client(Windows 8)

From the client the Login method looks like this

private async void Login_Click(object sender, RoutedEventArgs e)
{ 
   try 
   {  
      var credentials = new NetworkCredential("admin", "password");  
      var handler = new HttpClientHandler { Credentials = credentials };  
      var client = new HttpClient(handler) 
      {
        BaseAddress = new Uri("http://localhost:xxxxx/")
       };    
       var response = await client.GetAsync("api/accounts/token");                 
       response.EnsureSuccessStatusCode();  
       var accountInformationJson = await response.Content.ReadAsStringAsync(); 
       var json = JsonObject.Parse(accountInformationJson); 
       var token = json.GetNamedString("access_token");  
       var localSettings = ApplicationData.Current.LocalSettings; 
       localSettings.Values["sessionToken"] = token; 
    } 
    catch (HttpRequestException ex) { } 
    catch (Exception ex) { }
}

The function to get data after the login looks like this

try
{ 
   var localSettings = ApplicationData.Current.LocalSettings; 
   var sessionToken = localSettings.Values["sessionToken"]; 
   var client = new HttpClient() 
   { 
      BaseAddress = new Uri("http://localhost:xxxxx/") 
   }; 
   client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Session", sessionToken.ToString()); 
   var response = await client.GetAsync("api/accounts/123"); 
   response.EnsureSuccessStatusCode(); 
   var accountInformationJson = await response.Content.ReadAsStringAsync(); 
}
catch (HttpRequestException ex){ }
catch (Exception ex){ }

 References

http://leastprivilege.com/2012/06/19/session-token-support-for-asp-net-web-api/

http://ben.onfabrik.com/posts/dog-fooding-our-api-authentication

blog comments powered by Disqus