当前位置: 移动技术网 > IT编程>开发语言>.net > .NET Core IdentityServer4实战 第二章-OpenID Connect添加用户认证

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

2019年01月29日  | 移动技术网IT编程  | 我要评论

可行性研究报告范文,碳纤维加热板,宝摇2

内容:本文带大家使用identityserver4进行使用openid connect添加用户认证

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

  在这一篇文章中我们希望使用openid connect这种方式来验证我们的mvc程序(需要有identityserver4),我们首先需要干什么呢?那就是搞一个ui,这样非常美观既可以看到我们的身份验证效果,那么identityserver官方已经给我们提供了一套ui了,我们从哪里可以获取呢?

  可以通过这个地址就行克隆安装到本地并附加到你的mvc程序中,地址。当然我们可以根据powershell 进行远程拉取(以下命令在项目根目录进行code)

在windows中我们的命令如下:

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给我们写好的代码,有控制器,模型,视图,静态文件等等。

当然还需要在startup类中配置好你的mvc,这需要在configureservice里面将mvc添加到di中并在configure方法中将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(); 。

  最后,我们需要让我们的认证请求达到响应,应在管道中的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登录、微信登录了、后续的文章会写这些!

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网