从ASP.NET Core中的API读取JWT令牌

时间:2019-03-12 19:01:26

标签: asp.net-core jwt

我的设置:我已经创建并运行了WebAPI解决方案,该解决方案针对源(当前为数据库)执行用户名和密码的身份验证。这将生成JWT令牌,并将其返回到发出请求的应用程序(ASP.NET Core 2.2应用程序)。

大多数解决方案都谈到保护WebAPI公开方法的安全,但是我的方法是仅通过WebAPI进行身份验证。各个应用程序需要接受令牌,以便他们可以确定授权。

现在的问题是:从WebAPI读取令牌(我已经做过),对其进行验证,然后将其存储以供任何/所有控制器知道有经过身份验证的用户(通过Authorize)的最佳方法是什么?属性),只要令牌有效?

进行更多调试,看来我的令牌没有添加到标题中。我看到以下调试消息:

  

针对过滤器“ Microsoft.AspNet.Mvc.Filters.AuthorizeFilter”的请求的授权失败

代码更新2 -获取JWT的代码:

        var client = _httpClientFactory.CreateClient();
        client.BaseAddress = new Uri(_configuration.GetSection("SecurityApi:Url").Value);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        //login
        Task<HttpResponseMessage> response = ValidateUserAsync(client, username, password);
        Task<Core.Identity.TokenViewModel> tokenResult = response.Result.Content.ReadAsAsync<Core.Identity.TokenViewModel>();

        if (!response.Result.IsSuccessStatusCode)
        {
            if (tokenResult != null && tokenResult.Result != null)
            {
                ModelState.AddModelError("", tokenResult.Result.ReasonPhrase);
            }
            else
            {
                ModelState.AddModelError("", AppStrings.InvalidLoginError);
            }
            return View();
        }

        JwtSecurityToken token = new JwtSecurityToken(tokenResult.Result.Token);
        int userId;

        if (int.TryParse(token.Claims.First(s => s.Type == JwtRegisteredClaimNames.NameId).Value, out userId))
        {
            //load app claims
            Core.Identity.UserInfo userInfo = Core.Identity.UserLogin.GetUser(_identityCtx, userId);
            Core.Identity.UserStore uStore = new Core.Identity.UserStore(_identityCtx);
            IList<Claim> claims = uStore.GetClaimsAsync(userInfo, new System.Threading.CancellationToken(false)).Result;
            claims.Add(new Claim(Core.Identity.PowerFleetClaims.PowerFleetBaseClaim, Core.Identity.PowerFleetClaims.BaseUri));

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, JwtBearerDefaults.AuthenticationScheme);
            ClaimsPrincipal principal = new ClaimsPrincipal(claimsIdentity);

            //complete
            AuthenticationProperties authProperties = new AuthenticationProperties();
            authProperties.ExpiresUtc = token.ValidTo;
            authProperties.AllowRefresh = false;
            authProperties.IsPersistent = true;

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(JwtBearerDefaults.AuthenticationScheme, tokenResult.Result.Token);
            //var stuff = HttpContext.SignInAsync(JwtBearerDefaults.AuthenticationScheme, principal, authProperties);
        }
        else
        {
            ModelState.AddModelError("", AppStrings.InvalidLoginError);
            return View();
        }

        return RedirectToAction("Index", "Home");

启动:

private void ConfigureIdentityServices(IServiceCollection services)
    {
        services.ConfigureApplicationCookie(options => options.LoginPath = "/Login");

        //authentication token
        services.AddAuthentication(opt =>
        {
            opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddCookie(opt =>
        {
            opt.LoginPath = "/Login";
            opt.LogoutPath = "/Login/Logoff";
            opt.Cookie.Name = Configuration.GetSection("SecurityApi:CookieName").Value;
        }).AddJwtBearer(options =>
        {
            options.SaveToken = true;
            options.RequireHttpsMetadata = false;

            options.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateAudience = true,
                ValidAudience = Configuration.GetSection("SecurityApi:Issuer").Value,
                ValidateIssuer = true,
                ValidIssuer = Configuration.GetSection("SecurityApi:Issuer").Value,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("SecurityApi:Key").Value)),
                ValidateLifetime = true
            };
        });

        Core.Startup authStart = new Core.Startup(this.Configuration);
        authStart.ConfigureAuthorizationServices(services);
    }

验证:

public void ConfigureAuthorizationServices(IServiceCollection services)
    {
        services.AddDbContext<Identity.IdentityContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SecurityConn")));
        services.AddScoped<DbContext, Identity.IdentityContext>(f =>
        {
            return f.GetService<Identity.IdentityContext>();
        });

        services.AddIdentityCore<Identity.UserInfo>().AddEntityFrameworkStores<Identity.IdentityContext>().AddRoles<Identity.Role>();
        services.AddTransient<IUserClaimStore<Core.Identity.UserInfo>, Core.Identity.UserStore>();
        services.AddTransient<IUserRoleStore<Core.Identity.UserInfo>, Core.Identity.UserStore>();
        services.AddTransient<IRoleStore<Core.Identity.Role>, Core.Identity.RoleStore>();

        services.AddAuthorization(auth =>
        {
            auth.AddPolicy(JwtBearerDefaults.AuthenticationScheme, new AuthorizationPolicyBuilder().AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build());
            auth.AddPolicy(PFBaseClaim, policy => policy.RequireClaim(Identity.PFClaims.BaseUri));
        });
    }

1 个答案:

答案 0 :(得分:0)

最后,我的方法是使用安全的cookie和基本声明来证明用户已通过身份验证。

private void ConfigureAuthentication(IServiceCollection服务)         {             services.ConfigureApplicationCookie(options => options.LoginPath =“ / Login”);

        //authentication token
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(opt =>
        {
            opt.LoginPath = "/Login";
            opt.AccessDeniedPath = "/Login";
            opt.LogoutPath = "/Login/Logoff";
            opt.Cookie.Name = Configuration.GetSection("SecurityApi:CookieName").Value;
        }).AddJwtBearer(options =>
        {
            options.SaveToken = true;

            options.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateAudience = true,
                ValidAudience = Configuration.GetSection("SecurityApi:Issuer").Value,
                ValidateIssuer = true,
                ValidIssuer = Configuration.GetSection("SecurityApi:Issuer").Value,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("SecurityApi:Key").Value)),
                ValidateLifetime = true
            };
        });
    }

登录时:

            AuthenticationProperties authProperties = new AuthenticationProperties();
        authProperties.ExpiresUtc = token.ValidTo;
        authProperties.AllowRefresh = false;
        authProperties.IsPersistent = true;

        HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userStore.CreateAsync(user).Result, authProperties);

        return RedirectToAction("Index", "Home");