.NET Core 從1.1升級到2.0記錄(Cookie中間件踩坑)


.NET Core 2.0 新時代

萬眾矚目的.NET Core 2.0終於發布了,原定於9.19的dotnetconf大會的發布時間大大提前了1個月,.NET Core 2.0/.NET Standard 2.0的正式發布是.NET 開源跨平台的一個重大里程碑。

.NET Core 2.0 SDK下載地址:https://www.microsoft.com/net/download/core#/sdk

Visual Studio 2017 15.3下載地址:https://www.visualstudio.com/zh-hans/downloads/

更新ASP.NET Core 項目中的目標框架

更新ASP.NET Core Web項目中的Nuget依賴項

備注:刪除之前的 Microsoft.* 依賴項,使用 Microsoft.AspNetCore.All。

.NET Core 2.0 更新Cookie中間件使用方法

備注:我這邊當前項目單獨使用的Cookie中間件,未結合Identity使用。

1:在ConfigureServices添加Cookie中間件,使用自定義Scheme(坑就在這里) 

services.AddAuthentication(options=> {
                options.DefaultChallengeScheme = CookieAuthenInfo.QwCmsWebCookieInstance;
                options.DefaultSignInScheme = CookieAuthenInfo.QwCmsWebCookieInstance;
                options.DefaultAuthenticateScheme = CookieAuthenInfo.QwCmsWebCookieInstance;
            })
            .AddCookie(CookieAuthenInfo.QwCmsWebCookieInstance, m =>
            {
                m.LoginPath = new PathString("/Account/Login");
                m.AccessDeniedPath = new PathString("/Account/Denied");
                m.LogoutPath = new PathString("/Account/Logout");
                m.Cookie.Path = "/";
             });

踩坑:報異常 No authenticationScheme was specified, and there was no DefaultChallengeScheme found.

特別感謝Zonciu提供的幫助。

2:在Configure使用Cookie中間件

 app.UseAuthentication();

使用擴展類AuthenticationHttpContextExtensions

引入命名空間

using Microsoft.AspNetCore.Authentication;

新的擴展方法

使用方式

//登錄
await HttpContext.SignInAsync(CookieAuthenInfo.QwCmsWebCookieInstance, userPrincipal,
      new AuthenticationProperties
      {
          ExpiresUtc = DateTime.UtcNow.AddHours(12),
          IsPersistent = true,
          AllowRefresh = false
      });

//退出
await HttpContext.SignOutAsync(CookieAuthenInfo.QwCmsWebCookieInstance); 

AuthorizeAsync現在返回結果為AuthorizationResult

新的擴展方法

使用方式

var result = await HttpContext.AuthenticateAsync("xxxx");
if (result.Succeeded)
{
    ......
} 

參考

1:[Draft] Auth 2.0 Migration announcement #1310

2:Migrating Authentication and Identity to ASP.NET Core 2.0

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM