【问题标题】:How do you create and consume OWIN JWT?您如何创建和使用 OWIN JWT?
【发布时间】:2017-09-06 19:33:57
【问题描述】:

我有一个 WebAPI,我需要保护一个 Angular 4.x 应用程序,所以我可以使用 JWT。 我试图弄清楚使用 Microsoft 的 OWIN Katana 3.x 软件包实现它的最低限度(没有 OAuth?)。

怎么做?

【问题讨论】:

    标签: c# owin .net-4.5 jwt


    【解决方案1】:

    以下内容不起作用(Microsoft 的/系统部分以破坏方式纠缠)。但这是我能得到的最接近看起来几乎简单的东西。

    using System.IdentityModel.Tokens.Jwt;
    using System.Security.Claims;
    using System.Security.Cryptography;
    using Microsoft.IdentityModel.Tokens;
    using Microsoft.Owin;
    using Microsoft.Owin.Security.Jwt;
    using Owin;
    
    [assembly: OwinStartup(typeof(WebApplication1.Startup))]
    namespace WebApplication1
    {
        public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                var issuer = "test";
                var audience = issuer;
                var key = new AesManaged().Key;
    
                var options = new JwtBearerAuthenticationOptions
                {
                    AllowedAudiences = new[] { audience },
                    IssuerSecurityTokenProviders = new[] { new SymmetricKeyIssuerSecurityTokenProvider(issuer, key) }
                };
                app.UseJwtBearerAuthentication(options);
    
                app.Map("/Login", subApp =>
                {
                    subApp.Run(context =>
                    {
                        var tokenHandler = new JwtSecurityTokenHandler();
                        var tokenDescriptor = new SecurityTokenDescriptor
                        {
                            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.Sha256Digest),
                            Audience = audience,
                            Issuer = issuer,
                            Subject = new ClaimsIdentity(new[]
                            {
                              new Claim(ClaimTypes.Name, "Serge")
                            })
                        };
                        var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));
    
                        return context.Response.WriteAsync(token);
                    });
                });
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 2020-04-18
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 2016-02-08
      相关资源
      最近更新 更多