您如何创建和使用 OWIN JWT



我有一个WebAPI,我需要保护一个Angular 4.x应用程序,这样我就可以使用JWT。我试图弄清楚使用Microsoft的OWIN Katana3.x软件包实现它的最低要求(没有OAuth?(。

怎么能做到呢?

以下内容不起作用(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);
                });
            });
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新