Ejemplo n.º 1
0
 public ServicePrincipalController(
     TokenService tokenService,
     GraphService graphService,
     IOptions <AzureAdOptions> adOptions,
     IOptions <OpenIdConnectOptions> oidcOptions,
     AzureManagementService azureManagementService,
     ServicePrincipalRepository repository)
 {
     _tokenService           = tokenService;
     _graphService           = graphService;
     _adOptions              = adOptions.Value;
     _oidcOptions            = oidcOptions.Value;
     _azureManagementService = azureManagementService;
     _repository             = repository;
 }
Ejemplo n.º 2
0
        private async Task AddMicrosoftIdentityWebAppCallsWebApi_TestRedirectToIdentityProviderForSignOutEvent(
            IServiceProvider provider,
            OpenIdConnectOptions oidcOptions,
            Func <RedirectContext, Task> redirectFuncMock,
            ITokenAcquisitionInternal tokenAcquisitionMock)
        {
            var(httpContext, authScheme, authProperties) = CreateContextParameters(provider);

            await oidcOptions.Events.RedirectToIdentityProviderForSignOut(new RedirectContext(httpContext, authScheme, oidcOptions, authProperties)).ConfigureAwait(false);

            // Assert original RedirectToIdentityProviderForSignOut event and TokenAcquisition method were called
            await redirectFuncMock.ReceivedWithAnyArgs().Invoke(Arg.Any <RedirectContext>()).ConfigureAwait(false);

            await tokenAcquisitionMock.ReceivedWithAnyArgs().RemoveAccountAsync(Arg.Any <RedirectContext>()).ConfigureAwait(false);
        }
Ejemplo n.º 3
0
        private async Task AddMicrosoftIdentityWebAppCallsWebApi_TestAuthorizationCodeReceivedEvent(
            IServiceProvider provider,
            OpenIdConnectOptions oidcOptions,
            Func <AuthorizationCodeReceivedContext, Task> authCodeReceivedFuncMock,
            ITokenAcquisitionInternal tokenAcquisitionMock)
        {
            var(httpContext, authScheme, authProperties) = CreateContextParameters(provider);

            await oidcOptions.Events.AuthorizationCodeReceived(new AuthorizationCodeReceivedContext(httpContext, authScheme, oidcOptions, authProperties)).ConfigureAwait(false);

            // Assert original AuthorizationCodeReceived event and TokenAcquisition method were called
            await authCodeReceivedFuncMock.ReceivedWithAnyArgs().Invoke(Arg.Any <AuthorizationCodeReceivedContext>()).ConfigureAwait(false);

            await tokenAcquisitionMock.ReceivedWithAnyArgs().AddAccountToCacheFromAuthorizationCodeAsync(Arg.Any <AuthorizationCodeReceivedContext>(), Arg.Any <IEnumerable <string> >()).ConfigureAwait(false);
        }
Ejemplo n.º 4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseSession();

            app.UseCookieAuthentication();

            var options = new OpenIdConnectOptions
            {
                Authority       = string.Format("https://login.microsoftonline.com/tfp/{0}/{1}", Configuration["Authentication:AzureAdB2C:TenantName"], Configuration["Authentication:AzureAdB2C:SignInPolicyName"]),
                MetadataAddress = string.Format(Configuration["Authentication:AzureAdB2C:MetadataEndpointUrlTemplate"], Configuration["Authentication:AzureAdB2C:TenantName"], Configuration["Authentication:AzureAdB2C:SignInPolicyName"]),
                ClientId        = Configuration["Authentication:AzureAdB2C:ClientId"],
                ClientSecret    = Configuration["Authentication:AzureAdB2C:ClientSecret"],
                Events          = new OpenIdConnectEvents
                {
                    OnAuthorizationCodeReceived = OnAuthorizationCodeReceived,
                    OnAuthenticationFailed      = OnAuthenticationFailed
                },
                ResponseType = OpenIdConnectResponseType.CodeIdToken,
                SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme
            };

            options.Scope.Add($"{Constants.Scopes.NotesServiceAppIdUri}{Constants.Scopes.NotesServiceReadNotesScope}");
            options.Scope.Add($"{Constants.Scopes.NotesServiceAppIdUri}{Constants.Scopes.NotesServiceWriteNotesScope}");
            options.Scope.Add("offline_access");
            app.UseOpenIdConnectAuthentication(options);

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Ejemplo n.º 5
0
        public void Configure(string name, OpenIdConnectOptions options)
        {
            // Ignore OpenID Connect client handler instances that don't correspond to the instance managed by the OpenID module.
            if (!string.Equals(name, OpenIdConnectDefaults.AuthenticationScheme))
            {
                return;
            }

            var settings = GetClientSettingsAsync().GetAwaiter().GetResult();

            if (settings == null)
            {
                return;
            }

            options.Authority                     = settings.Authority.AbsoluteUri;
            options.ClientId                      = settings.ClientId;
            options.SignedOutRedirectUri          = settings.SignedOutRedirectUri ?? options.SignedOutRedirectUri;
            options.SignedOutCallbackPath         = settings.SignedOutCallbackPath ?? options.SignedOutCallbackPath;
            options.RequireHttpsMetadata          = string.Equals(settings.Authority.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
            options.GetClaimsFromUserInfoEndpoint = true;
            options.ResponseMode                  = settings.ResponseMode;
            options.ResponseType                  = settings.ResponseType;

            options.CallbackPath = settings.CallbackPath ?? options.CallbackPath;

            if (settings.Scopes != null)
            {
                foreach (var scope in settings.Scopes)
                {
                    options.Scope.Add(scope);
                }
            }

            if (settings.ResponseType.Contains(OpenIdConnectResponseType.Code) && !string.IsNullOrEmpty(settings.ClientSecret))
            {
                var protector = _dataProtectionProvider.CreateProtector(nameof(OpenIdClientConfiguration));

                try
                {
                    options.ClientSecret = protector.Unprotect(settings.ClientSecret);
                }
                catch
                {
                    _logger.LogError("The client secret could not be decrypted. It may have been encrypted using a different key.");
                }
            }
        }
Ejemplo n.º 6
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);
            };
        }
        /// <summary>
        /// Adds the <see cref="OpenIdConnectMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables OpenID Connect authentication capabilities.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
        /// <param name="options">An action delegate to configure the provided <see cref="OpenIdConnectOptions"/>.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IApplicationBuilder UseOpenIdConnectAuthentication(this IApplicationBuilder app, Action <OpenIdConnectOptions> configureOptions)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }


            var options = new OpenIdConnectOptions();

            if (configureOptions != null)
            {
                configureOptions(options);
            }
            return(app.UseOpenIdConnectAuthentication(options));
        }
Ejemplo n.º 8
0
        private static void ConfigureOpenIdConnectAuthentication(IApplicationBuilder applicationBuilder, IConfigurationSection openIdConnectAuthenticationConfigurationSection)
        {
            var tenantId = openIdConnectAuthenticationConfigurationSection["TenantId"];

            var openIdConnectAuthenticationOptions = new OpenIdConnectOptions
            {
                ClientId        = openIdConnectAuthenticationConfigurationSection["ClientId"],
                ClientSecret    = openIdConnectAuthenticationConfigurationSection["ClientSecret"],
                MetadataAddress = $"https://login.microsoftonline.com/{tenantId}/.well-known/openid-configuration",
                ResponseType    = "code id_token",
                SignInScheme    = Constants.AuthenticationSchemes.ApplicationCookie,
                SignOutScheme   = Constants.AuthenticationSchemes.ApplicationCookie
            };

            applicationBuilder.UseOpenIdConnectAuthentication(openIdConnectAuthenticationOptions);
        }
 public OpenIdConnectMiddlewareDiagnosticsTests()
 {
     _customEventWasRaised = false;
     _httpContext          = HttpContextUtilities.CreateHttpContext();
     _logger            = Substitute.For <ILogger <OpenIdConnectMiddlewareDiagnostics> >();
     _openIdDiagnostics = new OpenIdConnectMiddlewareDiagnostics(new LoggerMock <OpenIdConnectMiddlewareDiagnostics>(_logger));
     _openIdOptions     = new OpenIdConnectOptions();
     _openIdEvents      = new OpenIdConnectEvents();
     _authProperties    = new AuthenticationProperties();
     _authScheme        = new AuthenticationScheme(OpenIdConnectDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme, typeof(OpenIdConnectHandler));
     _eventHandler      = (context) =>
     {
         _customEventWasRaised = true;
         return(Task.CompletedTask);
     };
 }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

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

            var options = new OpenIdConnectOptions
            {
                AuthenticationScheme = "oidc",
                SignInScheme         = "Cookies",

                Authority            = Configuration["Authentication:Authority"],
                RequireHttpsMetadata = false,

                ClientId   = Configuration["Authentication:ClientId"],
                SaveTokens = true
            };

            options.Scope.Add("email"); // client requesting additioal claims
            options.Scope.Add("role");
            app.UseOpenIdConnectAuthentication(options);

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Ejemplo n.º 11
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseIdentity();

            List <string> issuers = new List <string> {
                Configuration["BaseUri"] + Configuration["Endpoint"],
                Configuration["BaseUri"] + ":" + Configuration["Port"] + Configuration["Endpoint"]
            };

            // Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715
            OpenIdConnectOptions config = new OpenIdConnectOptions
            {
                ClientId     = Configuration["ClientId"],
                ClientSecret = Configuration["ClientSecret"],
                Authority    = Configuration["BaseUri"] + Configuration["Endpoint"],
                ResponseType = OpenIdConnectResponseType.Code,
                GetClaimsFromUserInfoEndpoint = true,
                TokenValidationParameters     = new Microsoft.IdentityModel.Tokens.TokenValidationParameters {
                    ValidIssuers = issuers
                },
            };

            app.UseOpenIdConnectAuthentication(config);

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Ejemplo n.º 12
0
        private void SetupOpenIdSettings(OpenIdConnectOptions options)
        {
            var authorizationSection = Configuration.GetSection("Authorization");

            options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

            options.Authority            = authorizationSection.GetValue <string>("AuthorityUri");
            options.RequireHttpsMetadata = false;

            options.ClientId     = authorizationSection.GetValue <string>("ClientId");
            options.ClientSecret = authorizationSection.GetValue <string>("ClientSecret");
            options.ResponseType = "code id_token";

            options.SaveTokens = true;
            options.GetClaimsFromUserInfoEndpoint = true;
            options.ClaimActions.MapJsonKey("role", "role", "role");

            options.Scope.Add(IdentityServerConstants.StandardScopes.OfflineAccess);
            options.Scope.Add(IdentityServerConstants.StandardScopes.OpenId);
            options.Scope.Add(IdentityServerConstants.StandardScopes.Profile);
            options.Scope.Add(IdentityServerConstants.StandardScopes.Email);
            options.Scope.Add(AuthenticationConstants.ApplicationMainApi_FullAccessScope);
            options.Scope.Add(AuthenticationConstants.ApplicationMainApi_ReadOnlyScope);
            options.Scope.Add(AuthenticationConstants.RolesScope);

            options.Events = new OpenIdConnectEvents {
                OnRemoteFailure = (ctx) => {
                    ctx.Response.Redirect("/AccessDenied?schema=oidc");
                    ctx.HandleResponse();
                    return(Task.CompletedTask);
                },
                OnRedirectToIdentityProvider = ctx => {
                    var returnUrlValues = ctx.HttpContext.Request.Query["returnUrl"];
                    if (returnUrlValues.Any())
                    {
                        var returnUri = new Uri(returnUrlValues.First(), UriKind.RelativeOrAbsolute);
                        if (!returnUri.IsAbsoluteUri)
                        {
                            var request = ctx.HttpContext.Request;
                            returnUri = new UriBuilder(request.Scheme, request.Host.Host, request.Host.Port ?? -1, returnUri.OriginalString).Uri;
                        }
                        ctx.Properties.RedirectUri = returnUri.ToString();
                    }
                    return(Task.CompletedTask);
                }
            };
        }
Ejemplo n.º 13
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseDeveloperExceptionPage();
            app.UseStaticFiles();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme  = "Cookies",
                AutomaticAuthenticate = true
            });

            var oidcOptions = new OpenIdConnectOptions
            {
                AuthenticationScheme = "oidc",
                SignInScheme         = "Cookies",

                Authority             = "http://localhost:50000",
                RequireHttpsMetadata  = false,
                PostLogoutRedirectUri = "http://localhost:30000/",
                ClientId     = "mvc",
                ClientSecret = "secret",
                ResponseType = "code id_token",
                GetClaimsFromUserInfoEndpoint = true,
                SaveTokens = true
            };

            oidcOptions.Scope.Clear();
            oidcOptions.Scope.Add("openid");
            oidcOptions.Scope.Add("profile");
            oidcOptions.Scope.Add("api1");

            app.UseOpenIdConnectAuthentication(oidcOptions);


            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Ejemplo n.º 14
0
        public void Configure_NoServiceInfo_ReturnsDefaults()
        {
            // arrange
            var    opts    = new OpenIdConnectOptions();
            string authURL = "http://" + CloudFoundryDefaults.OAuthServiceUrl;

            // act
            OpenIdConnectConfigurer.Configure(null, opts);

            // assert
            Assert.Equal(CloudFoundryDefaults.DisplayName, opts.AuthenticationType);
            Assert.Equal(CloudFoundryDefaults.ClientId, opts.ClientId);
            Assert.Equal(CloudFoundryDefaults.ClientSecret, opts.ClientSecret);
            Assert.Equal(new PathString(CloudFoundryDefaults.CallbackPath), opts.CallbackPath);
            Assert.Equal(authURL + CloudFoundryDefaults.CheckTokenUri, opts.TokenInfoUrl);
            Assert.True(opts.ValidateCertificates);
        }
Ejemplo n.º 15
0
        private void ConfigureOpenIdConnect(OpenIdConnectOptions obj)
        {
            obj.SignInScheme = "Cookies";

            obj.Authority            = "https://testus.loginuat.pageuppeople.com";
            obj.RequireHttpsMetadata = false;

            obj.ClientId     = "<<your_client_id_here>>";
            obj.ClientSecret = "<<your_client_secret_here>>";

            obj.ResponseType = "code";

            obj.GetClaimsFromUserInfoEndpoint = false;
            obj.SaveTokens             = true;
            obj.AuthenticationMethod   = OpenIdConnectRedirectBehavior.RedirectGet;
            obj.BackchannelHttpHandler = new TokenMessageHandler();
        }
Ejemplo n.º 16
0
            public void Configure(string name, OpenIdConnectOptions options)
            {
                options.ClientId                  = AzureAdB2COptions.ClientId;
                options.Authority                 = AzureAdB2COptions.Authority;
                options.UseTokenLifetime          = true;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    NameClaimType = "name"
                };

                options.Events = new OpenIdConnectEvents()
                {
                    OnRedirectToIdentityProvider = OnRedirectToIdentityProvider,
                    OnRemoteFailure             = OnRemoteFailure,
                    OnAuthorizationCodeReceived = OnAuthorizationCodeReceived
                };
            }
Ejemplo n.º 17
0
        private static void ConfigureOptions(OpenIdConnectOptions options, Action <OpenIdConnectOptions> configure)
        {
            configure(options);
            options.ResponseType = Constants.ResponseType;
            options.ResponseMode = Constants.ResponseMode;
            options.CallbackPath = Constants.CallbackPath;
            options.ConfigureScpOpenIdProfileScopes();

            options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

            ((JwtSecurityTokenHandler)options.SecurityTokenValidator).MapInboundClaims = false;

            options.Events.OnAuthorizationCodeReceived  = OnAuthorizationCodeReceived;
            options.Events.OnTokenResponseReceived      = OnTokenResponseReceived;
            options.Events.OnRedirectToIdentityProvider = OnRedirectToIdentityProvider;
            options.Events.OnTokenValidated             = OnTokenValidated;
        }
Ejemplo n.º 18
0
        public static void ConfigureApp(IApplicationBuilder app, IConfigurationRoot configuration, ILogger logger)
        {
            var options = new OpenIdConnectOptions
            {
                ClientId              = configuration["AzureAD:ClientId"],
                Authority             = String.Format(configuration["AzureAd:AadInstance"], configuration["AzureAd:Tenant"]),
                ResponseType          = OpenIdConnectResponseType.IdToken,
                PostLogoutRedirectUri = configuration["AzureAd:PostLogoutRedirectUri"],
                Events = new OpenIdConnectEvents
                {
                    OnRemoteFailure  = OnAuthenticationFailed,
                    OnTokenValidated = x =>
                    {
                        var token = x.SecurityToken.RawPayload;
                        logger.LogInformation(token);
                        logger.LogInformation($"Issuer : {x.SecurityToken.Issuer}");
                        logger.LogInformation($"Audiences : {x.SecurityToken.Audiences.Aggregate(new StringBuilder(), (b,i) => b.Append(i).Append(""))}");
                        var tokenClaim = new Claim("token", token);

                        var identity = x.Ticket.Principal.Identity;

                        var claimIdentity = new ClaimsIdentity(
                            identity.AuthenticationType,
                            "name",
                            "role");

                        claimIdentity.AddClaim(tokenClaim);
                        claimIdentity.AddClaims(x.Ticket.Principal.Claims);

                        var princiapl = new ClaimsPrincipal(claimIdentity);

                        x.Ticket = new AuthenticationTicket(
                            princiapl,
                            x.Ticket.Properties,
                            x.Ticket.AuthenticationScheme);

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

            options.TokenValidationParameters.ValidateIssuer = false;

            app.UseOpenIdConnectAuthentication(options);
        }
Ejemplo n.º 19
0
 public static ClientOptions CreateClientOptionsConfigData(OpenIdConnectOptions authOption, NavigationManager navigationManager)
 {
     return(new ClientOptions
     {
         authority = authOption.Authority,
         client_id = authOption.ClientId,
         client_secret = authOption.ClientSecret,
         redirect_uri = navigationManager.GetAbsoluteUri(authOption.SignedInCallbackUri),
         silent_redirect_uri = navigationManager.GetAbsoluteUri(authOption.SilentRedirectUri),
         response_type = authOption.ResponseType,
         scope = string.Join(" ", authOption.Scopes.Distinct()),
         post_logout_redirect_uri = navigationManager.GetAbsoluteUri(authOption.SignedOutRedirectUri),
         popup_redirect_uri = navigationManager.GetAbsoluteUri(authOption.PopupSignInRedirectUri),
         popup_post_logout_redirect_uri = navigationManager.GetAbsoluteUri(authOption.PopupSignOutRedirectUri),
         loadUserInfo = authOption.LoadUserInfo,
         automaticSilentRenew = authOption.AutomaticSilentRenew,
         revokeAccessTokenOnSignout = authOption.RevokeAccessTokenOnSignout,
         filterProtocolClaims = authOption.FilterProtocolClaims,
         popupWindowFeatures = authOption.PopupWindowFeatures,
         clockSkew = authOption.ClockSkew,
         popupWindowTarget = authOption.PopupWindowTarget,
         silentRequestTimeout = authOption.SilentRequestTimeout,
         accessTokenExpiringNotificationTime = authOption.AccessTokenExpiringNotificationTime,
         monitorSession = authOption.MonitorSession,
         checkSessionInterval = authOption.CheckSessionInterval,
         includeIdTokenInSilentRenew = authOption.IncludeIdTokenInSilentRenew,
         staleStateAge = authOption.StaleStateAge,
         extraQueryParams = authOption.ExtraQueryParams,
         extraTokenParams = authOption.ExtraTokenParams,
         endSessionEndpoint = navigationManager.GetAbsoluteUri(authOption.EndSessionEndpoint),
         doNothingUri = navigationManager.GetAbsoluteUri(authOption.DoNothingUri),
         metadata = authOption.Metadata == null ? null : new ClientOidcMetadata
         {
             issuer = authOption.Metadata.Issuer,
             authorization_endpoint = authOption.Metadata.AuthorizationEndpoint,
             userinfo_endpoint = authOption.Metadata.UserinfoEndpoint,
             token_endpoint = authOption.Metadata.TokenEndpoint,
             check_session_iframe = authOption.Metadata.CheckSessionIframe,
             end_session_endpoint = authOption.Metadata.EndSessionEndpoint,
             revocation_endpoint = authOption.Metadata.RevocationEndpoint,
             jwks_uri = authOption.Metadata.JwksUri,
         },
         signingKeys = authOption.SigningKeys,
     });
 }
        public static IApplicationBuilder UseAuthentication(this IApplicationBuilder app)
        {
            var settings = app.ApplicationServices.GetService <IOptions <Settings> >();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme  = "cookies",
                AutomaticAuthenticate = true,
                ExpireTimeSpan        = TimeSpan.FromMinutes(60)
            });

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            var oidcOptions = new OpenIdConnectOptions
            {
                AuthenticationScheme = "oidc",
                SignInScheme         = "cookies",

                Authority             = settings.Value.Authentication.Authority,
                RequireHttpsMetadata  = settings.Value.Authentication.RequireHttpsMetadata,
                PostLogoutRedirectUri = settings.Value.Authentication.PostLogoutRedirectUri,
                ClientId     = "mvc",
                ResponseType = "id_token",
                SaveTokens   = true,

                TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    NameClaimType = JwtClaimTypes.Name,
                    RoleClaimType = JwtClaimTypes.Role,
                }
            };

            oidcOptions.Scope.Clear();
            oidcOptions.Scope.Add("openid");
            oidcOptions.Scope.Add("profile");
            oidcOptions.Scope.Add(Scopes.WebApplication);

            app.UseOpenIdConnectAuthentication(oidcOptions);
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedHost | ForwardedHeaders.XForwardedProto
            });

            return(app);
        }
