繁体   English   中英

User.Identity.IsAuthenticated 总是返回 false .NET CORE C#

[英]User.Identity.IsAuthenticated always return false .NET CORE C#

我试过var claimsIdentity = new ClaimsIdentity(GetUserClaims(user), token); 但我不知道如何使用它

我的启动.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedMemoryCache();
            services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromMinutes(1);
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            //Provide a secret key to Encrypt and Decrypt the Token
            var SecretKey = Encoding.ASCII.GetBytes
                 ("YourKey-2374-OFFKDI940NG7:56753253-tyuw-5769-0921-kfirox29zoxv");
            //Configure JWT Token Authentication
            services.AddAuthentication(auth =>
            {
                auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(token =>
            {
                token.RequireHttpsMetadata = false;
                token.SaveToken = true;
                token.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    //Same Secret key will be used while creating the token
                    IssuerSigningKey = new SymmetricSecurityKey(SecretKey),
                    ValidateIssuer = true,
                    //Usually, this is your application base URL
                    ValidIssuer = "http://localhost:45092/",
                    ValidateAudience = true,
                    //Here, we are creating and using JWT within the same application.
                    //In this case, base URL is fine.
                    //If the JWT is created using a web service, then this would be the consumer URL.
                    ValidAudience = "http://localhost:45092/",
                    RequireExpirationTime = true,
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero
                };
            });
            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseSession();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

我的服务.cs

public string LoginUser(string UserID, string Password)
        {
            var user = UserList.SingleOrDefault(x => x.UserId == UserID);
            if (user == null)
                return null;
            if (Password == user.Password)
            {
                //Authentication successful, Issue Token with user credentials 
                //Provide the security key which is given in 
                //Startup.cs ConfigureServices() method 
                var key = Encoding.ASCII.GetBytes
                ("YourKey-2374-OFFKDI940NG7:56753253-tyuw-5769-0921-kfirox29zoxv");
                //Generate Token for user 
                var JWToken = new JwtSecurityToken(
                    issuer: "http://localhost:45092/",
                    audience: "http://localhost:45092/",
                    claims: GetUserClaims(user),
                    notBefore: new DateTimeOffset(DateTime.Now).DateTime,
                    expires: new DateTimeOffset(DateTime.Now.AddDays(1)).DateTime,
                    //Using HS256 Algorithm to encrypt Token  
                    signingCredentials: new SigningCredentials
                    (new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                );
                string token = new JwtSecurityTokenHandler().WriteToken(JWToken);
                //var claimsIdentity = new ClaimsIdentity(GetUserClaims(user), token);
                //return claimsIdentity;
                return token;
            }
            else
            {
                return null;
            }
        }

        private List<User> UserList = new List<User>
        {
            new User {
                    UserId = "jsmith@email.com",
                    Password = "test", Email = "jsmith@email.com",
                    FirstName = "John", LastName = "Smith",
                    Phone = "356-735-2748", AccesLevel = "Director",
                    ReadOnly = "true"
            }
        };

        private IEnumerable<Claim> GetUserClaims(User user)
        { 
            IEnumerable<Claim> claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, user.FirstName + " " + user.LastName),
                new Claim("USERID", user.UserId),
                new Claim("EMAILID", user.Email),
                new Claim("PHONE", user.Phone),
                new Claim("ACCESS_LEVEL", user.AccesLevel.ToUpper()),
                new Claim("READ_ONLY", user.ReadOnly.ToUpper())
            };
            return claims;
        }

我的 Controller.cs

        public IActionResult LoginUser(User user)
        {
            TokenProvider _tokenProvider = new TokenProvider();
            var userToken = _tokenProvider.LoginUser(user.UserId.Trim(), user.Password);
            if (userToken != null)
            {
                //Save token in session object
                HttpContext.Session.SetString("JWToken", userToken);
                bool islogin = User.Identity.IsAuthenticated;
            }
            return Redirect("~/Home/Index");
        } 

最后,我的 Index.cshtml

@model Colegio.Models.User
@{
    ViewData["Title"] = "Home Page";
}
    @if (User.Identity.IsAuthenticated)
    {
        <div class="row">
            You are Logged in as
            <span style="font-size:large;color:forestgreen;">
                @User.Identity.Name
            </span>
        </div>
        <div class="row" style="padding-top:50px;">
            @Html.ActionLink("Log Off", "Logoff",
            "Home", null, new { @class = "btn btn-primary btn-lg rph-login-button" })
        </div>
    }

当我使用var claimsIdentity = new ClaimsIdentity(GetUserClaims(user), token); 在我的 service.ch 中,属性 IsAuthenticated 是真的,但是我必须做什么?

当我使用 var claimIdentity = new ClaimsIdentity(GetUserClaims(user), token); 在我的 service.ch 中,属性 IsAuthenticated 是真的,但是我必须做什么?

根据您的描述,我无法理解您为什么在 service.cs 登录方法中使用 ClaimsIdentity。

service.cs 登录方法用于生成 jwt 令牌。 控制器的 LoginUser 方法将检查用户密码和用户名,并将 jwt 令牌设置为 session。

但是 jwt 身份验证不会自动检查会话的 jwt 令牌,它会检查请求的请求 header。 Since you store the jwt token into the session not set the jwt token to the client side cookie, that means the client will not send request with jwt token header.

要解决此问题,您应该编写一个自定义中间件来读取会话的 jwt 令牌并将该令牌添加到请求 header 中。

更多细节,您可以参考以下代码:

修改startup.cs的Configure方法,添加自定义中间件:

  // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseSession();

        app.Use(async (context, next) =>
        {
            var JWToken = context.Session.GetString("JWToken");
            if (!string.IsNullOrEmpty(JWToken))
            {
                context.Request.Headers.Add("Authorization", "Bearer " + JWToken);
            }
            await next();
        });
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }

结果:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM