Showing posts with label OWIN. Show all posts
Showing posts with label OWIN. Show all posts

Monday, August 15, 2016

Customizing ASP.NET Identity using OWIN

When it comes to customizing ASP.NET Identity, there is not a lot of information on just how to accomplish this since Microsoft primarily expects you to use ASP.NET Identity out-of-the-box.

That is not to say, that there aren't ANY articles on customizing ASP.NET Identity, but they are definitely few and far between!

I found one such very helpful article on customizing ASP.NET Identity using OWIN here: http://benfoster.io/blog/aspnet-identity-stripped-bare-mvc-part-1

This is a 2-part article, so the other part can be found here: http://benfoster.io/blog/aspnet-identity-stripped-bare-mvc-part-2


Monday, July 27, 2015

Setting up OWIN for ASP.NET Web API from scratch

If you start out with either an ASP.NET MVC or ASP.NET Web API project using the option "No Authentication", you may notice that you will not get support for OWIN included in your project by default!

Therefore, you will have to add OWIN functionality back into your application step-by-step.

You can use these articles as starting points, but they are missing several pieces of information for hosting ASP.NET Web API in a standard Web Host:

http://www.asp.net/aspnet/overview/owin-and-katana/getting-started-with-owin-and-katana

http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api

Below are the steps that are needed to accomplish this by adding the appropriate NuGet packages:

  •  Microsoft.AspNet.WebApi.Owin
  • Microsoft.Owin.Security.OAuth
  • Microsoft.Owin.Security.Jwt
  • Microsoft.AspNet.WebApi.Cors
  • Microsoft.Owin.Host.SystemWeb
















Friday, July 24, 2015

Reading Claims from an OAuth Bearer Token

If you are using OWIN and OAuth in your ASP.NET Web API Web Application, like me, you may not know how to read back the Claims from the Bearer Token so that you can use them in your .NET Client.

Unfortunately, this information is incredibly difficult to find!!

Fortunately, there were a few code samples scattered over the web which allowed me to piece together a suitable solution.

Below is the code needed to read back the Claims from the resultant SecurityToken:
public static JwtSecurityToken GetJwtToken(string url, string userName, string password)

    {

        var pairs = new List<KeyValuePair<string, string>>

        {

            new KeyValuePair<string, string>("grant_type", "password"),

            new KeyValuePair<string, string>("username", userName),

            new KeyValuePair<string, string>("password", password)

        };

 

        var content = new FormUrlEncodedContent(pairs);

 

        using (var client = new HttpClient())

        {

            var response = client.PostAsync(url, content).Result;

            var result = response.Content.ReadAsStringAsync().Result;

 

            //Deserialize the JSON into a Dictionary<string, string>

            Dictionary<string, string> tokenDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(result);

            var handler = new JwtSecurityTokenHandler();

            return handler.ReadToken(tokenDictionary["access_token"]) as JwtSecurityToken;

        }//using

    }

You will need to reference the following assemblies/NuGet packages to use this code on the client:
  1. System.IdentityModel
  2. Microsoft.Owin.Security.Jwt

Then, once you have returned the JwtSecurityToken, you simply need to write code such as the following to read back the Claims:

JwtSecurityToken token = OAuthClientWrapper.GetJwtToken(Url, userName, password);

 

Console.WriteLine("Claims in OAuth Bearer Access Token:");

 

foreach (var tokenClaim in token.Claims)

{

    Console.WriteLine(string.Format("{0}:{1}", tokenClaim.Type, tokenClaim.Value));

}//foreach

Saturday, April 18, 2015

Configuring Visual Studio for SSL

If you are using OWIN and OAuth2, you may have encountered a requirement to develop using SSL.

Well, fortunately, developing with SSL using Visual Studio is extremely easy!

First, click on the Project Properties (Properties Window) for the ASP.NET Web Project:






You can also get to this Properties Window by selecting the Properties Window from the View menu:


Then choose the SSL Enabled option and change it to "True"




This will immediately provide you with an SSL URL for browsing your Web Application.  The first time you browse your SSL Web Application, you will get the following 2 dialogs:




Since it is a self-signed SSL certificate, you may get the following warnings (shown for Firefox):






Once you Confirm the Security Exception, you will be able to browse your Web Application using a Secured Url!




Wednesday, April 1, 2015

ASP.NET MVC 5 with OWIN

If you have read about OWIN/Project Katana and ASP.NET MVC, there seems to be some confusion as to whether or not ASP.NET MVC currently supports OWIN/Project Katana or not.

Well, I decided to create a brand new ASP.NET MVC 5 Project just to see if OWIN/Project Katana was truly included as part of the ASP.NET MVC 5 Default Project Template.







As you can see from the screenshots above, OWIN support is DEFINITELY INCLUDED as part of ASP.NET MVC 5 as is indicated by the inclusion of the Startup.cs file!!

This article provides a good overview of how to use OWIN in your ASP.NET MVC 5 Project: http://blogs.msdn.com/b/webdev/archive/2013/07/03/understanding-owin-forms-authentication-in-mvc-5.aspx


Monday, March 30, 2015

Testing Authorization Header Bearer Tokens with OAuth2 and ASP.NET Web API

If you are testing your OAuth2 ASP.NET Web API Host, you are probably going to use a tool that allows you to test your ASP.NET Web API endpoints such as Telerik Fiddler.

Unfortunately, if you are not using a tool that automatically provides the correct header information values for you, you are left to look up those appropriate values yourself since Fiddler does not provide any default header information.

If you want to generate your Bearer Token, you can set up Fiddler to pass the following parameters in the Request Body like so:





Once you have obtained the Bearer Token, in the Composer Headers section, you type in the following:


Authorization: Bearer <bearer token>

Therefore, your Fiddler Composer screen will look something like this:





That is all there is to it!!

Sunday, March 29, 2015

Secure ASP.NET Web API with Windows Active Directory and Microsoft OWIN Components

If you are looking to secure your ASP.NET Web API using OWIN/Katana with just "plain old" Windows Active Directory, unfortunately, you will only find articles like the following on securing your application:

http://www.cloudidentity.com/blog/2013/12/10/protecting-a-self-hosted-api-with-microsoft-owin-security-activedirectory/

https://msdn.microsoft.com/en-us/magazine/dn463788.aspx

As you can tell from the above articles, these articles specifically address "Azure Active Directory"!

But if you want to secure your application with just standard Windows Active Directory, you won't find much guidance in that arena.

Fortunately, plugging in Windows Active Directory support into your OWIN/OAuth Pipeline is not that much more difficult than using standard Forms Authentication with Active Directory as I have outlined in my previous article: http://samirvaidya.blogspot.com/2015/03/aspnet-mvc-forms-authentication-with.html

The main element to take away from standard Forms Authentication is the use of the Membership API to validate your Active Directory User Credentials and plug it into the OWIN/OAuth Pipeline. 

Therefore, if you use a code sample from my earlier OAuth article references (http://samirvaidya.blogspot.com/2015/03/aspnet-web-api-owinkatana-and-jwt.html), you can simply modify the ValidateClientAuthentication method to include code such as the following:

public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)

{

    try

    {

        var username = context.Parameters["username"];

        var password = context.Parameters["password"];

 

        //Use the Active Directory Membership Provider to authenticate the user credentials

        if (Membership.ValidateUser(username, password))

        {

            context.OwinContext.Set("otc:username", username);

            context.Validated();

        }

        else

        {

            context.SetError("Invalid credentials");

            context.Rejected();

        }

    }

    catch

    {

        context.SetError("Server error");

        context.Rejected();

    }

    return Task.FromResult(0);

}

That is all there is to it!!




Saturday, March 28, 2015

Implementing Refresh Tokens using OAuth2, OWIN and ASP.NET Web API

If you want to implement Refresh Tokens in your OWIN application with OAuth2, searching for how to accomplish this is not the easiest thing to find on the web.

Fortunately, Dominick Baier comes to the rescue regarding this topic: http://leastprivilege.com/2013/11/15/adding-refresh-tokens-to-a-web-api-v2-authorization-server/

This thread provides a much simpler solution to Dominick Baier's implementation of Refresh Tokens, but may not meet all of your needs and does not address overriding the GrantRefreshToken method in the
OAuthAuthorizationServerProvider class:  http://stackoverflow.com/questions/20637674/owin-security-how-to-implement-oauth2-refresh-tokens

However, when I implemented the 2 solutions in conjunction with the solution provided by Scott Allen: http://odetocode.com/blogs/scott/archive/2015/01/15/using-json-web-tokens-with-katana-and-webapi.aspx

I ended up with the following results when using the Stack Overflow solution:





As you can from the screenshot above in Fiddler, I am getting a Refresh Token back as expected.

However, when implementing Dominick Baier's solution, I got the following result:


Instead of getting the Refresh Token back as expected, I obtained an as:client_id value back.  Therefore, the code sample as posted in the article does not present a complete solution and is probably dependent on many other aspects in the solution to get everything working as expected.  You can get the full source code for Dominick Baier's solution here: https://github.com/IdentityModel/Thinktecture.IdentityModel/tree/master/samples/OAuth2/EmbeddedResourceOwnerFlowWithRefreshTokens

