.NET Framework MVC 和 Web Api Auth JWT

标签 .net asp.net-mvc jwt asp.net-web-api2 bearer-token

我在 MVC 中有一个使用 .NET Framework v4.7 的项目,上面有一些 WebApi。我需要知道的是如何使用中间件来为 HTTP 请求和 MVC Action 请求授权 JWT。

我到处寻找解决方案示例,但找不到任何东西。

如果有人可以提供帮助,我将不胜感激。

对不起英语。

最佳答案

如果我掌握了您的问题陈述,我认为 OWIN可能是一种选择:您将应用程序与底层托管分离,并获得一个可扩展的管道,您可以将中间件注入(inject)其中(非常像 .net core 开箱即用)。

更好的是 - 它提供了开箱即用的 JWT 支持(好吧,您需要安装一些 nuget 包 - 见下文)。然后您只需在 IAppBuilder 上启用它并使用标准 [Authorize] 滚动属性。

为了演示这个设置,我整理了一个 working GitHub repo here来说明 WebApi 中间件。

除了 Microsoft.AspNet.WebApi.Owin , Microsoft.Owin.Host.SystemWebMicrosoft.Owin.Security.Jwt nuget 包,它几乎是一个标准的 asp.net WebApi 项目,更改了以下文件:

/启动.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
        }
    }
}

/ Controller /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 ,这似乎使我能够成功保护以下 Controller :

/ Controller /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();
        }
    }
}

希望这能给你一些探索的选择

关于.NET Framework MVC 和 Web Api Auth JWT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52449799/

相关文章:

.net - 为什么 MobileServiceSQLiteStore 数据库中的createdAt、deleted和updatedAt列为空?

node.js - 从 Google JWT 到使用 React 和 Node.js 访问和刷新 token

asp.net-core - ASP.NET Core JWT 身份验证是否支持多个对称签名 key ?

wordpress - 如何解决 "JWT is not configured properly"问题?

.net - 我想要一些调试 WCF Web 服务异常的技巧

.net - UserControls 的构造函数中应该有 InitializeComponent 吗?

asp.net - 在 .NET2 站点下运行 IIS .NET4 应用程序

asp.net - 我想在 .NET MVC 中使用剑道网格添加全选复选框

asp.net-mvc - ASP.NET MVC - Html.BeginForm()。我可以发回不同的路由并保留现有的查询字符串值吗?

c# - 即使我没有在 html 中显示,我的模型绑定(bind)也能正常工作