iT邦幫忙

0

C# .net core MVC authorize 與 session問題

各位大大小的寫程式遇到一個無法解決的問題
先大概講一下我在做甚麼
使用者輸入帳密之後 系統判斷有沒有這個人 如果有 -> 跳轉頁面(並且將使用者帳號存入session) -> 跳轉頁面之後右上角會顯示剛剛session存的帳號名稱

到這邊我的程式碼大概都寫好了,
我先測試說,如果輸入成功會重新整理網頁,並且將剛剛session存的東西顯示在右上角
但是現在遇到一個問題,就是我在輸入使用者帳號密碼之後,authorize是驗證成功的,但是寫入session的時候會寫不進去,我要"再"登入一次才會寫進session裡面,我不知道為什麼第一次輸入的時候會寫不進session裡面(我是用Claim宣告的)

還請各位大大有遇過可以為小弟解答謝謝,需要補上的再麻煩跟我說~

Controller的部分
https://ithelp.ithome.com.tw/upload/images/20210525/201120756urSSBXMLF.png

前端
https://ithelp.ithome.com.tw/upload/images/20210525/20112075EBkXRlT2YK.png

startup.cs

public void ConfigureServices(IServiceCollection services)
{
//從組態讀取登入逾時設定
double loginExpireMinute = Configuration.GetValue("LoginExpireMinute");

        // 將 Session 存在 ASP.NET Core 記憶體中
        services.AddDistributedMemoryCache();
        services.AddSession();

        //註冊 CookieAuthentication,Scheme必填
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(option =>
        {
            //或許要從組態檔讀取,自己斟酌決定
            option.LoginPath = new PathString("/Login/Login");//登入頁
            option.LogoutPath = new PathString("/Login/Logout");//登出Action
                                                                //用戶頁面停留太久,登入逾期,或Controller中用戶登入時也可設定
            option.ExpireTimeSpan = TimeSpan.FromMinutes(loginExpireMinute);//沒給預設14天
                                                                            //↓資安建議false,白箱弱掃軟體會要求cookie不能延展效期,這時設false變成絕對逾期時間
                                                                            //↓如果你的客戶反應明明一直在使用系統卻容易被自動登出的話,你再設為true(然後弱掃policy請客戶略過此項檢查) 
            option.SlidingExpiration = false;
        });

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });


        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        // 加入這幾行會出現error status 400  --------------------------------------------------------------------------------------------------
        //services.AddMvc(options =>
        //{
        //    //↓和CSRF資安有關,這裡就加入全域驗證範圍Filter的話,待會Controller不必再加上[AutoValidateAntiforgeryToken]屬性
        //    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
        //});
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
        
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
        app.UseSession();
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        // SessionMiddleware 加入 Pipeline
        
        //app.Run(async (context) =>
        //{
        //    context.Session.SetString("Sample", "This is Session.");
        //    string message = context.Session.GetString("Sample");
        //    await context.Response.WriteAsync($"{message}");
        //});

        //留意先執行驗證...
        app.UseAuthentication();
        //再執行Route,如此順序程式邏輯才正確
        app.UseMvcWithDefaultRoute();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
wenhsinluo
iT邦新手 4 級 ‧ 2021-10-21 17:48:17

https://ithelp.ithome.com.tw/upload/images/20211021/20124530Q0Qb1Cgup8.jpg
還沒response就取值,所以取不到
所以讓你有錯覺要"再"登入一次
(有錯請糾正我)

哦!我晚點試試~
感謝回答~

我要發表回答

立即登入回答