For your convenience, I have provided the a variation of the code from the Stack Overflow article as well as Scott Allen’s code here:
public class ApplicationRefreshTokenProvider : AuthenticationTokenProvider

{

 

    private int _tokenExpiration;

 

    public ApplicationRefreshTokenProvider()

    {

        _tokenExpiration = Convert.ToInt32(ConfigurationManager.AppSettings["TokenExpiration"]);

    }

    public override void Create(AuthenticationTokenCreateContext context)

    {

        // Expiration time in seconds

        int expire = _tokenExpiration;

        context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddMinutes(expire));

        context.SetToken(context.SerializeTicket());

    }

 

    public override void Receive(AuthenticationTokenReceiveContext context)

    {

        context.DeserializeTicket(context.Token);

    }

 

}



OAuthOptions = new OAuthAuthorizationServerOptions

{

    TokenEndpointPath = new PathString("/Token"),

    Provider = new ApplicationOAuthProvider(),

    AccessTokenFormat = new MyJwtFormat(),

    RefreshTokenProvider = new ApplicationRefreshTokenProvider(),

    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(tokenExpiration),

    AllowInsecureHttp = true

};

Friday, March 20, 2015

Getting an OAuth Bearer Token from a .NET Client

If you have read this article (http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client), you probably already know how to call ASP.NET Web API from a .NET Client.

However, you may not be sure how to get an OAuth Bearer Token from a .NET Client in order to be able to use it throughout your Client Application.

Well, fortunately, it is actually relatively simple to accomplish this!

You can simply use an HttpClient Post to make the appropriate call to the OAuth Token Service:
public BearerToken GetOAuthToken()
{
 
    BearerToken token = null;
 
    var pairs = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("username", "myusername"),
        new KeyValuePair<string, string>("password", "myusername"),
        new KeyValuePair<string, string>("grant_type", "password")
    };
 
    var content = new FormUrlEncodedContent(pairs);
 
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 
        // New code:
        HttpResponseMessage response = client.PostAsync(new Uri("http://localhost:9000/Token"), content).Result;
        if (response.IsSuccessStatusCode)
        {
            token = response.Content.ReadAsAsync<BearerToken>().Result;
        }
    }//using
 
    return token;
}

The code for the BearerToken class is as follows:

 



public class BearerToken
{
    public string access_token { get; set; }
 
    public string expires_in { get; set; }
 
    public string token_type { get; set; }
}

 

Therefore, your call to your method will look like this:

 


var token = client.GetOAuthToken();
string access_token = token.access_token;

If you then want to send the Bearer Token along in a subsequent ASP.NET Web API Request, you just have to make sure that you set the Authorization Header like so:



httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", OAuthToken);

That is all there is to it!!




Thursday, March 19, 2015

No OWIN authentication manager is associated with the request

I have recently begun working with OWIN/Katana in order to introduce OAuth2 support to my ASP.NET Web API Applications.

Well, after following some code samples and attempting to browse to my ASP.NET Web API Controller Methods, I received the following error message:



No OWIN authentication manager is associated with the request

On one of my brand new Web API projects, I noticed that I was missing an assembly reference to:

Microsoft.Owin.Host.SystemWeb 

After updating my project to include this NuGet Package reference, my project started working!

Unfortunately, in another instance of my project, I continued encountering this error.  Even worse,

there are very few articles about the root cause of this error when dealing with OWIN/Katana.  In fact, there are still very few articles overall dealing with OWIN/Katana in general.

In any case, I started digging around the project and looking at how OWIN/Katana was doing its processing and as it turns out, Web API was not getting added to the ASP.NET Web API Pipeline!!

I was using some code which was calling an OWIN Module and then immediately setting up the OAuth Server like so:

public void ConfigureAuth(IAppBuilder app)

   {

       

       OAuthOptions = new OAuthAuthorizationServerOptions

       {

           TokenEndpointPath = new PathString("/Token"),

           Provider = new ApplicationOAuthProvider(),

           AccessTokenFormat = new MyJwtFormat(),

           AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),

           AllowInsecureHttp = true

       };

 

       app.UseOAuthAuthorizationServer(OAuthOptions);

 

   }


This was somehow truncating the ASP.NET Web API Processing directly out of the OWIN Pipeline, thus resulting in that error message.

As soon as I modified my Startup class and moved the call to setting up the OAuthAuthorizationServer OUTSIDE of the module, my Web API Controller started working again!

