Добиться единого входа с помощью Identity Server 3 в MVC - PullRequest
0 голосов
/ 27 сентября 2019

Я установил идентификационный сервер 3 в моем приложении.Ниже приведен код:

public void ConfigureAuth(IAppBuilder app)
    {
        // Configure Identity Server
        // at the identity uri, you are going to find the identity server
        app.Map("/identity", idsrvApp =>
        {
            idsrvApp.UseIdentityServer(new IdentityServerOptions
            {
                SiteName = "Embedded identity server",
                //IssuerUri = "https://identitysrv3/embedded", // in real scenarios  make sure this is unique. to uniquely identify users

                Factory = new IdentityServerServiceFactory()
                .UseInMemoryClients(Clients.Get())
                .UseInMemoryScopes(Scopes.Get())
                .UseInMemoryUsers(User.Get()),

                // this is not for SSL, that will be provided by IIS or Azure where we deploy. This is to sign the tokens
                SigningCertificate = LoadCertificate()
            });
        });        

        X509Certificate2 LoadCertificate()
        {
            return new X509Certificate2(
        string.Format(@"{0}\bin\identityServer\idsrv3test.pfx", AppDomain.CurrentDomain.BaseDirectory), "idsrv3test");
        }
    }

С этим сейчас я использую пользователей памяти.Нужно ли реализовывать удостоверение ASP.NET для достижения единого входа?

Это мой класс пользователя:

public static List<InMemoryUser> Get()
    {
        return new List<InMemoryUser>()
        {
            new InMemoryUser
            {
                Username = "Sidd",
                Password = "secret",
                Subject = "1",

                Claims = new[]
                {
                    new Claim(Constants.ClaimTypes.GivenName, "Sidd"),
                    new Claim(Constants.ClaimTypes.FamilyName, "Mehta"),
                }
            },
            new InMemoryUser
            {
                Username = "Humpty",
                Password = "secret",
                Subject = "3",

                Claims = new[]
                {
                    new Claim(Constants.ClaimTypes.GivenName, "Humpty"),
                    new Claim(Constants.ClaimTypes.FamilyName, "Sharma"),
                }
            },
            new InMemoryUser
            {
                Username = "Virat",
                Password = "secret",
                Subject = "4",

                Claims = new[]
                {
                    new Claim(Constants.ClaimTypes.GivenName, "Virat"),
                    new Claim(Constants.ClaimTypes.FamilyName, "Kohli"),
                }
            }
        };
    }

, а это мой класс клиентов:

 public static IEnumerable<Client> Get()
    {
        return new[]
        {
            new Client
            {
                Enabled = true,
                ClientName = "Identity Server Web Access",
                ClientId = "mvc",
                Flow = Flows.Hybrid,
                //RequireConsent = true,

                RedirectUris=new List<string>
                {
                    //"https://localhost:44329/"
                    AppConstants.IdClient,
                    AppConstants.IdClient2
                },
                AllowedScopes = new List<string>
                {
                    "openid",
                    "profile",                        
                }
            }
        };
    }

URI перенаправления содержит URL-адреса клиентских приложений MVC.

С уже заданными идентификатором и пользователями я создаю клиент приложения MVC.Обе конфигурации приложения похожи.Ниже приведен код:

Веб-клиент 2:

public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888

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

        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            ClientId = "mvc",
            Authority = AppConstants.IdSrv,
            RedirectUri = AppConstants.IdClient2,
            SignInAsAuthenticationType = "Cookies",
            ResponseType = "code id_token",
            Scope = "openid",

            Notifications = new OpenIdConnectAuthenticationNotifications()
            {
                MessageReceived = async n =>
                {
                    EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.IdToken);
                }

            }
        });
    }

Веб-клиент 1:

public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888

        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = new Dictionary<string, string>();

        AntiForgeryConfig.UniqueClaimTypeIdentifier = "unique_user_key";

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

        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            ClientId = "mvc",
            Authority = AppConstants.IdSrv,
            RedirectUri = AppConstants.IdClient,
            SignInAsAuthenticationType = "Cookies",
            ResponseType = "code id_token token",
            Scope = "openid profile",

            Notifications = new OpenIdConnectAuthenticationNotifications()
            {
                MessageReceived = async n =>
                {
                    //EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.IdToken);
                    //EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.AccessToken);

                    //var userinfo = await EndpointAndTokenHelper.CallUserInfoEndpoint(n.ProtocolMessage.AccessToken);
                },

                SecurityTokenValidated=async n =>
                {
                    var userInfo = await EndpointAndTokenHelper.CallUserInfoEndpoint(n.ProtocolMessage.AccessToken);

                    var givenNameClaim = new Claim(
                        Thinktecture.IdentityModel.Client.JwtClaimTypes.GivenName,
                        userInfo.Value<string>("given_name"));

                    var familyNameClaim = new Claim(
                        Thinktecture.IdentityModel.Client.JwtClaimTypes.FamilyName,
                        userInfo.Value<string>("family_name"));

                    //var roles = userInfo.Value<JArray>("role").ToList();

                    var newIdentity = new ClaimsIdentity(
                       n.AuthenticationTicket.Identity.AuthenticationType,
                       Thinktecture.IdentityModel.Client.JwtClaimTypes.GivenName,
                       Thinktecture.IdentityModel.Client.JwtClaimTypes.Role);

                    newIdentity.AddClaim(givenNameClaim);
                    newIdentity.AddClaim(familyNameClaim);
                }


            }
        });            
    }

Я хочу знать, какие дополнительные настройки необходимо выполнить, чтобыдобиться единого входа?Я могу подключиться к серверу идентификации, ввести свои учетные данные пользователя, иметь свои URI перенаправления.

Когда я захожу на оба веб-сайта, он запрашивает учетные данные пользователя при вызове атрибута [Authorize] в моем доме.контроллер.

...