簡體   English   中英

.NET Framework MVC 和 Web Api Auth JWT

[英].NET Framework MVC and Web Api Auth JWT

我在 MVC 中有一個項目,使用 .NET Framework v4.7 和一些 WebApi。 我需要知道的是如何使用中間件來為 HTTP 請求和 MVC 操作請求授權 JWT。

我到處搜索以尋找解決方案示例,但找不到任何東西。

如果有人可以提供幫助,我將不勝感激。

對不起英語。

如果我理解了您的問題陳述,我認為OWIN可能是一個選擇:您將您的應用程序與底層托管分離,並獲得一個可擴展的管道,您可以將中間件注入其中(非常類似於 .net core 開箱即用)。

更好的是 - 它帶有開箱即用的 JWT 支持(好吧,你需要安裝一些 nuget 包 - 見下文)。 然后您只需在您的IAppBuilder上啟用它並使用標准的[Authorize]屬性滾動。

為了演示這個設置,我在這里整理了一個可用的 GitHub 存儲庫來說明 WebApi 中間件。

除了Microsoft.AspNet.WebApi.OwinMicrosoft.Owin.Host.SystemWebMicrosoft.Owin.Security.Jwt nuget 包之外,它幾乎是一個標准的 asp.net WebApi 項目,其中更改了以下文件:

/Startup.cs

using System.Text;
using System.Web.Http;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Jwt;
using Owin;

namespace OWIN.WebApi
{
    public class Startup
    {
        public void Configuration(IAppBuilder appBuilder)
        {
            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config); // bootstrap your existing WebApi config 

            appBuilder.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateIssuerSigningKey = true, // I guess you don't even have to sign the token
                    ValidIssuer = "http://localhost",
                    ValidAudience = "http://localhost",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("jwt_signing_secret_key"))
                }
            });
            appBuilder.UseWebApi(config); // instruct OWIN to take over
        }
    }
}

/Controllers/ProtectedValuesController.cs

using System.Collections.Generic;
using System.Web.Http;

namespace OWIN.WebApi.Controllers
{
    [Authorize]
    public class ProtectedValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }
}

/Controllers/ObtainJwtController.cs

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using System.Web.Http;
using Microsoft.IdentityModel.Tokens;
using Claim = System.Security.Claims.Claim;

namespace OWIN.WebApi.Controllers
{
    // this class is literally just a test harness to help me generate a valid token for popping into Postman.
    public class ObtainJwtController: ApiController
    {
        private string CraftJwt()
        {
            string key = "jwt_signing_secret_key"; //Secret key which will be used later during validation    
            var issuer = "http://localhost";

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var permClaims = new List<Claim>
            {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim("valid", "1"),
                new Claim("userid", "1"),
                new Claim("name", "test")
            };

            var token = new JwtSecurityToken(issuer,
                issuer,
                permClaims,
                expires: DateTime.Now.AddDays(1),
                signingCredentials: credentials);
            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        public string Get()
        {
            return $"Bearer {CraftJwt()}";
        }
    }
}

這似乎也適用於 MVC

我添加了一些額外的 nuget 包來處理ASP.NET Identity ,這似乎使我能夠成功保護以下控制器:

/控制器/Home.cs

using System.Web.Mvc;

namespace OWIN.WebApi.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";

            return View();
        }

        [Authorize]
        public ActionResult Protected()
        {
            return View();
        }
    }
}

希望這能給你一些探索的選擇

看看我從你的問題你想使用 JWT 令牌為你的 WebApi 和正常的過程為你的 MVC 的理解,至於稍后從服務器生成的視圖,它不依賴於 JWT 令牌。

我見過這個問題。 在我的一個應用程序中,我同時托管 MVC 視圖和 webapi,而 MVC 視圖依賴於基於 cookie 的身份驗證和授權。 和 WebApi 調用依賴於 JWT 令牌進行授權和身份驗證。

抱歉,此解決方案來自 .net core。 您需要像這樣配置 Cookie 和 JWT 身份驗證

services.AddCookie()
.AddJwtBearer()

這里默認是您的 cookie 身份驗證。 現在要為您的 webapi 啟用 jwt 令牌,您需要使用以下屬性裝飾 webapi

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

希望這能回答你的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM