@manhng

Welcome to my blog!

Add Web Api To Mvc Application

June 3, 2018 16:27

Jwt + Web API (edit)

https://github.com/cuongle/WebApi.Jwt

Code Sample

https://stackoverflow.com/questions/29196920/can-i-retrieve-userinfo-from-bearer-token-on-server-side-web-api-2

https://stackoverflow.com/questions/36097931/asp-net-identity-currentprincipal-identity-does-not-contain-custom-claim

https://www.microsoftpressstore.com/articles/article.aspx?p=2225067

Nuget Packages

<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0" targetFramework="net452" />
<package id="Microsoft.IdentityModel.Logging" version="1.0.0" targetFramework="net452" />
<package id="Microsoft.IdentityModel.Tokens" version="5.0.0" targetFramework="net452" />
<package id="Microsoft.Net.Compilers" version="1.0.0" targetFramework="net452" developmentDependency="true" />
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net452" />
<package id="System.IdentityModel.Tokens.Jwt" version="5.0.0" targetFramework="net452" />
</packages>

WebAPI + Bearer JWT

using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Filters;

namespace WebApi.Jwt.Filters
{
    public class JwtAuthenticationAttribute : Attribute, IAuthenticationFilter
    {
        ....
        protected Task AuthenticateJwtToken(string token)
        {
            string username;

            if (ValidateToken(token, out username))
            {
                // based on username to get more information from database in order to build local identity
                var claims = new List
                {
                    new Claim(ClaimTypes.Name, username),
                    
                    // TODO: Manh
                    new Claim(ClaimTypes.UserData,"{'Roles':['Admin','Member'],'GOLD':1000000}")
                    // Add more claims if needed: Roles, ...
                };

                var identity = new ClaimsIdentity(claims, "Jwt");
                IPrincipal user = new ClaimsPrincipal(identity);

                return Task.FromResult(user);
            }

            return Task.FromResult(null);
        }
        ....
   }
}

Retrieve User Info from Bearer Token

using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Web.Http;
using WebApi.Jwt.Filters;

namespace WebApi.Jwt.Controllers
{
    public class ValueController : ApiController
    {
        [JwtAuthentication]
        public IHttpActionResult Get()
        {
            ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;

            var identityName = ClaimsPrincipal.Current.Identity.Name;
            var userName = User.Identity.Name;

            // TODO: Manh
            var userData = ClaimsPrincipal.Current.Claims
                .Where(c => c.Type == ClaimTypes.UserData)
                .Select(c=> c.Value)
                .SingleOrDefault();

            return Ok($"identity: {identityName}, name: {userName}");
        }
    }
}

Add Web Api To Mvc Application (edit)

https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

Nuget Command: 

Install-Package Microsoft.AspNet.WebApi.Core

Install-Package Microsoft.AspNet.WebApi.WebHost

Nuget browse: Microsoft ASP.NET Web API

https://stackoverflow.com/questions/26067296/how-to-add-web-api-to-an-existing-asp-net-mvc-5-web-application-project

https://forums.asp.net/t/2086957.aspx?How+to+add+web+api+project+in+MVC+4+5+project

Web API & ASP.NET Web Forms

https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/using-web-api-with-aspnet-web-forms

Ví dụ hay

https://developerslogblog.wordpress.com/2016/12/30/adding-web-api-support-to-an-existing-asp-net-mvc-project/

Web API + OWIN

https://www.ryadel.com/en/add-asp-net-web-api-support-to-an-existing-asp-net-mvc-web-application/

Categories

Recent posts