一. 新建asp.net core identity專案
新建專案->asp.net core web應用程式-> web應用程式(模型檢視控制器)&更改身份驗證為個人.
新建一個空資料庫, 然後在appsettings中的連線字串指向該空庫.
"DefaultConnection": "Data Source=.;Initial Catalog=IdentityDBTest;Integrated Security=False;Persist Security Info=False;User ID=sa;Password=sa1234;MultipleActiveResultSets=True;Pooling=True;Min Pool Size=1;Max Pool Size=300;"
cmd進入專案根目錄, 然後執行 dotnet ef database update -c ApplicationDbContext
會在指定的空庫中建立Identity的相應資料表.
修改launchSettings的Project執行方式的url為 http://localhost:40010
在Startup.cs中新增如下程式碼, 配置asp.net core identity的使用者相關資訊
public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); services.Configure<IdentityOptions>(options => { // Password settings options.Password.RequireDigit = false; options.Password.RequiredLength = 6; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequireLowercase = false; //options.Password.RequiredUniqueChars = 6; // Lockout settings //options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30); //options.Lockout.MaxFailedAccessAttempts = 10; //options.Lockout.AllowedForNewUsers = true; // User settings options.User.RequireUniqueEmail = true; }); services.ConfigureApplicationCookie(options => { // Cookie settings options.Cookie.Name = "identityCookieJJL"; options.Cookie.HttpOnly = true; options.ExpireTimeSpan = TimeSpan.FromMinutes(30); // If the LoginPath isn't set, ASP.NET Core defaults // the path to /Account/Login. options.LoginPath = "/Account/Login"; // If the AccessDeniedPath isn't set, ASP.NET Core defaults // the path to /Account/AccessDenied. options.AccessDeniedPath = "/Account/AccessDenied"; options.SlidingExpiration = true; }); // Add application services. services.AddTransient<IEmailSender, EmailSender>();
啟動並執行, 註冊一個使用者, 並且確保登入成功
二. 整合IdentityServer
新增IdentityServer4.aspnetIdentity的Nuget包, 同時會自動新增IdentityServer4.
在根目錄下新建一個AuthorizationConfig.cs類.
新增如下程式碼
/// <summary> /// 哪些API可以使用這個authorization server. /// </summary> /// <returns></returns> public static IEnumerable<ApiResource> ApiResources() { return new[] { new ApiResource("ProductApi", "微服務之產品Api") }; }
public static IEnumerable<IdentityResource> GetIdentityResources() { return new List<IdentityResource> { new IdentityResources.OpenId(), new IdentityResources.Profile() }; }
public static IEnumerable<Client> Clients() { return new[] { new Client { ClientId = "WebClientImplicit", ClientSecrets = new [] { new Secret("SecretKey".Sha256()) }, AllowedGrantTypes = GrantTypes.Implicit, AllowAccessTokensViaBrowser = true, RedirectUris = { http://localhost:40011/signin-oidc }, // where to redirect to after logout PostLogoutRedirectUris = { http://localhost:40011/signout-callback-oidc }, AllowedScopes = new List<string> { IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile, "ProductApi", IdentityServerConstants.ClaimValueTypes.Json } , RequireConsent=false,//不需要確認授權頁面,方便直接跳轉 AlwaysIncludeUserClaimsInIdToken=true } }; }
在StartUp.cs中的服務註冊方法中新增程式碼
// configure identity server with in-memory stores, keys, clients and scopes //我們在將Asp.Net Identity新增到DI容器中時,一定要把註冊IdentityServer放在Asp.Net Identity之後, //因為註冊IdentityServer會覆蓋Asp.Net Identity的一些配置,這個非常重要。 services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryPersistedGrants() .AddInMemoryIdentityResources(AuthorizationConfig.GetIdentityResources()) .AddInMemoryApiResources(AuthorizationConfig.ApiResources()) .AddInMemoryClients(AuthorizationConfig.Clients()) .AddAspNetIdentity<ApplicationUser>(); services.AddMvc();
在選暖寶的Configure使用註冊項的方法中新增如下程式碼
// app.UseAuthentication(); // not needed, since UseIdentityServer adds the authentication middleware app.UseIdentityServer();
接下來使用命令dotnet run啟動專案
三. 新建地址為http://localhost:40011/的asp.net core mvc專案, 命名為MvcClientImplict
新建專案的方法和上面的.net core identity一樣, 只是不需要個人驗證. 修改launchSettings的埠是40010, 對應identityserver的配置url
nuget獲取 identitymodel
public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(options => { options.DefaultScheme = "Cookies"; options.DefaultChallengeScheme = "oidc"; }) .AddCookie("Cookies") .AddOpenIdConnect("oidc", options => { options.SignInScheme = "Cookies"; options.Authority = "http://localhost:40010"; options.RequireHttpsMetadata = false; //options.ResponseType = "id_token code"; options.ResponseType = "id_token token"; options.ClientId = "WebClientImplicit"; options.SaveTokens = true; options.ClientSecret = "SecretKey"; options.Scope.Add("ProductApi"); //options.Scope.Add("offline_access"); options.GetClaimsFromUserInfoEndpoint = true;// }); services.AddMvc(); }
下面也別忘了 app.UseAuthentication()
執行並驗證授權成功成功
四. 新建一個webApi(埠40012), 配置受到identityserver的保護
nuget :IdentityServer4.AccessTokenValidation
public void ConfigureServices(IServiceCollection services) { services.AddAuthentication("Bearer") .AddIdentityServerAuthentication(option => { option.Authority = "http://localhost:40010";//這裡填寫/.well-known/openid-configuration裡看到的issuer option.RequireHttpsMetadata = false; option.ApiName = "ProductApi"; option.ApiSecret = "SecretKey"; }); services.AddMvc(); }
app.UseAuthentication();
在預設的api上新增驗證
[Authorize]
[Route("api/[controller]")]
public class ValuesController : Controller
{
在webapi裡面新建一個 controller
[Route("api/[controller]")] [Authorize] public class IdentityController : ControllerBase { [HttpGet] public IActionResult Get() { return new JsonResult(from c in User.Claims select new { c.Type, c.Value }); } }