.net core Identity集成IdentityServer4 (1)基本操做

一. 新建asp.net core identity項目

 

新建項目->asp.net core web應用程序-> web應用程序(模型視圖控制器)&更改身份驗證爲我的.git

新建一個空數據庫, 而後在appsettings中的鏈接字符串指向該空庫.web

"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 ApplicationDbContextapi

會在指定的空庫中建立Identity的相應數據表.mvc

修改launchSettings的Project執行方式的url爲 http://localhost:40010app

在Startup.cs中添加以下代碼, 配置asp.net core identity的用戶相關信息asp.net

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>();

啓動並運行, 註冊一個用戶, 而且確保登陸成功ide

 

 

二. 集成IdentityServer

添加IdentityServer4.aspnetIdentity的Nuget包, 同時會自動添加IdentityServer4.微服務

在根目錄下新建一個AuthorizationConfig.cs類.ui

添加以下代碼

/// <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()

運行並驗證受權成功成功

image

 

四. 新建一個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
   {

image

在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 });
        }
    }

image

相關文章
相關標籤/搜索