Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying ASP.NET Web API Security Essentials
  • Table Of Contents Toc
  • Feedback & Rating feedback
ASP.NET Web API Security Essentials

ASP.NET Web API Security Essentials

By : Gunasundaram
2.3 (3)
close
close
ASP.NET Web API Security Essentials

ASP.NET Web API Security Essentials

2.3 (3)
By: Gunasundaram

Overview of this book

This book incorporates the new features of ASP.NET Web API 2 that will help you to secure an ASP.NET Web API and make a well-informed decision when choosing the right security mechanism for your security requirements. We start by showing you how to set up a browser client to utilize ASP.NET Web API services. We then cover ASP.NET Web API’s security architecture, authentication, and authorization to help you secure a web API from unauthorized users. Next, you will learn how to use SSL with ASP.NET Web API, including using SSL client certificates, and integrate the ASP.NET Identity system with ASP.NET Web API. We’ll show you how to secure a web API using OAuth2 to authenticate against a membership database using OWIN middleware. You will be able to use local logins to send authenticated requests using OAuth2. We also explain how to secure a web API using forms authentication and how users can log in with their Windows credentials using integrated Windows authentication. You will come to understand the need for external authentication services to enable OAuth/OpenID and social media authentication. We’ll then help you implement anti-Cross-Site Request Forgery (CSRF) measures in ASP.NET Web API. Finally, you will discover how to enable Cross-Origin Resource Sharing (CORS) in your web API application.
Table of Contents (11 chapters)
close
close
10
Index

Implementing authentication in HTTP message handlers

For a self-hosted web API, the best practice is to implement authentication in an HTTP Message Handler. The principal will be set by the message handler after verifying the HTTP request. For a web API that is self-hosted, consider implementing authentication in a message handler. Otherwise, use an HTTP module instead.

The following code snippet shows an example of basic authentication implemented in an HTTP module:

public class AuthenticationHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
                                                               CancellationToken cancellationToken)
        {
            var credentials = ParseAuthorizationHeader(request);

            if (credentials != null)
            {
                // Check if the username and passowrd in credentials are valid against the ASP.NET membership.
                // If valid, the set the current principal in the request context
                var identity = new GenericIdentity(credentials.Username);
                Thread.CurrentPrincipal = new GenericPrincipal(identity, null);;
            }

            return base.SendAsync(request, cancellationToken)
                .ContinueWith(task =>
                {
                    var response = task.Result;
                    if (credentials == null && response.StatusCode == HttpStatusCode.Unauthorized)
                        Challenge(request, response);

                    return response;
                });
        }

        protected virtual Credentials ParseAuthorizationHeader(HttpRequestMessage request)
        {
            string authorizationHeader = null;
            var authorization = request.Headers.Authorization;
            if (authorization != null && authorization.Scheme == "Basic")
                authorizationHeader = authorization.Parameter;

            if (string.IsNullOrEmpty(authorizationHeader))
                return null;

            authorizationHeader = Encoding.Default.GetString(Convert.FromBase64String(authorizationHeader));

            var authenticationTokens = authorizationHeader.Split(':');
            if (authenticationTokens.Length < 2)
                return null;

            return new Credentials() { Username = authenticationTokens[0], Password = authenticationTokens[1], };
        }

        void Challenge(HttpRequestMessage request, HttpResponseMessage response)
        {
            response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", request.RequestUri.DnsSafeHost));
        }

        public class Credentials
        {
            public string Username { get; set; }
            public string Password { get; set; }
        }
    }
Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
ASP.NET Web API Security Essentials
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon