【问题标题】:User.Identity.IsAuthenticated always return false .NET CORE C#User.Identity.IsAuthenticated 总是返回 false .NET CORE C#
【发布时间】:2020-10-04 03:35:18
【问题描述】:

我试过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;
        }

我的控制器.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>
    }

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

【问题讨论】:

    标签: c# asp.net-core razor jwt razor-pages


    【解决方案1】:

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

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

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

    但是 jwt 认证不会自动检查会话的 jwt 令牌,它会检查请求的请求头。由于您将 jwt 令牌存储到会话中,没有将 jwt 令牌设置为客户端 cookie,这意味着客户端不会发送带有 jwt 令牌标头的请求。

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

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

    修改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?}");
            });
        }
    

    结果:

    【讨论】:

      猜你喜欢
      • 2013-10-30
      • 1970-01-01
      • 2019-01-27
      • 2020-01-12
      • 2014-11-10
      • 1970-01-01
      • 2023-03-15
      • 2018-04-28
      • 1970-01-01
      相关资源
      最近更新 更多