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

一. 新建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()

运行并验证授权成功成功

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

 

 

posted @ 2018-07-10 22:06  MyCoolDog  阅读(840)  评论(0编辑  收藏  举报