2017-04-11 1 views
0

J'ai un WebAPI, et je dois sécuriser une application Angular 4.x donc je pourrais utiliser JWT. J'essaie de comprendre quel est le strict minimum (pas d'OAuth?) Pour y parvenir en utilisant les paquets OWIN Katana 3.x de Microsoft.Comment créez-vous et consommez OWIN JWT?

Comment cela peut-il être fait?

Répondre

0

Ce qui suit ne fonctionne pas (les parties de Microsoft/System s'emmêlent). Mais c'est le plus proche de quelque chose qui me semble presque 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); 
       }); 
      }); 
     } 
    } 
}