簡體   English   中英

如何使用JWT對來自角度SPA的Web Api 2進行用戶身份驗證?

[英]How do I use JWT for user authentication against Web Api 2 from angular SPA?

我正在嘗試將身份驗證從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;
          });

登錄時,我將返回的令牌作為字符串。 然后,將其存儲在我的客戶端會話中。 然后,我將其放在標題中以用於后續請求。

當我嘗試在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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM