@manhng

Welcome to my blog!

Web API 2.2

October 16, 2019 05:18

Web API 2.2 (edit)

ASP.NET WEB API OAuth 2.0 Token Based Authentication: Grant Resource Owner Credentials

GET: http://localhost:1231/api/values (Authorization: Bear ...)

POST: http://localhost:1231/token (application/x-www-form-urlencoded) {username: test@gmail.com, password: 123@Abc, grant_type: password}

https://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/comment-page-4/

https://www.c-sharpcorner.com/article/asp-net-mvc-oauth-2-0-rest-web-api-authorization-using-database-first-approach/

https://www.codeproject.com/Articles/1187872/Token-Based-Authentication-for-Web-API-where-Legac

https://forums.asp.net/t/2154351.aspx?Custom+Jwt+Token+generator+and+Validation+ISecureDataFormat+AuthenticationTicket+

https://stackoverflow.com/questions/47351750/how-to-implement-isecuredataformatauthenticationticket-unprotect-method/54844743#54844743

NuGet Packages

Install-Package EntityFramework -Version 6.3.0
Install-Package Microsoft.AspNet.WebApi.Owin -Version 5.2.2
Install-Package Microsoft.Owin.Security -Version 3.0.0
Install-Package Microsoft.AspNet.Identity.Owin -Version 2.1.0
Install-Package Microsoft.Owin.Host.SystemWeb -Version 3.0.0
Install-Package Swashbuckle -Version 5.2.2

WebApiConfig.cs

using Microsoft.Owin.Security.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
 
namespace WebApi2
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
 
            // Web API routes
            config.MapHttpAttributeRoutes();
 
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Startup.cs

using Microsoft.Owin;
using Owin;
 
[assemblyOwinStartup(typeof(WebApi2.Startup))]
namespace WebApi2
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

Startup.Auth.cs

using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace WebApi2
{
    /// <summary>
    /// https://www.codeproject.com/Articles/1187872/Token-Based-Authentication-for-Web-API-where-Legac
    /// </summary>
    public partial class Startup
    {
        public static OAuthAuthorizationServerOptions OAuthOptions { getprivate set; }
 
        public static string PublicClientId { getprivate set; }
 
        // For more information on configuring authentication, 
        // please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath =
                new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(10),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };
 
            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);
        }
    }
}

Providers \ ApplicationOAuthProvider.cs

Snippet

using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
 
namespace WebApi2
{
    public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
    {
        private readonly string _publicClientId;
 
        public ApplicationOAuthProvider(string publicClientId)
        {
            if (publicClientId == null)
            {
                throw new ArgumentNullException("publicClientId");
            }
 
            _publicClientId = publicClientId;
        }
 
        public override async Task GrantResourceOwnerCredentials
        (OAuthGrantResourceOwnerCredentialsContext context)
        {
            // TODO: MANH
            /*** Replace below user authentication code as per your Entity Framework Model ***
            using (var obj = new UserDBEntities())
            {
                
                tblUserMaster entry = obj.tblUserMasters.Where
                <tblUserMaster>(record => 
                record.User_ID == context.UserName && 
                record.User_Password == context.Password).FirstOrDefault();
 
                if (entry == null)
                {
                    context.SetError("invalid_grant", 
                    "The user name or password is incorrect.");
                    return;
                }                
            }
            */
 
            ClaimsIdentity oAuthIdentity =
            new ClaimsIdentity(context.Options.AuthenticationType);
            ClaimsIdentity cookiesIdentity =
            new ClaimsIdentity(context.Options.AuthenticationType);
 
            AuthenticationProperties properties = CreateProperties(context.UserName);
            AuthenticationTicket ticket =
            new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
 
        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            foreach (KeyValuePair<string,
            string> property in context.Properties.Dictionary)
            {
                context.AdditionalResponseParameters.Add(property.Key, property.Value);
            }
 
            return Task.FromResult<object>(null);
        }
 
        public override Task ValidateClientAuthentication
        (OAuthValidateClientAuthenticationContext context)
        {
            // Resource owner password credentials does not provide a client ID.
            if (context.ClientId == null)
            {
                context.Validated();
            }
 
            return Task.FromResult<object>(null);
        }
 
        public override Task ValidateClientRedirectUri
        (OAuthValidateClientRedirectUriContext context)
        {
            if (context.ClientId == _publicClientId)
            {
                Uri expectedRootUri = new Uri(context.Request.Uri, "/");
 
                if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                {
                    context.Validated();
                }
            }
 
            return Task.FromResult<object>(null);
        }
 
        public static AuthenticationProperties CreateProperties(string userName)
        {
            IDictionary<stringstring>
            data = new Dictionary<stringstring>
            {
                { "userName", userName }
            };
            return new AuthenticationProperties(data);
        }
    }
}

All packages

Install-Package Ninject.Web.WebApi -Version 3.2.4
  + Install-Package Ninject -Version 3.2.4
  + Install-Package Ninject.Web.Common -Version 3.2.4
Install-Package Ninject.Web -Version 3.2.1
Install-Package Ninject.Mvc5 -Version 3.2.1
Install-Package Ninject.WebApi.DependencyResolver -Version 0.1.4758.24814
Install-Package Swashbuckle -Version 5.2.2
  + Install-Package Swashbuckle.Core -Version 5.2.2
Install-Package EntityFramework -Version 6.3.0
---------------------------------------------
 ASP.NET Identity 2.1, ASP.NET Web API 2.2
---------------------------------------------
Install-Package Microsoft.AspNet.Identity.Owin -Version 2.1.0
Install-Package Microsoft.AspNet.Identity.EntityFramework -Version 2.1.0
Install-Package Microsoft.Owin.Host.SystemWeb -Version 3.0.0
Install-Package Microsoft.AspNet.WebApi.Owin -Version 5.2.2
Install-Package Microsoft.Owin.Security -Version 3.0.0
Install-Package Microsoft.Owin.Security.OAuth -Version 3.0.0
Install-Package Microsoft.Owin.Cors -Version 3.0.0
Install-Package Sendgrid -Version 5.0.0
  + Install-Package SendGrid.SmtpApi -Version 1.1.3
Install-Package System.IdentityModel.Tokens.Jwt -Version 4.0.1
Install-Package Thinktecture.IdentityModel.Core -Version 1.3.0
Install-Package Microsoft.Owin.Security.Jwt -Version 3.0.0

Categories

Recent posts