【发布时间】:2017-09-06 19:33:57
【问题描述】:
我有一个 WebAPI,我需要保护一个 Angular 4.x 应用程序,所以我可以使用 JWT。 我试图弄清楚使用 Microsoft 的 OWIN Katana 3.x 软件包实现它的最低限度(没有 OAuth?)。
怎么做?
【问题讨论】:
我有一个 WebAPI,我需要保护一个 Angular 4.x 应用程序,所以我可以使用 JWT。 我试图弄清楚使用 Microsoft 的 OWIN Katana 3.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);
});
});
}
}
}
【讨论】: