2014-07-17 15 views
5

Sto provando a configurare l'autenticazione da un'applicazione Single Page AngularJS (SPA) a un Web Api basato su OWIN. Ecco quello che ho ...Come utilizzare JWT per l'autenticazione utente contro Web Api 2 da angular SPA?

Questa è la funzione di login (azione POST su un AuthenticationController in API)

public HttpResponseMessage login(Credentials creds) 
    { 
     if (creds.Password == "password" && creds.Username.ToLower() == "username") 
     { 
      var user = new User { UserId = 101, Name = "John Doe", Role = "admin" }; 

      var tokenDescriptor = new SecurityTokenDescriptor() 
      { 
       Subject = new ClaimsIdentity(new[] 
       { 
        new Claim(ClaimTypes.Name, user.Name), 
        new Claim(ClaimTypes.Role, user.Role) 
       }), 

       AppliesToAddress = "http://localhost:/8080", 
       TokenIssuerName = "myApi", 

       SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(TestApp.Api.Startup.GetBytes("ThisIsTopSecret")), 
        "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", 
        "http://www.w3.org/2001/04/xmlenc#sha256") 
      }; 

      var tokenHandler = new JwtSecurityTokenHandler(); 
      var token = tokenHandler.CreateToken(tokenDescriptor); 
      var tokenString = tokenHandler.WriteToken(token); 

      return Request.CreateResponse<LoginResponse>(HttpStatusCode.Accepted, new LoginResponse { User = user, AuthToken = tokenString }); 
     } 

     return Request.CreateResponse(HttpStatusCode.Unauthorized); 
    } 

Questo è il mio OWIN startup config

public void Configuration(IAppBuilder app) 
    { 
     app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); 

     HttpConfiguration config = new HttpConfiguration(); 
     config.Routes.MapHttpRoute(
      name: "Default", 
      routeTemplate: "{controller}" 
     ); 

     var jsonSettings = config.Formatters.JsonFormatter.SerializerSettings; 
     jsonSettings.Formatting = Formatting.Indented; 
     jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 

     app.UseWebApi(config); 

     app.UseJwtBearerAuthentication(
     new JwtBearerAuthenticationOptions 
     { 
      AuthenticationMode = AuthenticationMode.Active, 
      AllowedAudiences = new[] { "http://localhost:8080" }, 
      IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] 
      { 
       new SymmetricKeyIssuerSecurityTokenProvider("myApp", TestApp.Api.Startup.GetBytes("ThisIsTopSecret")) 
      } 
     }); 
    } 

Questo è il angolare codice che sto usando per chiamare un controller nell'API che ha l'attributo Autorizzato.

$http({ method: 'GET', url: 'http://localhost:5000/Admin', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + Session.token }}) 
      .then(function (res) { 
       return res.data; 
      }); 

Al momento dell'accesso ottengo il token restituito come stringa. Quindi lo memorizzo nella sessione lato client. Allora lo prendo e lo metto nella mia intestazione per le richieste successive.

Quando provo a chiamare un'azione "Autorizzata" nell'API ottengo una risposta 401 anche se il mio token è stato passato attraverso l'intestazione della richiesta.

Sono nuovo di JWT quindi potrei essere totalmente fuori base sul mio approccio. Qualsiasi consiglio sarebbe grande.

risposta

4

Credo che sia un ordine di operazioni cosa. Sposta l'istruzione app.UseJwt sopra la riga app.UseWebApi.

app.UseJwtBearerAuthentication(
    new JwtBearerAuthenticationOptions 
    { 
     AuthenticationMode = AuthenticationMode.Active, 
     AllowedAudiences = new[] { "http://localhost:8080" }, 
     IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] 
     { 
      new SymmetricKeyIssuerSecurityTokenProvider("myApp", TestApp.Api.Startup.GetBytes("ThisIsTopSecret")) 
     } 
    }); 

app.UseWebApi(config); 
+1

Mi stai prendendo in giro ... questo ha funzionato per me! –

+0

@Sam, https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware – jsign

Problemi correlati