.NET Core IdentityServer4实战 第二章-OpenID Connect添加用户认证

内容:本文带你们使用IdentityServer4进行使用OpenID Connect添加用户认证git

做者:zara(张子浩) 欢迎分享,但需在文章鲜明处留下原文地址。github

  在这一篇文章中咱们但愿使用OpenID Connect这种方式来验证咱们的MVC程序,咱们首先须要干什么呢?那就是搞一个UI,这样很是美观既能够看到咱们的身份验证效果,那么IdentityServer官方已经给咱们提供了一套UI了,咱们从哪里能够获取呢?shell

  能够经过这个地址就行克隆安装到本地并附加到你的MVC程序中,地址。固然咱们能够根据PowerShell 进行远程拉取(如下命令在项目根目录进行Code)数据库

在Windows中咱们的命令以下:bash

iex ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/IdentityServer/IdentityServer4.Quickstart.UI/master/getmaster.ps1'))

或者在macOS或Linux上使用bash one-line:服务器

\curl -L https://raw.githubusercontent.com/IdentityServer/IdentityServer4.Quickstart.UI/master/getmaster.sh | bash

 下图所示是我在Windows Powershell中进行远程拉取的。微信

安装完项目中会添加一个Quickstart的这么一个文件夹,其中有IdentityServer给咱们写好的代码,有控制器,模型,视图,静态文件等等。cookie

固然还须要在Startup类中配置好你的MVC,这须要在ConfigureService里面将MVC添加到DI中并在Configure方法中将MVC中间件添加到管道上。mvc

// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = "Cookies";
                options.DefaultChallengeScheme = "oidc";
            })  .AddCookie("Cookies")
                .AddOpenIdConnect("oidc", options =>
                {
                    options.Authority = "http://localhost:5000";
                    options.RequireHttpsMetadata = false;

                    options.ClientId = "mvc";
                    options.SaveTokens = true;
                });
        }

  首先咱们经过 AddAuthentication 将身份验证服务添加到咱们的DI中。其中参数有三个,第一个 DefaultScheme 它呢能够设置咱们经过Cookies进行保存登陆信息。那么后面是咱们的 DefaultChallengeScheme ,它的参数是 oidc ,也就是由于当咱们须要用户登陆时,咱们将使用OpenID Connect协议。而后 AddCookie 咱们使用添加可处理cookie的处理程序。最后, AddOpenIdConnect 用于配置执行OpenID Connect协议的处理程序。这 Authority 代表咱们信任IdentityServer。而后咱们经过 ClientId 识别这个客户。  SaveTokens 用于在cookie中保留来自IdentityServer的令牌,同时我还关闭了JWT声明映射,这样会让咱们的应用程序流畅地经过: JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); 。app

  最后,咱们须要让咱们的认证请求达到响应,应在管道中的MVC以前添加认证中间件。

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            ///xxx//添加服务请求
            app.UseAuthentication();
       ///xxx
        }

  为了触发验证,咱们在 HomeController 中添加一个特性 [Authorize] 。还要修改该Action的View以显示用户的信息,例如:

@using Microsoft.AspNetCore.Authentication
<dl> @foreach (var claim in User.Claims) { <dt>@claim.Type</dt> <dd>@claim.Value</dd> } </dl> <h2>Properties</h2> <dl> @foreach (var prop in (await Context.AuthenticateAsync()).Properties.Items) { <dt>@prop.Key</dt> <dd>@prop.Value</dd> } </dl>

若是你如今启动的话,会出现内部错误,由于MVC客户端在认证平台服务器中并无注册。

如今咱们回到咱们的认证服务中心,在Config.cs中添加以下代码(范围表明您想要保护的内容以及客户想要访问的内容。与OAuth相比,OIDC中的范围不表明API,而是表明用户ID,名称或电子邮件地址等身份数据。

public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
            };
        }

而后,您须要将这些身份资源添加到Startup.cs中的IdentityServer配置中。使用 AddInMemoryIdentityResources 扩展方法调用 AddIdentityServer() 。

public void ConfigureServices(IServiceCollection services)
        {
            // configure identity server with in-memory stores, keys, clients and scopes
            services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.GetSoluction())
                .AddInMemoryClients(Config.GetClients())
                //.AddTestUsers(Config.GetUsers());

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

   最后一步是将MVC客户端的配置添加到IdentityServer。基于OpenID Connect的客户端与咱们目前添加的OAuth 2.0客户端很是类似。但因为OIDC中的流程始终是交互式的,所以咱们须要在配置中添加一些重定向URL。将如下内容添加到您的客户端配置:

public static IEnumerable<Client> GetClients()
{
    return new List<Client>
    {
        // other clients omitted...

        // OpenID Connect implicit flow client (MVC)
        new Client
        {
            ClientId = "mvc",
            ClientName = "MVC Client",
            AllowedGrantTypes = GrantTypes.Implicit,

            // where to redirect to after login
            RedirectUris = { "http://localhost:5002/signin-oidc" },

            // where to redirect to after logout
            PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },

            AllowedScopes = new List<string>
            {
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile
            }
        }
    };
}

 就这样咱们启动项目,如今启动项目也就没有什么问题了。

 其中咱们用到了IdentityServer的Quickstart,虽然说已经写好了不少相关的控制器等等,这个Ui可是仍是本身写个好,或者改造!

总结:这篇文章说明了Server和Client之间的配置关系,Client不用管Server,只须要知道 Authority 的地址,携带其中的 ClientId ,而Server中相比上一篇文章中咱们多了 Client 里面有ClientId用于和Client端匹配,那么咱们就能够存到数据库中!而Server端须要注入Client信息,经过 AddInMemoryClients 方法。固然你想到这里了,那么就必定能够介入QQ登陆、微信登陆了、后续的文章会写这些!

相关文章
相关标签/搜索