コード例 #1
0
        public static void UseHelseIdProtectedPaths(this IApplicationBuilder app,
                                                    IHelseIdWebKonfigurasjon config,
                                                    IHprFeatureFlags hprFlags,
                                                    IRedirectPagesKonfigurasjon redirect,
                                                    IReadOnlyCollection <PathString> excludeList)
        {
            if (!config.AuthUse)
            {
                return;
            }
            var excluded = new List <PathString>
            {
                "/favicon.ico",
                redirect.Forbidden,
                redirect.LoggedOut,
                redirect.Statuscode
            };

            if (excludeList != null && excludeList.Any())
            {
                excluded.AddRange(excludeList);
            }

            app.UseProtectPaths(new ProtectPathsOptions(DeterminePresidingPolicy(config, hprFlags), redirect.Forbidden)
            {
                Exclusions = excluded
            });
        }
コード例 #2
0
        public void AddSecretConfiguration(IHelseIdWebKonfigurasjon configAuth, OpenIdConnectOptions options)
        {
            var secretParts = configAuth.ClientSecret.Split(':');

            if (secretParts.Length != 2)
            {
                throw new InvalidEnterpriseCertificateSecretException(configAuth.ClientSecret);
            }

            var storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), secretParts[0]);
            var thumprint     = secretParts[1];

            var store = new X509Store(storeLocation);

            store.Open(OpenFlags.ReadOnly);

            var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumprint, true);

            if (certificates.Count == 0)
            {
                throw new Exception($"No certificate with thumbprint {options.ClientSecret} found in store LocalMachine");
            }

            var x509SecurityKey = new X509SecurityKey(certificates[0]);

            options.Events.OnAuthorizationCodeReceived = ctx =>
            {
                ctx.TokenEndpointRequest.ClientAssertionType = IdentityModel.OidcConstants.ClientAssertionTypes.JwtBearer;
                ctx.TokenEndpointRequest.ClientAssertion     = ClientAssertion.Generate(configAuth, x509SecurityKey);

                return(Task.CompletedTask);
            };
        }
コード例 #3
0
        public static (bool Result, string PolicyName) AddHelseIdWebAuthentication(this IServiceCollection services,
                                                                                   IHelseIdWebKonfigurasjon helseIdKonfigurasjon,
                                                                                   IRedirectPagesKonfigurasjon redirectPagesKonfigurasjon,
                                                                                   IHprFeatureFlags hprKonfigurasjon,
                                                                                   IWhitelist whitelist,
                                                                                   IHelseIdSecretHandler?secretHandler = null)
        {
            if (!helseIdKonfigurasjon.AuthUse)
            {
                return(false, "");
            }
            services.AddScoped <IHprFactory, HprFactory>();
            services.AddScoped <ICurrentUser, CurrentHttpUser>();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            (var authorizeFilter, string policyName) = AddAuthentication(services, helseIdKonfigurasjon, redirectPagesKonfigurasjon, hprKonfigurasjon, whitelist, secretHandler);
            services.AddControllers(config => config.Filters.Add(authorizeFilter));
            if (helseIdKonfigurasjon.UseHprNumber)
            {
                services.AddScoped <IAuthorizationHandler, HprAuthorizationHandler>();
            }
            if (hprKonfigurasjon.UseHpr && hprKonfigurasjon.UseHprPolicy)
            {
                services.AddScoped <IAuthorizationHandler, HprGodkjenningAuthorizationHandler>();
            }
            return(true, policyName);
        }
コード例 #4
0
        public static void DefaultHelseIdOptions(this OpenIdConnectOptions options,
                                                 IHelseIdWebKonfigurasjon configAuth,
                                                 IRedirectPagesKonfigurasjon redirectPagesKonfigurasjon,
                                                 IHelseIdSecretHandler?secretHandler = null)
        {
            var acrValues    = GetAcrValues(configAuth); // spesielt for id-porten, e.g. krever sikkerhetsnivå 4
            var hasAcrValues = !string.IsNullOrWhiteSpace(acrValues);

            options.Authority            = configAuth.Authority;
            options.RequireHttpsMetadata = true;
            options.ClientId             = configAuth.ClientId;

            options.ResponseType = "code";
            options.TokenValidationParameters.ValidAudience = configAuth.ClientId;
            options.CallbackPath          = "/signin-callback";
            options.SignedOutCallbackPath = "/signout-callback";
            options.Scope.Clear();
            //options.CorrelationCookie.SameSite = SameSiteMode.Lax;
            //options.NonceCookie.SameSite = SameSiteMode.Lax;
            foreach (var scope in configAuth.AllScopes)
            {
                options.Scope.Add(scope.Trim());
            }
            options.SaveTokens = true;
            options.Events.OnRedirectToIdentityProvider = ctx =>
            {
                //API requests should get a 401 status instead of being redirected to login
                if (ctx.Request.Path.StartsWithSegments("/api"))
                {
                    ctx.Response.Headers["Location"] = ctx.ProtocolMessage.CreateAuthenticationRequestUrl();
                    ctx.Response.StatusCode          = StatusCodes.Status401Unauthorized;
                    ctx.HandleResponse();
                }

                if (ctx.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication && hasAcrValues)
                {
                    ctx.ProtocolMessage.AcrValues = acrValues;
                }

                return(Task.CompletedTask);
            };

            options.AccessDeniedPath = redirectPagesKonfigurasjon.Forbidden;

            if (secretHandler == null)
            {
                // Defaults to Shared Secret to be backwards compatible
                secretHandler = new HelseIdSharedSecretHandler();
            }

            secretHandler.AddSecretConfiguration(configAuth, options);

            string GetAcrValues(IHelseIdWebKonfigurasjon helseIdWebKonfigurasjon)
            {
                return(string.Join(' ', helseIdWebKonfigurasjon.SecurityLevels.Select(sl => $"Level{sl}")));
            }
        }
