Asp.net 如何使用JWT对angular SPA的Web Api 2进行用户身份验证?

Asp.net 如何使用JWT对angular SPA的Web Api 2进行用户身份验证?,asp.net,angularjs,asp.net-web-api,owin,jwt,Asp.net,Angularjs,Asp.net Web Api,Owin,Jwt,我正在尝试设置从AngularJS单页应用程序(SPA)到基于OWIN构建的Web Api的身份验证。这是我所拥有的 这是登录函数(在API中对AuthenticationController执行操作后) 这是我用来调用API中具有Authorized属性的控制器的angular代码 $http({ method: 'GET', url: 'http://localhost:5000/Admin', headers: { 'Content-Type': 'application/json', '

我正在尝试设置从AngularJS单页应用程序(SPA)到基于OWIN构建的Web Api的身份验证。这是我所拥有的

这是登录函数(在API中对AuthenticationController执行操作后)

这是我用来调用API中具有Authorized属性的控制器的angular代码

$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响应,即使我的令牌是通过请求的头传入的


我是JWT的新手,所以我可能完全偏离了我的方法。任何建议都很好。

我相信这是一个操作顺序问题。将app.UseJwt语句移到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);
@山姆,
$http({ method: 'GET', url: 'http://localhost:5000/Admin', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + Session.token }})
          .then(function (res) {
              return res.data;
          });
    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);