Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将IdentityServer4标识映射到任何Web应用程序(.Net MVC样板文件、.Net核心样板文件)_C#_Asp.net Mvc_Identityserver4_Aspnetboilerplate - Fatal编程技术网

C# 如何将IdentityServer4标识映射到任何Web应用程序(.Net MVC样板文件、.Net核心样板文件)

C# 如何将IdentityServer4标识映射到任何Web应用程序(.Net MVC样板文件、.Net核心样板文件),c#,asp.net-mvc,identityserver4,aspnetboilerplate,C#,Asp.net Mvc,Identityserver4,Aspnetboilerplate,我正在创建一个SSO服务器,将所有用户集中在ActiveDirectory(AD)中,并在那里管理它们,而不是管理每个特定应用程序的数据库 为了创建此服务器,我使用IdentityServer4(Idsr4)和 我已经将Idsr4设置为使用基于广告的标识(这是“集中式标识”),用户现在可以使用自己的广告登录/密码登录Idsr4 现在的问题是如何将集中式标识映射到应用程序。我想在几个应用程序中使用相同的身份用户 我通读了IdentityServer4的文档,但找不到任何与提议的结构相关的内容 是否

我正在创建一个SSO服务器,将所有用户集中在ActiveDirectory(AD)中,并在那里管理它们,而不是管理每个特定应用程序的数据库

为了创建此服务器,我使用IdentityServer4(Idsr4)和

我已经将Idsr4设置为使用基于广告的标识(这是“集中式标识”),用户现在可以使用自己的广告登录/密码登录Idsr4

现在的问题是如何将集中式标识映射到应用程序。我想在几个应用程序中使用相同的身份用户

我通读了IdentityServer4的文档,但找不到任何与提议的结构相关的内容

是否有人有清晰的结构设置,可以用来理解整个设置?(如Asp.NETMVC样板文件、IdentityServer4、受保护的Api等分离。)

IdentityServer4配置:

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        // configure identity server with in-memory stores, keys, clients and scopes
        services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            ////.AddSigningCredential(...) // Strongly recommended, if you want something more secure than developer signing (Read The Manual since it's highly recommended)
            .AddInMemoryIdentityResources(InMemoryInitConfig.GetIdentityResources())
            .AddInMemoryApiResources(InMemoryInitConfig.GetApiResources())
            .AddInMemoryClients(InMemoryInitConfig.GetClients())
            .AddLdapUsers<OpenLdapAppUser>(Configuration.GetSection("IdentityServerLdap"), UserStore.InMemory);
    }
public void配置服务(IServiceCollection服务)
{
services.AddMvc();
//使用内存存储、密钥、客户端和作用域配置identity server
services.AddIdentityServer()
.AddDeveloperSigningCredential()
////.AddSigningCredential(…)//如果您想要比开发人员签名更安全的东西,强烈建议您阅读该手册,因为它是强烈建议的)
.AddInMemoryIdentityResources(InMemoryInitConfig.GetIdentityResources())
.AddInMemoryApiResources(InMemoryInitConfig.GetApiResources())
.AddInMemoryInputConfig.GetClient()中的
.AddLdapUsers(Configuration.GetSection(“IdentityServerLdap”)、UserStore.InMemory);
}
MemoryInitConfig中的IdentityServer4:

namespace QuickstartIdentityServer{
public class InMemoryInitConfig
{
    // scopes define the resources in your system
    public static IEnumerable<IdentityResource> GetIdentityResources()
    {
        return new List<IdentityResource>
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
        };
    }

    public static IEnumerable<ApiResource> GetApiResources()
    {
        return new List<ApiResource>
        {
            new ApiResource("api1", "My API")
        };
    }

    // clients want to access resources (aka scopes)
    public static IEnumerable<Client> GetClients()
    {
        // client credentials client
        return new List<Client>
        {
            
            //DEMO HTTP CLIENT
            new Client
            {
                ClientId = "demo",
                ClientSecrets = new List<Secret> {new Secret("password".Sha256()) } ,
                ClientName = "demo",
                AllowedGrantTypes = {
                    GrantType.ClientCredentials, // Server to server
                    GrantType.ResourceOwnerPassword, // User to server
                    GrantType.Implicit
                },

                //GrantTypes.HybridAndClientCredentials,
                AllowAccessTokensViaBrowser = true,

                AllowOfflineAccess = true,
                AccessTokenLifetime = 90, // 1.5 minutes
                AbsoluteRefreshTokenLifetime = 0,
                RefreshTokenUsage = TokenUsage.OneTimeOnly,
                RefreshTokenExpiration = TokenExpiration.Sliding,
                UpdateAccessTokenClaimsOnRefresh = true,
                RequireConsent = false,

                RedirectUris = {
                    "http://localhost:6234/"
                },

                PostLogoutRedirectUris = { "http://localhost:6234" },
                AllowedCorsOrigins ={ "http://localhost:6234/" },

                AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    "api1"
                },
                
            },

            

        };
    }
}
命名空间QuickstartIdentityServer{
MemoryInitConfig中的公共类
{
//作用域定义系统中的资源
公共静态IEnumerable GetIdentityResources()
{
返回新列表
{
新标识资源.OpenId(),
新标识资源.Profile(),
};
}
公共静态IEnumerable GetApiResources()
{
返回新列表
{
新的API资源(“api1”、“我的API”)
};
}
//客户端希望访问资源(也称为作用域)
公共静态IEnumerable GetClients()
{
//客户端凭据客户端
返回新列表
{
//演示HTTP客户端
新客户
{
ClientId=“演示”,
ClientSecrets=新列表{new Secret(“password”.Sha256())},
ClientName=“演示”,
AllowedGrantTypes={
GrantType.ClientCredentials,//服务器到服务器
GrantType.ResourceOwnerPassword,//用户到服务器
GrantType.Implicit
},
//GrantTypes.HybridAndClientCredentials,
AllowAccessTokensViaBrowser=true,
AllowOfflineAccess=true,
AccessTokenLifetime=90,//1.5分钟
绝对寿命=0,
RefreshTokenUsage=TokenUsage.OneTimeOnly,
RefreshTokenExpiration=令牌过期。滑动,
UpdateAccessTokenClaimsOnRefresh=true,
RequireSent=false,
重定向URI={
"http://localhost:6234/"
},
PostLogoutRedirectUris={”http://localhost:6234" },
AllowedCorsOrigins={”http://localhost:6234/" },
允许范围=
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
“api1”
},
},
};
}
}
}

我的客户端配置:

public void Configuration(IAppBuilder app)

    {
        
        app.UseAbp();

        app.UseOAuthBearerAuthentication(AccountController.OAuthBearerOptions);

        // ABP
        //app.UseCookieAuthentication(new CookieAuthenticationOptions
        //{
        //    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        //    LoginPath = new PathString("/Account/Login"),
        //    // evaluate for Persistent cookies (IsPermanent == true). Defaults to 14 days when not set.
        //    //ExpireTimeSpan = new TimeSpan(int.Parse(ConfigurationManager.AppSettings["AuthSession.ExpireTimeInDays.WhenPersistent"] ?? "14"), 0, 0, 0),
        //    //SlidingExpiration = bool.Parse(ConfigurationManager.AppSettings["AuthSession.SlidingExpirationEnabled"] ?? bool.FalseString)
        //    ExpireTimeSpan = TimeSpan.FromHours(12),
        //    SlidingExpiration = true
        //});
        // END ABP

        /// IDENTITYSERVER
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "Cookies"
        });

        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            Authority = "http://localhost:5443", //ID Server
            ClientId = "demo",
            ClientSecret = "password",
            ResponseType = "id_token token",
            SignInAsAuthenticationType = "Cookies",
            RedirectUri = "http://localhost:6234/", //URL of website when cancel login on idsvr4
            PostLogoutRedirectUri = "http://localhost:6234", //URL Logout ??? << when this occor
            Scope = "openid",
            RequireHttpsMetadata = false,

            //AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,

        });
        /// END IDENTITYSERVER

        app.UseExternalSignInCookie("Cookies");
        
        app.MapSignalR();
    }
public void配置(IAppBuilder应用程序)
{
app.UseAbp();
应用程序UseAuthBeareAuthentication(AccountController.OAuthBeareOptions);
//ABP
//app.UseCookieAuthentication(新的CookieAuthenticationOptions
//{
//AuthenticationType=DefaultAuthenticationTypes.ApplicationOkie,
//LoginPath=新路径字符串(“/Account/Login”),
////评估持久性Cookie(IsPermanent==true)。未设置时默认为14天。
////ExpireTimeSpan=新的时间跨度(int.Parse(ConfigurationManager.AppSettings[“AuthSession.ExpireTimeDays.WhenPersistent”]??“14”),0,0,0),
////SlidingExpiration=bool.Parse(ConfigurationManager.AppSettings[“AuthSession.SlidingExpirationEnabled”]??bool.FalseString)
//ExpireTimeSpan=从小时(12)开始的时间跨度,
//slidengexpiration=true
//});
//末端ABP
///标识服务器
app.UseCookieAuthentication(新的CookieAuthenticationOptions
{
AuthenticationType=“Cookies”
});
app.UseOpenIdConnectAuthentication(新的OpenIdConnectAuthenticationOptions
{
权威=”http://localhost:5443“,//ID服务器
ClientId=“演示”,
ClientSecret=“密码”,
ResponseType=“id\u令牌”,
SignInAsAuthenticationType=“Cookies”,
重定向URI=”http://localhost:6234/“,//取消登录idsvr4时网站的URL

PostLogoutRedirectUri=”http://localhost:6234“,//URL注销???我认为
GrantType.ResourceOwnerPassword
流不支持
AD
登录,也不支持
使用OpenIDConnectAuthentication
混合
流。
通过客户端mvc应用程序的身份验证后,您可以在
HttpContext.User
中查看任何声明,并找到正确的声明值作为用户身份(它们只是声明,无需创建本地帐户)

Ok r
public void Configuration(IAppBuilder app)

    {
        
        app.UseAbp();

        // ABP
        //app.UseOAuthBearerAuthentication(AccountController.OAuthBearerOptions);

        //app.UseCookieAuthentication(new CookieAuthenticationOptions
        //{
        //    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        //    LoginPath = new PathString("/Account/Login"),
        //    // evaluate for Persistent cookies (IsPermanent == true). Defaults to 14 days when not set.
        //    //ExpireTimeSpan = new TimeSpan(int.Parse(ConfigurationManager.AppSettings["AuthSession.ExpireTimeInDays.WhenPersistent"] ?? "14"), 0, 0, 0),
        //    //SlidingExpiration = bool.Parse(ConfigurationManager.AppSettings["AuthSession.SlidingExpirationEnabled"] ?? bool.FalseString)
        //    ExpireTimeSpan = TimeSpan.FromHours(12),
        //    SlidingExpiration = true
        //});
        // END ABP

        /// IDENTITYSERVER
        AntiForgeryConfig.UniqueClaimTypeIdentifier = Thinktecture.IdentityModel.Client.JwtClaimTypes.Subject;
        JwtSecurityTokenHandler.DefaultInboundClaimFilter.Clear();

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "Cookies"
        });

        // CONFIG OPENID
        var openIdConfig = new OpenIdConnectAuthenticationOptions
        {
            Authority = "http://localhost:5443", //ID Server
            ClientId = "demo",
            ClientSecret = "password",
            ResponseType = "id_token token",
            SignInAsAuthenticationType = "Cookies",
            RedirectUri = "http://localhost:6234/", //URL of website when cancel login on idsvr4
            PostLogoutRedirectUri = "http://localhost:6234", //URL Logout ??? << when this occor
            Scope = "openid profile api1",
            RequireHttpsMetadata = false,
            
            // get userinfo
            Notifications = new OpenIdConnectAuthenticationNotifications {
                SecurityTokenValidated = async n => {
                    var userInfoClient = new UserInfoClient(
                        new Uri(n.Options.Authority + "/connect/userinfo"),
                              n.ProtocolMessage.AccessToken);

                    var userInfo = await userInfoClient.GetAsync();
                    
                    // create new identity and set name and role claim type
                    var nid = new ClaimsIdentity(
                        n.AuthenticationTicket.Identity.AuthenticationType,
                        ClaimTypes.GivenName,
                        ClaimTypes.Role);

                    foreach (var x in userInfo.Claims) {
                        nid.AddClaim(new Claim(x.Item1, x.Item2));        
                    }

                    // keep the id_token for logout
                    nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

                    // add access token for sample API
                    nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));

                    // keep track of access token expiration
                    nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));

                    // add some other app specific claim
                    //nid.AddClaim(new Claim("app_specific", "some data"));

                    n.AuthenticationTicket = new AuthenticationTicket(
                        nid,
                        n.AuthenticationTicket.Properties);

                    n.Request.Headers.SetValues("Authorization ", new string[] { "Bearer ", n.ProtocolMessage.AccessToken });

                }
            }

        };
        // END CONFIG OPENID

        app.UseOpenIdConnectAuthentication(openIdConfig);
        
        /// END IDENTITYSERVER

        app.UseExternalSignInCookie("Cookies");
        
        app.MapSignalR();
    }