您如何创建和使用OWIN JWT? [英] How do you create and consume OWIN JWT?

查看:113
本文介绍了您如何创建和使用OWIN JWT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WebAPI,我需要保护Angular 4.x应用程序,因此我可以使用JWT. 我试图找出使用Microsoft的OWIN Katana 3.x 软件包实现此目标的最低要求(没有OAuth?).

I have a WebAPI, and I need to secure an Angular 4.x app so I though I could use JWT. I'm trying to figure out what's the bare minimum (no OAuth?) to achieve it using Microsoft's OWIN Katana 3.x packages.

怎么办?

推荐答案

以下操作不起作用(Microsoft的/系统部件以一种折断的方式缠绕).但这是我所能找到的最简单的东西.

The following doesn't work (Microsoft's/System parts entangled in a breaking way). But it's the closest I could get to something looking almost simple.

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);
                });
            });
        }
    }
}

这篇关于您如何创建和使用OWIN JWT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