簡體   English   中英

從ASP.NET Core中的API讀取JWT令牌

[英]Reading JWT Token from API in ASP.NET Core

我的設置:我已經創建並運行了WebAPI解決方案,該解決方案針對源(當前為db)執行用戶名和密碼的身份驗證。 這將生成JWT令牌,並將其返回到發出請求的應用程序(ASP.NET Core 2.2應用程序)。

大多數解決方案都談到保護WebAPI公開方法的安全,但是我的方法是僅通過WebAPI進行身份驗證。 各個應用程序需要接受令牌,以便他們可以確定授權。

現在的問題是:從WebAPI讀取令牌(我已經完成),對其進行驗證,然后將其存儲以供任何/所有控制器知道有經過身份驗證的用戶(通過Authorize屬性)的最佳方法是什么?只要令牌有效?

對此進行更多調試,似乎我的令牌未添加到標頭中。 我看到以下調試消息:

篩選器'Microsoft.AspNet.Mvc.Filters.AuthorizeFilter'的請求授權失敗

代碼Update2-獲得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));
        });
    }

最后,我的方法是使用安全cookie和基本聲明來證明用戶已通過身份驗證。

私人無效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");

暫無
暫無

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

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