.net Core IdentityServer4实例

@[TOC](.net Core IdentityServer4(4.1.2版本)实战)

VS2019 .NET5.0 新建IdentityServer4项目

1.新建ASP.NET Core Web应用项目,选择.net5.0,命名MyIdentityServer
2.引用gutnet包:IdentityServer4(4.1.2),IdentityServer4.AspNetIdentity(4.1.2),Microsoft.AspNetCore.Authentication.JwtBearer(5.0.9)
3.添加Config配置文件:

/// <summary>
    /// 1、Identity测试使用
    /// </summary>
    public class Config
    {
        /// <summary>
        /// 1、微服务API资源
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new List<ApiResource>()
            {
                new ApiResource("api1","My api"){ Scopes={"api1"} }
            };
        }
        //创建具体的scope
        public static IEnumerable<ApiScope> GetApiScopes()
        {
            return new ApiScope[] {
                new ApiScope("api1","My first api")};
        }
        /// <summary>
        /// 2、客户端
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
            {
                new Client
                {
                    ClientId = "client",
                    // 没有交互性用户,使用 clientid/secret 实现认证。
                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    // 用于认证的密码
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },
                    // 客户端有权访问的范围(Scopes)
                    AllowedScopes = {  "api1" },
                    AllowOfflineAccess=true
                },
                new Client
                {
                    ClientId = "client-jiafxh",
                    // 没有交互性用户,使用 clientid/secret 实现认证。
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                    // 用于认证的密码
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },
                    // 客户端有权访问的范围(Scopes)
                    AllowedScopes = { "api1" },
                    AllowOfflineAccess=true
                },
                new Client
                {
                    ClientId="client-code",
                    ClientSecrets={new Secret("secret".Sha256())},
                    AllowedGrantTypes=GrantTypes.Code,// 这是单点登录标志
                    RequireConsent =false,
                    RequirePkce=true,
                    RedirectUris={ "http://localhost:5002/signin-oidc"}, // 让首页网站知道
                    PostLogoutRedirectUris={ "http://localhost:5002/signout-callback-oidc"},// 注销账号让首页网站知道
                    AllowedScopes = {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "api1" 
                    },
                    AllowOfflineAccess=true
                },
                new Client
                {
                    ClientId = "eom",
                    ClientName = "eom Client",
                    AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                    ClientSecrets =
                    {
                        new Secret("secreteom".Sha256())
                    },
                    RequireConsent = false,
                    RedirectUris = { "http://localhost:5002/signin-oidc" },
                    PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },
                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                          "api1"
                    },
                    AllowOfflineAccess = true,
                    //直接返回客户端需要的Claims
                    AlwaysIncludeUserClaimsInIdToken = true,  AllowAccessTokensViaBrowser = true
                },
                new Client
                {
                    ClientId = "eomui",
                    ClientName = "eomui Client",
                    AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                    ClientSecrets =
                    {
                        new Secret("secreteomui".Sha256())
                    },
                    RequireConsent = false,
                    RedirectUris = { "http://localhost:5002/signin-oidc" },
                    PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },
                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "api1"
                    },
                    AllowOfflineAccess = true,
                    //直接返回客户端需要的Claims
                    AlwaysIncludeUserClaimsInIdToken = true,  AllowAccessTokensViaBrowser = true
                },
            };
        }

        /// <summary>
        /// 客户端下面的用户
        /// </summary>
        /// <returns></returns>
        public static List<TestUser> GetUsers()
        {
            return new List<TestUser>()
            {
                new TestUser
                {
                    SubjectId="1",
                    Username="jiafxh",
                    Password="123456"
                }
            };
        }

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

4.配置Startup:

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

            //配置Cookie决策
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath = new PathString("/Account/login");
                options.AccessDeniedPath = new PathString("/denied");
            }); ;

            // 配置IdentityServer4
            services.AddIdentityServer()
                .AddDeveloperSigningCredential()// 1、用户登录配置
                .AddInMemoryIdentityResources(Config.Ids)// 4、注册openid资源
                .AddInMemoryClients(Config.GetClients()) // 3、注册客户端(模式)
                .AddTestUsers(Config.GetUsers())// 4、注册登录用户(模式)
                .AddInMemoryApiScopes(Config.GetApiScopes());// 2、注册Api资源
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseAuthentication();
            app.UseIdentityServer();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

获取 QuickStart UI

打开项目地址,执行cmd
运行命令:dotnet new -i identityserver4.templates
执行完后继续运行:dotnet new is4ui
都执行完毕后你会看到你的项目下多了Quickstart和Views两个文件夹

运行项目如下:

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值