Ejemplo n.º 21
0
        public void Configure_WithServiceInfo_ReturnsExpected()
        {
            // arrange
            string         authURL = "http://domain";
            var            opts    = new OpenIdConnectOptions();
            SsoServiceInfo info    = new SsoServiceInfo("foobar", "clientId", "secret", "http://domain");

            // act
            OpenIdConnectConfigurer.Configure(info, opts);

            // assert
            Assert.Equal(CloudFoundryDefaults.DisplayName, opts.AuthenticationType);
            Assert.Equal("clientId", opts.ClientId);
            Assert.Equal("secret", opts.ClientSecret);
            Assert.Equal(new PathString(CloudFoundryDefaults.CallbackPath), opts.CallbackPath);
            Assert.Equal(authURL + CloudFoundryDefaults.CheckTokenUri, opts.TokenInfoUrl);
            Assert.True(opts.ValidateCertificates);
        }
Ejemplo n.º 22
0
 public BlazorAuthenticationStateProvider(
     IJSRuntime jsRuntime,
     NavigationManager navigationManager,
     ClientOptions clientOptions,
     IClaimsParser <TUser> claimsParser,
     AuthenticationEventHandler authenticationEventHandler,
     HttpClient httpClient,
     OpenIdConnectOptions openIdConnectOptions,
     IServiceProvider serviceProvider)
 {
     _jsRuntime                  = jsRuntime;
     _navigationManager          = navigationManager;
     _clientOptions              = clientOptions;
     _claimsParser               = claimsParser;
     _authenticationEventHandler = authenticationEventHandler;
     _openIdConnectOptions       = openIdConnectOptions;
     _serviceProvider            = serviceProvider;
 }
Ejemplo n.º 23
0
        public static OpenIdConnectOptions GetOpenIdOptionConfigurations(OpenIdConnectOptions options)
        {
            options.Authority = "http://localhost:5001";

            options.ClientId = "mvc";

            options.RequireHttpsMetadata = false;
            options.ResponseType         = "id_token";

            options.Scope.Add(IdentityServerConstants.StandardScopes.OpenId);
            options.Scope.Add(IdentityServerConstants.StandardScopes.Profile);
            options.Scope.Add(IdentityServerConstants.StandardScopes.Email);

            options.SaveTokens   = true;
            options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

            return(options);
        }
        public void Configure_NoServiceInfo_ReturnsExpected()
        {
            var oidcOptions = new OpenIdConnectOptions();

            CloudFoundryOpenIdConnectConfigurer.Configure(null, oidcOptions, new CloudFoundryOpenIdConnectOptions()
            {
                ValidateCertificates = false
            });

            Assert.Equal(CloudFoundryDefaults.AuthenticationScheme, oidcOptions.ClaimsIssuer);
            Assert.Equal(CloudFoundryDefaults.ClientId, oidcOptions.ClientId);
            Assert.Equal(CloudFoundryDefaults.ClientSecret, oidcOptions.ClientSecret);
            Assert.Equal(new PathString(CloudFoundryDefaults.CallbackPath), oidcOptions.CallbackPath);
            Assert.Equal(19, oidcOptions.ClaimActions.Count());
            Assert.Equal(CookieAuthenticationDefaults.AuthenticationScheme, oidcOptions.SignInScheme);
            Assert.False(oidcOptions.SaveTokens);
            Assert.NotNull(oidcOptions.BackchannelHttpHandler);
        }
