Как выполнить единый вход с помощью IdentityServer4 на существующий ASP.NET MVC5 Boilerplate - PullRequest
0 голосов
/ 27 апреля 2019

Я устанавливаю единый вход для своей компании, для этого я использую IdentityServer4 с LdapExtension (Вот пример).

Это позволяет пользователям проходить аутентификацию в любом приложении.с учетными данными ActiveDirectory

Теперь дело в том, что компания использует приложения в ASP.NET MVC5 BOILERPLATE с AngularJS и что я не могу заставить приложение понимать объекты пользователя, поступающие изIdentityServer

Может ли кто-нибудь помочь мне с этой реализацией?


Я попробовал это сделать

Вот мои настройки на IdentityServer:

  • StartupClass:

    public class Startup{
    public Startup(IHostingEnvironment env, IConfiguration configuration)
    {
        Env = env;
        Configuration = configuration;
    }
    
    private IHostingEnvironment Env { get; }
    private IConfiguration Configuration { get; }
    
    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 Configure(IApplicationBuilder app)
    {
        if (Env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
    
        app.UseIdentityServer();
        app.UseStaticFiles();
        app.UseMvcWithDefaultRoute();
    }
    }
    
  • My InMemoryInitConfig:

    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"
                },
    
            },
    
    
    
        };
    }
    }
    

Вот моя сторона клиента:

  • StatupClass:

    public class Startup{
    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
    
        #region idsr4
        /// IDENTITYSERVER
    
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "Cookies"
        });
    
        // config do openID
        var openIdConfig = new OpenIdConnectAuthenticationOptions
        {
            Authority = "http://localhost:5443", //ID Server0
            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,
    
            // Pega as informações do endpoint de compinfo do identityserver
            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);
    
                    // HACK: NAÔ SEI PERCORRER ENUM 
                    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 });
    
                }
            }
    
        };
        // fim config do openID
    
        app.UseOpenIdConnectAuthentication(openIdConfig);
    
        // END IDENTITYSERVER
        #endregion
    
        app.UseExternalSignInCookie("Cookies");
    
        app.MapSignalR();
    }
    }
    
...