private async void Window_Loaded(object sender, RoutedEventArgs e)
      {
          var browser = new EmbeddedBrowser(webBrowser, _clientOptions.RedirectUri);

          _clientOptions.Browser = browser;

          var client = new HelseIdClient(_clientOptions);

          var result = await client.Login();

          if (result.IsError)
          {
              OnLoginError?.Invoke(this, new LoginEventArgs()
                {
                    Response = result
                });
          }
          else
          {
              OnLoginSuccess?.Invoke(this, new LoginEventArgs()
                {
                    Response      = result,
                    AccessToken   = result.AccessToken,
                    IdentityToken = result.IdentityToken,
                    IsError       = result.IsError,
                    Error         = result.Error
                });
          }
      }
Esempio n. 2
0
        private async Task Login()
        {
            if (_options == null)
            {
                MessageBox.Show("You must create a client configuration before logging in..", "Missing client configuration");
                return;
            }

            try
            {
                Dispatcher.Invoke(() =>
                {
                    if (UseJwtBearerClientAuthenticationRSA.IsChecked.HasValue &&
                        UseJwtBearerClientAuthenticationRSA.IsChecked.Value)
                    {
                        _options.SigningMethod = Common.Jwt.JwtGenerator.SigningMethod.RsaSecurityKey;
                    }
                    if (UseJwtBearerClientAuthenticationEntCert.IsChecked.HasValue &&
                        UseJwtBearerClientAuthenticationEntCert.IsChecked.Value)
                    {
                        _options.SigningMethod         = Common.Jwt.JwtGenerator.SigningMethod.X509EnterpriseSecurityKey;
                        _options.CertificateThumbprint = EnterpriseCertificateTextBox.Text;
                    }
                });

                var client = new HelseIdClient(_options);

                var result = await client.Login();

                HandleLoginResult(result);

                Dispatcher.Invoke(() =>
                {
                    if (Application.Current.MainWindow == null)
                    {
                        return;
                    }

                    Application.Current.MainWindow.Activate();
                    Application.Current.MainWindow.WindowState = WindowState.Normal;
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                MessageBox.Show(e.Message, e.StackTrace);
                throw;
            }
        }
        public async Task <TokenResponse> RsaSignIn(string clientId, string scope)
        {
            var options = new HelseIdClientOptions
            {
                Authority     = _settings.Authority,
                ClientId      = clientId,
                RedirectUri   = _settings.RedirectUri,
                Scope         = scope,
                FilterClaims  = false,
                Flow          = OidcClientOptions.AuthenticationFlow.AuthorizationCode,
                ResponseMode  = OidcClientOptions.AuthorizeResponseMode.Redirect,
                SigningMethod = Common.Jwt.JwtGenerator.SigningMethod.RsaSecurityKey
            };
            var client = new HelseIdClient(options);

            var result = await client.ClientCredentialsSignIn();

            return(result);
        }
        public async Task <string> SignIn()
        {
            var options = new HelseIdClientOptions
            {
                Authority             = _settings.Authority,
                ClientId              = _settings.ClientId,
                RedirectUri           = _settings.RedirectUri,
                Scope                 = "openid profile helseid://scopes/client/dcr https://ehelse.no/kjernejournal/nokkeladmin_api",
                FilterClaims          = false,
                Flow                  = OidcClientOptions.AuthenticationFlow.AuthorizationCode,
                ResponseMode          = OidcClientOptions.AuthorizeResponseMode.Redirect,
                CertificateThumbprint = _settings.Thumbprint,
                SigningMethod         = Common.Jwt.JwtGenerator.SigningMethod.X509EnterpriseSecurityKey
            };

            var client = new HelseIdClient(options);
            var result = await client.Login();

            return(result.AccessToken);
        }
        public async Task <string> SignIn()
        {
            var options = new HelseIdClientOptions
            {
                Authority   = _settings.Authority,
                ClientId    = _settings.ClientId,
                RedirectUri = _settings.RedirectUri,
                Scope       = new[] { StandardScopes.OpenId, StandardScopes.Profile, ClientScopes.Dcr, ClientScopes.Kj }.ToSpaceSeparatedList(),
                FilterClaims          = false,
                Flow                  = OidcClientOptions.AuthenticationFlow.AuthorizationCode,
                ResponseMode          = OidcClientOptions.AuthorizeResponseMode.Redirect,
                CertificateThumbprint = _settings.Thumbprint,
                LoadProfile           = false,
                SigningMethod         = Common.Jwt.JwtGenerator.SigningMethod.X509EnterpriseSecurityKey
            };

            var client = new HelseIdClient(options);
            var result = await client.Login();

            return(result.AccessToken);
        }
Esempio n. 6
0
        private async void TokenExchange_Click(object sender, RoutedEventArgs e)
        {
            if (UseJwtBearerClientAuthenticationRSA.IsChecked.HasValue &&
                UseJwtBearerClientAuthenticationRSA.IsChecked.Value)
            {
                _options.SigningMethod = SigningMethod.RsaSecurityKey;
            }
            if (UseJwtBearerClientAuthenticationEntCert.IsChecked.HasValue &&
                UseJwtBearerClientAuthenticationEntCert.IsChecked.Value)
            {
                _options.SigningMethod         = SigningMethod.X509EnterpriseSecurityKey;
                _options.CertificateThumbprint = EnterpriseCertificateTextBox.Text;
            }

            _options.Scope = "nhn/helseid.test.api.fullframework";
            var client   = new HelseIdClient(_options);
            var response = await client.TokenExchange(_result.AccessToken);

            _tokenExchangeResult = response;
            var tokenAsText = response.AccessToken.DecodeToken();

            ExchangeTokenClaimsTextBox.Dispatcher.Invoke(() => { ExchangeTokenClaimsTextBox.Text = tokenAsText; });
        }
Esempio n. 7
0
        public void ConfigureServices(IServiceCollection services)
        {
            var settings = Config.Setting();

            services.AddMvc();

            var opt = new HelseIdClientOptions
            {
                ClientId              = settings.ClientId,
                ClientSecret          = settings.ClientSecret,
                Authority             = settings.Authority,
                RedirectUri           = settings.RedirectUri,
                PostLogoutRedirectUri = settings.PostLogoutRedirectUri,
                SigningMethod         = (JwtGenerator.SigningMethod)Enum.Parse(typeof(JwtGenerator.SigningMethod), settings.SigningMethod),
                CertificateThumbprint = settings.CertificateThumbprint,
                Scope = settings.Scope
            };
            var client = new HelseIdClient(opt);

            services.AddSingleton <IHelseIdClient>(client);

            services.AddAuthentication(options =>
            {
                options.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = "oidc";
            })
            .AddCookie(options =>
            {
                options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
                options.Cookie.Name    = "HelseId.Clients.Core.MvcHybrid";
            })
            .AddOpenIdConnect("oidc", options =>
            {
                options.Authority            = settings.Authority;
                options.RequireHttpsMetadata = true;
                options.ClientSecret         = settings.ClientSecret;
                options.ClientId             = settings.ClientId;
                options.ResponseType         = settings.ResponseType;
                options.Scope.Clear();
                foreach (var scope in settings.Scope.FromSpaceSeparatedToList())
                {
                    options.Scope.Add(scope);
                }

                options.GetClaimsFromUserInfoEndpoint = true;
                options.SaveTokens = true;
                options.Events     = new OpenIdConnectEvents
                {
                    OnAuthorizationCodeReceived = async ctx =>
                    {
                        var result = await client.AcquireTokenByAuthorizationCodeAsync(ctx.ProtocolMessage.Code);

                        var response = new OpenIdConnectMessage
                        {
                            AccessToken  = result.AccessToken,
                            IdToken      = result.IdentityToken,
                            RefreshToken = result.RefreshToken
                        };

                        ctx.HandleCodeRedemption(response);
                    },
                    OnRedirectToIdentityProvider = redirectContext =>
                    {
                        var provider          = settings.IdentityProvider;
                        var level             = settings.OnlyLevel4 ? "Level4" : string.Empty;
                        var testPid           = settings.TestPid;
                        var testHprNumber     = settings.TestHprNumber;
                        var testSecurityLevel = settings.TestSecurityLevel;
                        var prompt            = settings.ForceLogin ? "login" : string.Empty;

                        if (!string.IsNullOrWhiteSpace(provider))
                        {
                            redirectContext.ProtocolMessage.AcrValues = $"idp:{provider} {level}";
                        }
                        else if (!string.IsNullOrWhiteSpace(level))
                        {
                            redirectContext.ProtocolMessage.AcrValues = level;
                        }

                        if (!string.IsNullOrWhiteSpace(prompt))
                        {
                            redirectContext.ProtocolMessage.Prompt = "login";
                        }

                        if (!string.IsNullOrEmpty(testPid))
                        {
                            redirectContext.ProtocolMessage.SetParameter("test_pid", testPid);
                            if (!string.IsNullOrEmpty(testSecurityLevel))
                            {
                                redirectContext.ProtocolMessage.SetParameter("test_security_level", testSecurityLevel);
                            }
                        }

                        if (!string.IsNullOrEmpty(testHprNumber))
                        {
                            redirectContext.ProtocolMessage.SetParameter("test_hpr_number", testHprNumber);
                        }

                        return(Task.CompletedTask);
                    }
                };
            });
        }
Esempio n. 8
0
        public void Configuration(IAppBuilder app)
        {
            var settings = Config.Setting();

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

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ResponseType = settings.ResponseType,
                SignInAsAuthenticationType = "Cookies",
                ClientId              = settings.ClientId,
                ClientSecret          = settings.ClientSecret,
                Authority             = settings.Authority,
                RedirectUri           = settings.RedirectUri,
                PostLogoutRedirectUri = settings.PostLogoutRedirectUri,
                Scope = settings.Scope,

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async n =>
                    {
                        var opt = new HelseIdClientOptions
                        {
                            ClientId              = n.Options.ClientId,
                            ClientSecret          = n.Options.ClientSecret,
                            Authority             = n.Options.Authority,
                            RedirectUri           = settings.RedirectUri,
                            SigningMethod         = (JwtGenerator.SigningMethod)Enum.Parse(typeof(JwtGenerator.SigningMethod), settings.SigningMethod),
                            CertificateThumbprint = settings.CertificateThumbprint
                        };

                        var client = new HelseIdClient(opt);

                        var tokenResponse = await client.AcquireTokenByAuthorizationCodeAsync(n.ProtocolMessage.Code);

                        //// create new identity
                        var id = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType);
                        id.AddClaims(n.AuthenticationTicket.Identity.Claims);

                        id.AddClaim(new Claim("access_token", tokenResponse.AccessToken));
                        id.AddClaim(new Claim("expires_at", DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToLocalTime().ToString()));
                        id.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken));
                        id.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                        id.AddClaim(new Claim("sid", n.AuthenticationTicket.Identity.FindFirst("sid").Value));

                        n.AuthenticationTicket = new AuthenticationTicket(
                            new ClaimsIdentity(id.Claims, n.AuthenticationTicket.Identity.AuthenticationType),
                            n.AuthenticationTicket.Properties);
                    },

                    RedirectToIdentityProvider = redirectContext =>
                    {
                        var provider          = settings.IdentityProvider;
                        var level             = settings.OnlyLevel4 ? "Level4" : string.Empty;
                        var testPid           = settings.TestPid;
                        var testHprNumber     = settings.TestHprNumber;
                        var testSecurityLevel = settings.TestSecurityLevel;
                        var prompt            = settings.ForceLogin ? "login" : string.Empty;

                        if (!string.IsNullOrWhiteSpace(provider))
                        {
                            redirectContext.ProtocolMessage.AcrValues = $"idp:{provider} {level}";
                        }
                        else if (!string.IsNullOrWhiteSpace(level))
                        {
                            redirectContext.ProtocolMessage.AcrValues = level;
                        }

                        if (!string.IsNullOrWhiteSpace(prompt))
                        {
                            redirectContext.ProtocolMessage.Prompt = "login";
                        }

                        if (!string.IsNullOrEmpty(testPid))
                        {
                            redirectContext.ProtocolMessage.SetParameter("test_pid", testPid);
                            if (!string.IsNullOrEmpty(testSecurityLevel))
                            {
                                redirectContext.ProtocolMessage.SetParameter("test_security_level", testSecurityLevel);
                            }
                        }

                        if (!string.IsNullOrEmpty(testHprNumber))
                        {
                            redirectContext.ProtocolMessage.SetParameter("test_hpr_number", testHprNumber);
                        }

                        return(Task.CompletedTask);
                    }
                }
            });
        }