iT邦幫忙

2022 iThome 鐵人賽

DAY 13
1

IdentityOptions

IdentityOptions類別可用來設定身分識別系統的所有選項。

屬性

ClaimsIdentity 取得或設定 ClaimsIdentityOptions 識別系統的 。
Lockout 取得或設定 LockoutOptions 識別系統的 。
Password 取得或設定 PasswordOptions 識別系統的 。
SignIn 取得或設定 SignInOptions 識別系統的 。
Stores 取得或設定 StoreOptions 識別系統的 。
Tokens 取得或設定 TokenOptions 識別系統的 。
User 取得或設定 UserOptions 識別系統的 。

Program.cs

builder.Services.Configure<IdentityOptions>(options =>
{
    //密碼設定
    options.Password.RequireDigit = true; //密碼需不需要包含數字
    options.Password.RequireLowercase = true; //密碼是否必須包含小寫
    options.Password.RequireNonAlphanumeric = true; //密碼是否必須包含特殊符號
    options.Password.RequireUppercase = true; //密碼是否必須包含大寫
    options.Password.RequiredLength = 6; //密碼長度必須符合6以上
    options.Password.RequiredUniqueChars = 1;  //至少要有1個字元不一樣

    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); //	
取得或設定 TimeSpan 發生鎖定時,使用者遭到鎖定。 預設為 5 分鐘。
    options.Lockout.MaxFailedAccessAttempts = 5; //使用者鎖定之前允許的失敗存取嘗試次數,假設已啟用鎖定。 預設值為 5
    options.Lockout.AllowedForNewUsers = true; //是否可以鎖定新的使用者

    options.User.AllowedUserNameCharacters =
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+"; //驗證使用者名稱的使用者名稱中允許的字元清單
    options.User.RequireUniqueEmail = false; //電子郵件不能重覆使用
});

builder.Services.ConfigureApplicationCookie(options =>
{
    // Cookie settings
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

    options.LoginPath = "/Identity/Account/Login";
    options.AccessDeniedPath = "/Identity/Account/AccessDenied";
    options.SlidingExpiration = true;
});

在上一篇我們成功透過頁面登入、註冊,但是我覺得很奇怪,我的程式碼找不到那幾個頁面的code,Areas跟Views資料夾都找不到Login Register.....今天來解密囉,請繼續看下去。
https://ithelp.ithome.com.tw/upload/images/20220928/20152200hIpYXlatlT.png

Scaffolding Identity

安裝 Microsoft.VisualStudio.Web.CodeGeneration.Design

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design

Identity執行 scaffolder

dotnet tool install -g dotnet-aspnet-codegenerator //先前已安裝這邊可以跳過

快速建立 UI (分號做為命令分隔符號)

dotnet aspnet-codegenerator identity -dc NetCoreIdentity.Data.ApplicationDbContext --files "Account.Register;Account.Login;Account.Logout;Account.RegisterConfirmation"

執行完畢後可以看到 Areas 有檔案了!
*若沒看到.cs檔案可以重開 Visual Studio 就可以看到了
https://ithelp.ithome.com.tw/upload/images/20220928/20152200t99O2LGaNF.png

停用預設帳戶驗證

上一篇最後展示註冊後會跳一個註冊確認畫面,可選取連結以認證帳戶的 。 此功能應僅用於測試,應在生產應用程式中停用自動帳戶驗證。
若要要求已確認的帳戶,並防止在註冊時立即登入,請在RegisterConfirmation.cshtml.cs中 設定 DisplayConfirmAccountLink = false。
https://ithelp.ithome.com.tw/upload/images/20220928/201522008CenLVnOks.png


參考資料

Introduction to Identity on ASP.NET Core


上一篇
[Day12]- ASP.NET Core Identity(1)
下一篇
[Day14]- EF Core Code First
系列文
ASP.NET Core 30 天旅程30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言