.NET Framework MVC和Web Api Auth JWT

编程入门 行业动态 更新时间:2024-10-24 06:26:14
本文介绍了.NET Framework MVC和Web Api Auth JWT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在MVC中使用.NET Framework v4.7并带有一些WebApi的项目.我需要知道的是如何在此之后使用中间件来为JWT授权HTTP请求和MVC Action请求.

I have a project in MVC using .NET Framework v4.7 with some WebApi on it. What I need to know is how to use a middleware between then to authorize a JWT for HTTP requests and MVC Action requests.

我到处搜索以寻找解决方案样本,但找不到任何东西.

I've searched everywhere looking for a solution sample, but I couldn't find anything.

如果有人可以帮忙,我将不胜感激.

If anyone could help, I would be grateful.

对不起,英语.

推荐答案

如果我掌握了您的问题说明,我认为 OWIN 可能是一种选择:将应用程序与基础托管分离,并获得可注入的可扩展管道中间件进入(很像 core可以直接使用).

If I grasped your problem statement, I think OWIN might be an option: you decouple your application from underlying hosting and get an extensible pipeline that you can inject middleware into (pretty much like core works out of the box).

甚至更好-它具有开箱即用的JWT支持(嗯,您需要安装一些nuget软件包-见下文).然后,您只需在IAppBuilder上启用它并使用标准[Authorize]属性滚动即可.

Even better - it comes with JWT support out of the box (well, you need to install a few nuget packages - see below). Then you simply enable it on your IAppBuilder and roll with standard [Authorize] attributes.

为演示此设置,我在这里整理了在此处运行GitHub存储库说明WebApi中间件.

To demo this setup, I've put together a working GitHub repo here to illustrate WebApi middleware.

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

Apart from Microsoft.AspNet.WebApi.Owin, Microsoft.Owin.Host.SystemWeb and Microsoft.Owin.Security.Jwt nuget packages, it's pretty much a stock standard asp WebApi project with the following files changed:

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 = "localhost", ValidAudience = "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 = "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身份,这似乎使我能够成功保护以下控制器:

This appears to work for MVC too

I have added a few extra nuget packages to do with ASP.NET Identity, which seems to have enabled me to successfully protect the following controller:

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

希望这为您提供了探索的选择

Hopefully that gives you some options to explore

更多推荐

.NET Framework MVC和Web Api Auth JWT

本文发布于:2023-11-16 21:10:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1607468.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:MVC   Framework   NET   Web   JWT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!