2014-07-17 33 views
5

我試圖設置從AngularJS單頁應用程序(SPA)到建立在OWIN上的Web Api的身份驗證。以下是我有...如何使用JWT進行角度SPA的Web Api 2用戶驗證?

這是登錄功能(在API上AuthenticationController POST操作)

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

這是我OWIN啓動配置

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

這是角我用來調用具有授權屬性的API中的控制器的代碼。

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

當我登錄時,我得到返回的標記作爲字符串。然後我將它存儲在我的客戶端會話中。然後,我把它放在我的標題中供以後的請求使用。

當我嘗試在API中調用「授權」操作時,即使通過請求頭傳入了令牌,我也會收到401響應。

我是新來的智威湯遜,所以我可能完全脫離我的方法。任何建議都會很棒。

回答

4

我相信這是一個操作順序的事情。移動app.UseWebApi行上方的app.UseJwt語句。

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

你一定是在開玩笑我......這對我有效! –

+0

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