ASP.NET Web API - Screencast series Part 6: Authorization - Jon Galloway

ASP.NET Web API - Screencast series Part 6: Authorization

We're concluding a six part series on ASP.NET Web API that accompanies the getting started screencast series. This is an introductory screencast series that walks through from File / New Project to some more advanced scenarios like Custom Validation and Authorization. The screencast videos are all short (3-5 minutes) and the sample code for the series is both available for download and browsable online. I did the screencasts, but the samples were written by the ASP.NET Web API team.

In Part 1 we looked at what ASP.NET Web API is, why you'd care, did the File / New Project thing, and did some basic HTTP testing using browser F12 developer tools.

In Part 2 we started to build up a sample that returns data from a repository in JSON format via GET methods.

In Part 3, we modified data on the server using DELETE and POST methods.

In Part 4, we extended on our simple querying methods form Part 2, adding in support for paging and querying.

In Part 5, we added support for Data Annotation based validation using an Action Filter.

In Part 6, we'll require authentication using the built-in Authorization Filter.

[Video and code on the ASP.NET site]

Requiring Authorization using the Authorization Filter

In Part 5, we use a custom Global Action Filter to enforce validation on every Action. In this (final) part, we'll use the built-in Authorize Filter. As with other Filters, they can be applied at the Action, Controller, or Global levels. In this case, we'll add it at the controller level by adding the AuthorizationFilter attribute.

[Authorize] 
public class CommentsController : ApiController  
{ 
    ...
}

That's it from the server side. If a client makes an unauthorized request, the AuthorizationFilter does the only thing that makes sense for an HTTP API - it returns an HTTP Status Code 401, Authorization Required. Again, we're back to the value of using HTTP for an API - we don't need to arrange anything, any client on any platform will know what an HTTP 401 response means.

Handling Redirection on the Client

Many websites (and web frameworks) handle authorization by doing a server-side redirection to a login page. I wrote an in-depth post about how ASP.NET MVC handles authorization redirection - internally an HttpUnauthorizedResult (HTTP 401) is intercepted by the FormsAuthenticationModule, which redirects to Login URL specified in web.config.

None of that makes sense from an HTTP API perspective, though. HTTP API's return HTTP Responses to clients, which include things like Status Codes, Response Body, and Headers. It's up to the client to decide what to do when they get a 401. In this JavaScript / browser based sample, we'll just redirect to the login page on the client.

$(function () { 
    $("#getCommentsFormsAuth").click(function () { 
        viewModel.comments([]); 
        $.ajax({ url: "/api/comments", 
            accepts: "application/json", 
            cache: false, 
            statusCode: { 
                200: function(data) { 
                    viewModel.comments(data); 
                }, 
                401: function(jqXHR, textStatus, errorThrown) { 
                    self.location = '/Account/Login/'; 
                } 
            } 
        }); 
    }); 
});

In this case, logging in gives you a valid forms auth cookie, so your next request will pass authorization.

What about other validation scenarios?

If you want to do something different with validation in an ASP.NET Web API controller, usually the best approach is to create a custom Authorization Filter which derives from the base AuthorizationFilterAttribute and overrides the OnAuthorization method. Here a few blog posts showing how to extend authentication in ASP.NET Web API:

On the client, it's up to you. You may want to show a login form in a desktop application, handle things programmatically when accessing the service via code, etc. You'll follow the same pattern, though - handle the HTTP 401 status code and login to the server, either by posting to a login action or following the service's documented login API.

The End... and Where To Next

That wraps up this series. Some ideas of where to go next:

Published Friday, March 23, 2012 4:55 PM by Jon Galloway
Filed under: ,

Comments

# re: ASP.NET Web API - Screencast series Part 6: Authorization

This example might be misleading to less experienced developers.

The point of the API is to be consumed by the machine/code, not by humans. Therefore, redirecting to the login Web page makes no sense whatsoever because the client is software that does not care about nicely formatted web login page, but rather a way to login programmatically.

On top of that, hardcoding the path to the login page is simply wrong, the response should have included the link to the login "page".

I hope I'm not sounding too negative here, I really do love Web API but times before less-than-ideal examples like this one have led to similar code in production because people look at everything coming from Microsoft as guidance.

Sunday, April 15, 2012 5:25 AM by Drazen Dotlic

# re: ASP.NET Web API - Screencast series Part 6: Authorization

wow, awesome post.Thanks Again.

Tuesday, September 11, 2012 7:13 AM by lawl

# re: ASP.NET Web API - Screencast series Part 6: Authorization

A round of applause for your article post.Much thanks again. Awesome.

Wednesday, September 12, 2012 4:13 PM by Bill Roberson

# re: ASP.NET Web API - Screencast series Part 6: Authorization

I really liked your article.Much thanks again. Really Great.

Wednesday, September 12, 2012 6:52 PM by roofer in Massachusetts

# re: ASP.NET Web API - Screencast series Part 6: Authorization

Very informative blog.Really looking forward to read more. Want more.

Wednesday, September 12, 2012 10:47 PM by satnam

# re: ASP.NET Web API - Screencast series Part 6: Authorization

Interesting, but still I would like to know more about it. Liked the article:D

Friday, September 14, 2012 12:20 AM by Denver Nightlife

# re: ASP.NET Web API - Screencast series Part 6: Authorization

Appreciate you sharing, great blog post.Really looking forward to read more. Great.

Friday, September 14, 2012 9:21 AM by find out more here

# re: ASP.NET Web API - Screencast series Part 6: Authorization

This is one awesome blog.Thanks Again. Much obliged.

Monday, September 17, 2012 7:43 AM by rent mechanical bulls

# re: ASP.NET Web API - Screencast series Part 6: Authorization

Really appreciate you sharing this article.Thanks Again. Want more.

Monday, September 17, 2012 11:16 AM by hillcrest dentist

# re: ASP.NET Web API - Screencast series Part 6: Authorization

Wow, great post.Really looking forward to read more.

Monday, September 17, 2012 2:20 PM by this website

# re: ASP.NET Web API - Screencast series Part 6: Authorization

This is one awesome blog.Really looking forward to read more. Really Cool.

Thursday, September 20, 2012 1:15 AM by How to talk to girls

# re: ASP.NET Web API - Screencast series Part 6: Authorization

I am so grateful for your post.Much thanks again. Really Cool.

Thursday, September 20, 2012 3:49 AM by best canadian wine

# re: ASP.NET Web API - Screencast series Part 6: Authorization

I value the blog article.Much thanks again. Want more.

Thursday, September 20, 2012 11:16 AM by Around the world

# re: ASP.NET Web API - Screencast series Part 6: Authorization

Thanks for the blog post.Thanks Again.

Friday, September 21, 2012 9:56 AM by best stop snoring aids

# re: ASP.NET Web API - Screencast series Part 6: Authorization

Wow, great blog. Really Cool.

Friday, September 21, 2012 4:39 PM by video production

# re: ASP.NET Web API - Screencast series Part 6: Authorization

A round of applause for your article.Much thanks again. Will read on...

Friday, September 21, 2012 7:18 PM by kate middleton

# re: ASP.NET Web API - Screencast series Part 6: Authorization

Say, you got a nice blog article. Cool.

Saturday, September 22, 2012 1:05 AM by internet advertising

# re: ASP.NET Web API - Screencast series Part 6: Authorization

Im obliged for the post.

Sunday, September 23, 2012 3:00 AM by recipes made healthy

# re: ASP.NET Web API - Screencast series Part 6: Authorization

I really enjoy the article post. Much obliged.

Sunday, September 23, 2012 8:35 AM by turnkey gift

# re: ASP.NET Web API - Screencast series Part 6: Authorization

Muchos Gracias for your article.Thanks Again. Keep writing.

Sunday, September 23, 2012 3:58 PM by New York City

# re: ASP.NET Web API - Screencast series Part 6: Authorization

Muchos Gracias for your blog post. Great.

Monday, September 24, 2012 6:57 AM by Alexander Mans

# re: ASP.NET Web API - Screencast series Part 6: Authorization

Say, you got a nice article.Thanks Again. Want more.

Tuesday, September 25, 2012 1:37 PM by tattoos

# re: ASP.NET Web API - Screencast series Part 6: Authorization

Thanks a lot for the blog post.Really looking forward to read more. Awesome.

Wednesday, September 26, 2012 3:22 AM by zquiet

# re: ASP.NET Web API - Screencast series Part 6: Authorization

Im grateful for the blog post.Thanks Again. Much obliged.

Wednesday, September 26, 2012 4:37 AM by orange county auto glass repair

# re: ASP.NET Web API - Screencast series Part 6: Authorization

Appreciate you sharing, great blog.

Wednesday, September 26, 2012 9:34 AM by cuentos cortos en inglés

# re: ASP.NET Web API - Screencast series Part 6: Authorization

I really enjoy the blog.Thanks Again. Really Cool.

Wednesday, September 26, 2012 12:02 PM by followers

# re: ASP.NET Web API - Screencast series Part 6: Authorization

Muchos Gracias for your post.Much thanks again. Fantastic.

Wednesday, September 26, 2012 2:26 PM by hypnosis training

# re: ASP.NET Web API - Screencast series Part 6: Authorization

Fantastic article. Cool.

Wednesday, September 26, 2012 5:09 PM by Peter Francis-Macrae

# re: ASP.NET Web API - Screencast series Part 6: Authorization

I really like and appreciate your article.Really looking forward to read more. Keep writing.

Wednesday, September 26, 2012 10:51 PM by Peter Francis-Macrae

# re: ASP.NET Web API - Screencast series Part 6: Authorization

Extremely easy by words but in reality�, a lot of things don`t correspond. Not everything is so rosy..!

Thursday, September 27, 2012 5:05 PM by income v