如何使用JWT对角度SPA的Web Api 2进行用户身份验证?

时间:2014-07-17 20:34:45

标签: asp.net angularjs asp.net-web-api owin jwt

我正在尝试将AngularJS单页面应用程序(SPA)中的身份验证设置为基于OWIN构建的Web Api。这就是我的......

这是登录功能(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"))
            }
        });
    }

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

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

当我登录时,我将返回的令牌作为字符串。然后我将它存储在我的客户端Session中。然后我把它拿到我的标题中以备后续请求。

当我尝试在API中调用“授权”操作时,即使我的令牌通过请求的标头传入,我也会获得401响应。

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

1 个答案:

答案 0 :(得分:4)

我认为这是一个操作顺序。将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);