【问题标题】:Authorizing Access with JWT tokens in asp.net mvc website在 asp.net mvc 网站中使用 JWT 令牌授权访问
【发布时间】:2021-10-09 16:07:21
【问题描述】:

我想在我的 ASP.NET MVC 网站中使用 jwt 令牌进行授权。我已经创建了一个从本教程生成 jwt 令牌的 api: https://www.c-sharpcorner.com/article/asp-net-web-api-2-creating-and-validating-jwt-json-web-token/

现在我在我的 asp.net mvc 网站中添加了以下 nuget 包:

System.IdentityModel.Tokens.Jwt 5.5.0 
Microsoft.Owin.Security.Jwt 4.0.1
Microsoft.AspNet.WebApi.Owin 5.2.3
Microsoft.Owin.Host.SystemWeb 4.0.1 

我还创建了一个启动文件并插入了以下代码:

   app.UseJwtBearerAuthentication(  
                   new JwtBearerAuthenticationOptions  
                   {  
                       AuthenticationMode = AuthenticationMode.Active,  
                       TokenValidationParameters = new TokenValidationParameters()  
                       {  
                           ValidateIssuer = true,  
                           ValidateAudience = true,  
                           ValidateIssuerSigningKey = true,  
                           ValidIssuer = "example.com", //some string, normally web url,  
                           ValidAudience = "example.com",  
                           IssuerSigningKey = new 

    SymmetricSecurityKey(Encoding.UTF8.GetBytes("my_secret_key_12345"))  

                       }  
                   }); 

然后我使用邮递员创建一个 jwt 令牌并挑战网站的授权。 生成令牌方法如下。 (就像教程一样):

    public Object GetToken()    
    {    
        string key = "my_secret_key_12345";
        var issuer = "example.com";  //normally this will be your site URL    
      
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));    
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);    
      
        //Create a List of Claims, Keep claims name short    
        var permClaims = new List<Claim>();    
        permClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));    
        permClaims.Add(new Claim("valid", "1"));    
        permClaims.Add(new Claim("userid", "1"));    
        permClaims.Add(new Claim("name", "bilal"));    
      
        //Create Security Token object by giving required parameters    
        var token = new JwtSecurityToken(issuer, //Issure    
                        issuer,  //Audience    
                        permClaims,    
                        expires: DateTime.Now.AddDays(1),    
                        signingCredentials: credentials);    
        var jwt_token = new JwtSecurityTokenHandler().WriteToken(token);    
        return new { data = jwt_token };    
    }

我创建了以下方法来挑战授权:

[Authorize]
     public string checkbystring()
        {
            return "worked";
        }

但是当我在邮递员中测试时,不断弹出以下错误: IIS 10.0 详细错误 - 401.0 - 未经授权

我们将不胜感激任何关于完成这项工作的建议。

【问题讨论】:

    标签: asp.net-mvc jwt


    【解决方案1】:

    我在 ASP NET MVC 中遇到了类似的问题,生成了我的令牌,但是当我使用它时,我得到了 401 错误。 我需要创建一个使用 JWT 令牌而不是 Core 的 ASP NET MVC 应用程序。 我的解决方案是包含一个缺少的库: Microsoft.Owin.Host.SystemWeb

    using Microsoft.IdentityModel.Tokens;
    using Microsoft.Owin;
    using Microsoft.Owin.Security;
    using Microsoft.Owin.Security.Jwt;
    using Owin;
    using System.Text;
    
    
    [assembly: OwinStartup(typeof(WebAPI.Startup))]
    namespace WebAPI
    {
        public class Startup
        {
            private readonly string SecuretyKey = "KEY--$%TESTE&##&#";
    
            public void Configuration(IAppBuilder app)
            {
    
                app.UseJwtBearerAuthentication(
                   new JwtBearerAuthenticationOptions
                   {
                       AuthenticationMode = AuthenticationMode.Active,
                       TokenValidationParameters = new TokenValidationParameters()
                       {
                           ValidAudience = "Teste.com",
                           ValidIssuer = "Teste.com",
                           IssuerSigningKey = new SymmetricSecurityKey(
                               Encoding.UTF8.GetBytes(SecuretyKey)),
                           ValidateLifetime = true,
                           ValidateIssuerSigningKey = true
                       }
                   });
            }
        }
    }

    除此之外,其他必要的包的图像如下。 enter image description here

    【讨论】:

      猜你喜欢
      • 2019-10-19
      • 2019-05-05
      • 2018-11-28
      • 2019-04-17
      • 2021-06-13
      • 2018-06-05
      • 2020-10-20
      • 2017-10-23
      • 1970-01-01
      相关资源
      最近更新 更多