且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 JWT 身份验证实现从 .net core 2 转移到 asp.net web api 2

更新时间:2023-09-21 10:06:22

将我的实现从 .net core 2 转移到 asp.net web api 2

structure change for transfer my implementation from .net core 2 to asp.net web api 2

我使用 System.IdentityModel.Tokens.Jwt 命名空间来生成和验证 JWT 令牌.

i use System.IdentityModel.Tokens.Jwt namespace for generate and validate JWT token.

.net core 2 兼容 System.IdentityModel.Tokens.Jwt version="5.1.4" 但 asp.net web api 2 兼容 System.IdentityModel.Tokens.Jwt 版本="4.0.2"

.net core 2 compatible with System.IdentityModel.Tokens.Jwt version="5.1.4" but asp.net web api 2 compatible with System.IdentityModel.Tokens.Jwt version="4.0.2"

包版本中的相同更改对代码进行了更改,我使用 System.IdentityModel.Tokens 命名空间而不是 Microsoft.IdentityModel.Tokens的部分代码> 因为更改了软件包版本.

The same change in the package version made changes to the code, also the part of code i use the System.IdentityModel.Tokens namespace instead of Microsoft.IdentityModel.Tokens because of changing package versions.

代码更改:

JwtTokenBuilder 类:

在这个类中改变SigningCredentials参数设置

in this class change SigningCredentials parameter setting

  var token = new JwtSecurityToken(
                    issuer: this.issuer,
                    audience: this.audience,
                    claims: claims,
                    expires: this.expireTime,
                    signingCredentials: new System.IdentityModel.Tokens.SigningCredentials(
                                              this.securityKey,
                                              Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature
                                            , Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature));

安全密钥类:

更改安全密钥生成方式

using System.IdentityModel.Tokens;
using System.Text;

namespace solution.Authentication
{
  public static class JwtSecurityKey
  {
    public static SymmetricSecurityKey Create(string secret)
    {
      return new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
    }
  }
}

控制器属性:

namespace solution.Controllers
{
  public class ExampleController : ApiController
  {
    [HttpPost]
    [Route("api/Example")]
    [System.Web.Http.Authorize]
    public void Run()
    {
       // do something;
    }
  }  
}

我的主要更改是在 Startup OWIN 类中并将 Microsoft.Owin.Security.Jwt 包版本从3.1.0"更改为3.0.0"以进行验证传入请求的 JWT 令牌.

My main change was in Startup OWIN class and change Microsoft.Owin.Security.Jwt package version from "3.1.0" to "3.0.0" for validate JWT token for incoming requests.

实现:

using Microsoft.Owin;
using Owin;
using System.Web.Http;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Jwt;

[assembly: OwinStartup(typeof(solution.Startup))]

namespace solution
{
  public class Startup
  {
    public void Configuration(IAppBuilder app)
    {
      app.MapSignalR();
      HttpConfiguration config = new HttpConfiguration();
      config.MapHttpAttributeRoutes();
      ConfigureOAuth(app);
      app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
      app.UseWebApi(config);
    }
    public void ConfigureOAuth(IAppBuilder app)
    {
      var issuer = "issuer";
      var audience = "audience";
      var secret = JwtSecurityKey.Create("SecurityKey").GetSymmetricKey();

      // Api controllers with an [Authorize] attribute will be validated with JWT
      var option =
          new JwtBearerAuthenticationOptions
          {
            AuthenticationMode = AuthenticationMode.Active,
            AllowedAudiences = new[] { audience },
            IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
              {
                        new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
              }
          };
      app.UseJwtBearerAuthentication(
            option
        );
    }
  }
}