Ejemplo n.º 25
0
        private static OpenIdConnectOptions CreateOpenIdConnectAuthOptions(IConfiguration configuration)
        {
            var options = new OpenIdConnectOptions
            {
                ClientId = configuration["Authentication:OpenId:ClientId"],
                Authority = configuration["Authentication:OpenId:Authority"],
                PostLogoutRedirectUri = configuration["App:WebSiteRootAddress"] + "Account/Logout",
                ResponseType = OpenIdConnectResponseType.IdToken
            };

            var clientSecret = configuration["Authentication:OpenId:ClientSecret"];
            if (!clientSecret.IsNullOrEmpty())
            {
                options.ClientSecret = clientSecret;
            }

            return options;
        }
        private void ConfigureOpenIdConnectOptions(OpenIdConnectOptions options, OpenIDSettings openIdSettings)
        {
            options.Authority    = $"https://{openIdSettings.Domain}";
            options.ClientId     = openIdSettings.ClientId;
            options.ClientSecret = openIdSettings.ClientSecret;

            options.ResponseType = "code";
            options.CallbackPath = new PathString("/signin-auth0");

            options.ClaimsIssuer = "Auth0";
            options.SaveTokens   = true;
            options.Events       = CreateOpenIdConnectEvents();

            options.Scope.Clear();
            options.Scope.Add("openid");
            options.Scope.Add("name");
            options.Scope.Add("email");
            options.Scope.Add("picture");
        }
        private static void SetProtocolMessageOptions(OpenIdConnectOptions options)
        {
            var fakeOpenIdRequestMessage = new FakeOpenIdConnectMessage(ExpectedAuthorizeRequest, ExpectedLogoutRequest);

            options.AutomaticChallenge = true;
            options.Events             = new OpenIdConnectEvents()
            {
                OnRedirectToAuthenticationEndpoint = (context) =>
                {
                    context.ProtocolMessage = fakeOpenIdRequestMessage;
                    return(Task.FromResult(0));
                },
                OnRedirectToEndSessionEndpoint = (context) =>
                {
                    context.ProtocolMessage = fakeOpenIdRequestMessage;
                    return(Task.FromResult(0));
                }
            };
        }
Ejemplo n.º 28
0
        private void setOpenIdConnectOptions(OpenIdConnectOptions options)
        {
            options.SignInScheme         = Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme;
            options.Authority            = "http://localhost:5000";
            options.RequireHttpsMetadata = false;

            options.ClientId     = "clientWebPortal";
            options.ClientSecret = "49C1A7E1-0C79-4A89-A3D6-A37998FB86B1";

            options.ResponseType = "code id_token";
            options.SaveTokens   = true;
            options.GetClaimsFromUserInfoEndpoint = true;

            options.Scope.Clear();
            options.Scope.Add("openid");
            options.Scope.Add("profile");
            options.Scope.Add("offline_access");
            options.Scope.Add("testApi");
        }
        public void Configure_WithServiceInfo_ReturnsExpected()
        {
            var authURL     = "https://domain";
            var oidcOptions = new OpenIdConnectOptions();
            var info        = new SsoServiceInfo("foobar", "clientId", "secret", authURL);

            CloudFoundryOpenIdConnectConfigurer.Configure(info, oidcOptions, new CloudFoundryOpenIdConnectOptions());

            Assert.Equal(CloudFoundryDefaults.AuthenticationScheme, oidcOptions.ClaimsIssuer);
            Assert.Equal(authURL, oidcOptions.Authority);
            Assert.Equal("clientId", oidcOptions.ClientId);
            Assert.Equal("secret", oidcOptions.ClientSecret);
            Assert.Equal(new PathString(CloudFoundryDefaults.CallbackPath), oidcOptions.CallbackPath);
            Assert.Null(oidcOptions.BackchannelHttpHandler);
            Assert.Equal(19, oidcOptions.ClaimActions.Count());
            Assert.Equal(CookieAuthenticationDefaults.AuthenticationScheme, oidcOptions.SignInScheme);
            Assert.False(oidcOptions.SaveTokens);
            Assert.Null(oidcOptions.BackchannelHttpHandler);
        }
Ejemplo n.º 30
0
        public void Can_CalculateFullRedirectUri_WithNonDefaults()
        {
            // arrange
            var options = new OpenIdConnectOptions
            {
                AuthDomain   = "my_oauth_server",
                CallbackPath = new PathString("/something_else")
            };
            var requestContext = OwinTestHelpers.CreateRequest("GET", string.Empty, "https", "some_server", 1234);

            // act
            var redirectUri = UriUtility.CalculateFullRedirectUri(options, requestContext.Request);

            // assert
            Assert.StartsWith(options.AuthDomain, redirectUri);
            Assert.Contains("response_type=code", redirectUri);
            Assert.Contains("scope=openid", redirectUri);
            Assert.EndsWith("redirect_uri=" + WebUtility.UrlEncode("https://some_server:1234/something_else"), redirectUri);
        }