コード例 #5
0
 /// <summary>
 /// Determine the presiding policy from configuration.
 /// Will return Policies.HidAuthenticated if no other policies are configured.
 /// </summary>
 /// <param name="helseIdWebKonfigurasjon"></param>
 /// <param name="hprFeatureFlags"></param>
 /// <returns></returns>
 private static string DeterminePresidingPolicy(IHelseIdWebKonfigurasjon helseIdWebKonfigurasjon, IHprFeatureFlags hprFeatureFlags)
 => new []
 {
     new { PolicyActive = helseIdWebKonfigurasjon.UseHprNumber && hprFeatureFlags.UseHprPolicy, Policy = Policies.GodkjentHprKategoriPolicy },
     new { PolicyActive = helseIdWebKonfigurasjon.UseHprNumber, Policy = Policies.HprNummer },
     new { PolicyActive = true, Policy = Policies.HidAuthenticated }
 }
 .ToList()
 .First(p => p.PolicyActive).Policy;
コード例 #6
0
        public void AddSecretConfiguration(IHelseIdWebKonfigurasjon configAuth, OpenIdConnectOptions options)
        {
            var jwk            = File.ReadAllText(configAuth.ClientSecret);
            var jwkSecurityKey = new JsonWebKey(jwk);

            options.Events.OnAuthorizationCodeReceived = ctx =>
            {
                ctx.TokenEndpointRequest.ClientAssertionType = IdentityModel.OidcConstants.ClientAssertionTypes.JwtBearer;
                ctx.TokenEndpointRequest.ClientAssertion     = ClientAssertion.Generate(configAuth, jwkSecurityKey);

                return(Task.CompletedTask);
            };
        }
コード例 #7
0
 public static void DefaultHelseIdOptions(this CookieAuthenticationOptions options,
                                          IHelseIdWebKonfigurasjon configAuth,
                                          IRedirectPagesKonfigurasjon redirectPagesKonfigurasjon)
 {
     options.ExpireTimeSpan      = TimeSpan.FromMinutes(60);
     options.SlidingExpiration   = true;
     options.Cookie.HttpOnly     = true;
     options.Cookie.IsEssential  = true;
     options.Cookie.SecurePolicy = configAuth.UseHttps ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest;
     options.AccessDeniedPath    = redirectPagesKonfigurasjon.Forbidden;
     // NOTE: options.Events must be set in AddAutomaticTokenManagement.
     // This is because it overrides the events set here.
 }
コード例 #8
0
        public void AddSecretConfiguration(IHelseIdWebKonfigurasjon configAuth, OpenIdConnectOptions options)
        {
            var xml = File.ReadAllText(configAuth.ClientSecret);
            var rsa = RSA.Create();

            rsa.FromXmlString(xml);
            var rsaSecurityKey = new RsaSecurityKey(rsa);

            options.Events.OnAuthorizationCodeReceived = ctx =>
            {
                ctx.TokenEndpointRequest.ClientAssertionType = IdentityModel.OidcConstants.ClientAssertionTypes.JwtBearer;
                ctx.TokenEndpointRequest.ClientAssertion     = ClientAssertion.Generate(configAuth, rsaSecurityKey);

                return(Task.CompletedTask);
            };
        }
コード例 #9
0
ファイル: Jwt.cs プロジェクト: mmalvik/fhi.helseid
        public static string Generate(IHelseIdWebKonfigurasjon configAuth, SecurityKey securityKey)
        {
            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha512);

            var extraClaims = new List <Claim>
            {
                new Claim(JwtClaimTypes.Subject, configAuth.ClientId),
                new Claim(JwtClaimTypes.IssuedAt, DateTimeOffset.Now.ToUnixTimeSeconds().ToString()),
                new Claim(JwtClaimTypes.JwtId, Guid.NewGuid().ToString("N"))
            };

            var audience = Path.Combine(configAuth.Authority, "connect/token");

            var payload = CreatePayload(configAuth.ClientId, audience, extraClaims);
            var header  = new JwtHeader(signingCredentials);

            UpdateJwtHeader(securityKey, header);

            var tokenHandler = new JwtSecurityTokenHandler();

            return(tokenHandler.WriteToken(new JwtSecurityToken(header, payload)));
        }
コード例 #10
0
 public void AddSecretConfiguration(IHelseIdWebKonfigurasjon configAuth, OpenIdConnectOptions options)
 {
     options.ClientSecret = configAuth.ClientSecret;
 }
コード例 #11
0
        public static (AuthorizationPolicy AuthPolicy, string PolicyName) AddHelseIdAuthorizationPolicy(this IServiceCollection services,
                                                                                                        IHelseIdHprFeatures helseIdFeatures,
                                                                                                        IHprFeatureFlags hprFeatures,
                                                                                                        IHelseIdWebKonfigurasjon helseIdWebKonfigurasjon,
                                                                                                        IWhitelist whitelist)
        {
            var authenticatedHidUserPolicy = new AuthorizationPolicyBuilder()
                                             .RequireAuthenticatedUser()
                                             .RequireClaim(IdentityClaims.SecurityLevel, helseIdWebKonfigurasjon.SecurityLevels)
                                             .Build();

            if (helseIdFeatures.UseHprNumber)
            {
                var hprNumberPolicyBuilder = new AuthorizationPolicyBuilder()
                                             .Combine(authenticatedHidUserPolicy);
                hprNumberPolicyBuilder.Requirements.Add(new HprAuthorizationRequirement());
                var hprNumberPolicy = hprNumberPolicyBuilder.Build();

                if (hprFeatures.UseHpr && hprFeatures.UseHprPolicy)
                {
                    var policy = new AuthorizationPolicyBuilder()
                                 .Combine(hprNumberPolicy);
                    policy.Requirements.Add(new HprGodkjenningAuthorizationRequirement());
                    var HprGodkjenningPolicy = policy.Build();
                    services.AddAuthorization(config =>
                    {
                        config.AddPolicy(Policies.HidAuthenticated, authenticatedHidUserPolicy);
                        config.AddPolicy(Policies.HprNummer, hprNumberPolicy);
                        config.AddPolicy(Policies.GodkjentHprKategoriPolicy, HprGodkjenningPolicy);
                        config.DefaultPolicy = HprGodkjenningPolicy;
                    });
                    return(HprGodkjenningPolicy, Policies.GodkjentHprKategoriPolicy);
                }

                services.AddAuthorization(config =>
                {
                    config.AddPolicy(Policies.HidAuthenticated, authenticatedHidUserPolicy);
                    config.AddPolicy(Policies.HprNummer, hprNumberPolicy);
                    config.DefaultPolicy = hprNumberPolicy;
                });
                return(hprNumberPolicy, Policies.HprNummer);
            }

            services.AddAuthorization(config =>
            {
                config.AddPolicy(Policies.HidAuthenticated, authenticatedHidUserPolicy);
                config.DefaultPolicy = authenticatedHidUserPolicy;
            });
            return(authenticatedHidUserPolicy, Policies.HidAuthenticated);
        }
コード例 #12
0
        /// <summary>
        /// Normally used by AddHelseIdWebAuthentication
        /// </summary>
        public static (AuthorizeFilter AuthorizeFilter, string PolicyName) AddAuthentication(IServiceCollection services,
                                                                                             IHelseIdWebKonfigurasjon helseIdKonfigurasjon,
                                                                                             IRedirectPagesKonfigurasjon redirectPagesKonfigurasjon,
                                                                                             IHprFeatureFlags hprKonfigurasjon,
                                                                                             IWhitelist whitelist,
                                                                                             IHelseIdSecretHandler?secretHandler = null
                                                                                             )
        {
            const double tokenRefreshBeforeExpirationTime = 2;

            services.AddHelseIdAuthentication()
            .AddCookie(options =>
            {
                options.DefaultHelseIdOptions(helseIdKonfigurasjon, redirectPagesKonfigurasjon);
            })
            .AddOpenIdConnect(HelseIdContext.Scheme, options =>
            {
                options.DefaultHelseIdOptions(helseIdKonfigurasjon, redirectPagesKonfigurasjon, secretHandler);
            })
            .AddAutomaticTokenManagement(options => options.DefaultHelseIdOptions(tokenRefreshBeforeExpirationTime));       // For å kunne ha en lengre sesjon,  håndterer refresh token

            (var authPolicy, string policyName) = services.AddHelseIdAuthorizationPolicy(helseIdKonfigurasjon, hprKonfigurasjon, helseIdKonfigurasjon, whitelist);

            return(new AuthorizeFilter(authPolicy), policyName);
        }