This was the final code I was able to get working:




public void ConfigureAuth(IAppBuilder app)

    {

        

        OAuthOptions = new OAuthAuthorizationServerOptions

        {

            TokenEndpointPath = new PathString("/Token"),

            Provider = new ApplicationOAuthProvider(),

            AccessTokenFormat = new MyJwtFormat(),

            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),

            AllowInsecureHttp = true

        };

 

 

 

    }



public partial class Startup

{

    public void Configuration(IAppBuilder app)

    {

        

 

        // Enable the application to use bearer tokens to authenticate users

        ConfigureAuth(app);

        app.UseOAuthAuthorizationServer(OAuthOptions);        

    }

}




ASP.NET Web API OWIN/Katana and JWT

If you are interested in using ASP.NET Web API with OWIN/Katana and JWT (JSON Web Tokens), there is very little documentation to get you started on this path from Microsoft.

Fortunately, this article does a pretty good job: http://odetocode.com/blogs/scott/archive/2015/01/15/using-json-web-tokens-with-katana-and-webapi.aspx

On the down side, there is no downloadable code sample available and there are lots of defects in the code base:

  1. The first defect is that none of the namespaces that need to be imported are displayed.  Therefore, in the MyJwtFormat class you need to import the System.IdentityModel assembly
  2. In the MyJwtFormat class, you are attempting to sign using a byte array, but the Convert.FromBase64String method fails
  3. If you use a basic string and use Encoding.UTF8.GetBytes, you will get an error message that you need at least 128 bits
  4. The constructor for the MyJwtFormat class does not provide an empty/default constructor, therefore, you will get an error when attempting to call the empty constructor.  Therefore, you will need to add an empty constructor or pass in the OAuthOptions as a parameter.  However, because the MyJwtFormat class is being instantiated in the OAuthOptions set up, you cannot pass it in as a parameter!! 
Here is the corrected MyJwtFormat class for your review:

 
using System;

using System.Collections.Generic;

using System.IdentityModel.Tokens;

using System.Linq;

using System.Text;

using System.Web;

using Microsoft.Owin.Security;

using Microsoft.Owin.Security.OAuth;

 

namespace OAuth2JWTServer

{

    public class MyJwtFormat : ISecureDataFormat<AuthenticationTicket>

    {

        private readonly OAuthAuthorizationServerOptions _options;

 

        public MyJwtFormat()

        {

                

        }

 

        public MyJwtFormat(OAuthAuthorizationServerOptions options)

        {

            _options = options;

        }

 

        public string SignatureAlgorithm

        {

            get { return "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"; }

        }

 

        public string DigestAlgorithm

        {

            get { return "http://www.w3.org/2001/04/xmlenc#sha256"; }

        }

 

        public string Protect(AuthenticationTicket data)

        {

            if (data == null) throw new ArgumentNullException("data");

 

            var issuer = "localhost";

            var audience = "all";

            var bytes = Encoding.UTF8.GetBytes("+zqf97FD/xyzzyplugh42ploverFeeFieFoeFooxqjE=");

            var now = DateTime.UtcNow;

            var expires = now.AddMinutes(60);

            var signingCredentials = new SigningCredentials(

                                        new InMemorySymmetricSecurityKey(bytes),

                                        SignatureAlgorithm,

                                        DigestAlgorithm);

            var token = new JwtSecurityToken(issuer, audience, data.Identity.Claims,

                                             now, expires, signingCredentials);

 

            return new JwtSecurityTokenHandler().WriteToken(token);

        }

 

        public AuthenticationTicket Unprotect(string protectedText)

        {

            throw new NotImplementedException();

        }

    }

}
 
 
 
This article provides a downloadable code sample, however, it is a bit more complex than the article posted by Scott Allen as well as using NuGet Packages outside of the Microsoft software suite (ThinkTecture).  Therefore, you will have to decide for yourself if you want to follow this approach or follow Scott Allen's much simpler approach:  http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/

Sunday, March 15, 2015

Getting started with OAuth2 and ASP.NET Web API

In the past, if you wanted to implement a Token Issuing Service, you would have probably created a Security Token Service using WCF and Windows Identity Foundation.

Well, with the recent releases of ASP.NET Web API, creating such functionality is much easier with support for OAuth2.

In fact, the default ASP.NET Web API Template provides support for OAuth2 out-of-the-box as is outlined in this article: http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api

If you want a slightly more involved and detailed discussion of the individual facets of OAuth2, you can check out this article: http://www.asp.net/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server