コード例 #1
0
        /// <summary>
        /// Initializes a new <see cref="GoogleOptions"/>.
        /// </summary>
        public NortonOpenIdConnectOptions()
        {
            CallbackPath = new PathString("/signin-norton-two");
            Authority    = NortonDefaults.Development.Authority;

            ResponseType = OpenIdConnectResponseType.Code;
            GetClaimsFromUserInfoEndpoint = true;
            SaveTokens = true;

            Events = new OpenIdConnectEvents()
            {
                OnRedirectToIdentityProvider = (context) =>
                {
                    if (context.Request.Path != "/Account/ExternalLogin")
                    {
                        context.Response.Redirect("/Account/login");
                        context.HandleResponse();
                    }

                    return(Task.FromResult(0));
                }
            };
            Scope.Add("openid");
            Scope.Add("profile");
            Scope.Add("email");
        }
コード例 #2
0
        public static void Config(IApplicationBuilder app)
        {
            OpenIdConnectEvents events = null;

            app.UseOpenIdConnectAuthentication(options =>
            {
                options.AuthenticationScheme  = "Oidc";
                options.AutomaticAuthenticate = false;
                options.AutomaticChallenge    = true;
                options.SignInScheme          = "Cookies";  // Middle-ware to persist user in a cookie

                options.Authority    = Constants.Authority; // Identity Server
                options.ClientId     = Constants.ClientId;  // This application must be registered in identity server with this id
                options.ResponseType = "code id_token";
                options.GetClaimsFromUserInfoEndpoint = true;

                options.Scope.Add("offline_access"); // this scope is needed to get the refresh token
                options.Scope.Add("role");           // a demo scope that contains a claim with the same name "role"
                options.Scope.Add("tickets_api");    // this scope is needed to access the resource API

                // Used to register events later
                events = options.Events as OpenIdConnectEvents;
            });

            if (events != null)
            {
                events.OnAuthorizationCodeReceived = OnAuthorizationCodeReceived;
            }
        }
コード例 #3
0
        /// <summary>
        /// Initializes a new <see cref="NortonOpenIdConnectOptions"/>.
        /// </summary>
        public NortonOpenIdConnectOptions()
        {
            CallbackPath = new PathString("/signin-norton");
            Authority    = NortonDefaults.Development.Authority;

            ResponseType = OpenIdConnectResponseType.Code;
            GetClaimsFromUserInfoEndpoint = true;
            SaveTokens = true;

            Events = new OpenIdConnectEvents()
            {
                OnRedirectToIdentityProvider = (context) =>
                {
                    if (context.Request.Path != "/Account/ExternalLogin")
                    {
                        context.Response.Redirect("/account/login");
                        context.HandleResponse();
                    }

                    return(Task.FromResult(0));
                }
            };
            Scope.Add("openid");
            Scope.Add("profile");
            Scope.Add("email");

            ClaimActionCollectionMapExtensions.MapJsonKey(ClaimActions, ClaimTypes.NameIdentifier, "id");
            ClaimActionCollectionMapExtensions.MapJsonKey(ClaimActions, ClaimTypes.Name, "displayName");
            ClaimActionCollectionMapExtensions.MapJsonSubKey(ClaimActions, ClaimTypes.GivenName, "name", "givenName");
            ClaimActionCollectionMapExtensions.MapJsonSubKey(ClaimActions, ClaimTypes.Surname, "name", "familyName");
        }
コード例 #4
0
        /// <summary>
        /// Initializes a new <see cref="GoogleOptions"/>.
        /// </summary>
        public GoogleOpenIdConnectOptions()
        {
            CallbackPath = new PathString("/signin-google");
            Authority    = "https://accounts.google.com";

            ResponseType = OpenIdConnectResponseType.Code;
            GetClaimsFromUserInfoEndpoint = true;
            SaveTokens = true;

            Events = new OpenIdConnectEvents()
            {
                OnRedirectToIdentityProvider = (context) =>
                {
                    if (context.Request.Path != "/Account/ExternalLogin")
                    {
                        context.Response.Redirect("/account/login");
                        context.HandleResponse();
                    }

                    return(Task.FromResult(0));
                }
            };
            Scope.Add("openid");
            Scope.Add("profile");
            Scope.Add("email");

            ClaimActionCollectionMapExtensions.MapJsonKey(ClaimActions, ClaimTypes.NameIdentifier, "id");
            ClaimActionCollectionMapExtensions.MapJsonKey(ClaimActions, ClaimTypes.Name, "displayName");
            ClaimActionCollectionMapExtensions.MapJsonSubKey(ClaimActions, ClaimTypes.GivenName, "name", "givenName");
            ClaimActionCollectionMapExtensions.MapJsonSubKey(ClaimActions, ClaimTypes.Surname, "name", "familyName");
            ClaimActionCollectionMapExtensions.MapJsonKey(ClaimActions, "urn:google:profile", "url");
            ClaimActionCollectionMapExtensions.MapCustomJson(ClaimActions, ClaimTypes.Email, GoogleHelper.GetEmail);
        }
コード例 #5
0
        /// <summary>
        /// Subscribes to all the OpenIdConnect events, to help debugging, while
        /// preserving the previous handlers (which are called)
        /// </summary>
        /// <param name="events">Events to subscribe to</param>
        public static void Subscribe(OpenIdConnectEvents events)
        {
            s_onRedirectToIdentityProvider      = events.OnRedirectToIdentityProvider;
            events.OnRedirectToIdentityProvider = OnRedirectToIdentityProviderAsync;

            s_onMessageReceived      = events.OnMessageReceived;
            events.OnMessageReceived = OnMessageReceivedAsync;

            s_onAuthorizationCodeReceived      = events.OnAuthorizationCodeReceived;
            events.OnAuthorizationCodeReceived = OnAuthorizationCodeReceivedAsync;

            s_onTokenResponseReceived      = events.OnTokenResponseReceived;
            events.OnTokenResponseReceived = OnTokenResponseReceivedAsync;

            s_onTokenValidated      = events.OnTokenValidated;
            events.OnTokenValidated = OnTokenValidatedAsync;

            s_onUserInformationReceived      = events.OnUserInformationReceived;
            events.OnUserInformationReceived = OnUserInformationReceivedAsync;

            s_onAuthenticationFailed      = events.OnAuthenticationFailed;
            events.OnAuthenticationFailed = OnAuthenticationFailedAsync;

            s_onRemoteSignOut      = events.OnRemoteSignOut;
            events.OnRemoteSignOut = OnRemoteSignOutAsync;

            s_onRedirectToIdentityProviderForSignOut      = events.OnRedirectToIdentityProviderForSignOut;
            events.OnRedirectToIdentityProviderForSignOut = OnRedirectToIdentityProviderForSignOutAsync;

            s_onSignedOutCallbackRedirect      = events.OnSignedOutCallbackRedirect;
            events.OnSignedOutCallbackRedirect = OnSignedOutCallbackRedirectAsync;
        }
コード例 #6
0
        private static OpenIdConnectEvents SetupOpenIdConnectEvents()
        {
            var events = new OpenIdConnectEvents
            {
                OnTokenValidated = context =>
                {
                    var tokenJwt = context.SecurityToken;
                    if (tokenJwt != null && !string.IsNullOrEmpty(tokenJwt.RawPayload))
                    {
                        Debug.WriteLine($"---------------------------------- Token ---------------------------------------------");
                        Debug.WriteLine(tokenJwt.Payload.SerializeToJson());
                        Debug.WriteLine($"---------------------------------- Token ---------------------------------------------");

                        var payload = JsonSerializer.Deserialize <TokenPayload>(tokenJwt.Payload.SerializeToJson());
                        context.Principal.AddIdentities(FillToken(payload));
                    }
                    return(Task.CompletedTask);
                },
                OnAuthenticationFailed = context =>
                {
                    return(Task.CompletedTask);
                },
                OnAccessDenied = context =>
                {
                    return(Task.CompletedTask);
                },
                OnRemoteFailure = context =>
                {
                    return(Task.CompletedTask);
                }
            };

            return(events);
        }
コード例 #7
0
        public void SetOpenIdConnectsOptionsCorrectly(bool getClaimsFromUserInfoEndpoint)
        {
            var mockTokenValidatedEvent   = Substitute.For <Func <TokenValidatedContext, Task> >();
            var mockUserInfoReceivedEvent = Substitute.For <Func <UserInformationReceivedContext, Task> >();

            var oktaMvcOptions = new OktaMvcOptions
            {
                PostLogoutRedirectUri = "http://foo.postlogout.com",
                AuthorizationServerId = "bar",
                ClientId     = "foo",
                ClientSecret = "baz",
                OktaDomain   = "http://myoktadomain.com",
                GetClaimsFromUserInfoEndpoint = getClaimsFromUserInfoEndpoint,
                CallbackPath = "/somecallbackpath",
                Scope        = new List <string> {
                    "openid", "profile", "email"
                },
                OnTokenValidated          = mockTokenValidatedEvent,
                OnUserInformationReceived = mockUserInfoReceivedEvent,
            };

            var events = new OpenIdConnectEvents()
            {
                OnRedirectToIdentityProvider = null
            };

            var oidcOptions = new OpenIdConnectOptions();

            OpenIdConnectOptionsHelper.ConfigureOpenIdConnectOptions(oktaMvcOptions, events, oidcOptions);

            oidcOptions.ClientId.Should().Be(oktaMvcOptions.ClientId);
            oidcOptions.ClientSecret.Should().Be(oktaMvcOptions.ClientSecret);
            oidcOptions.SignedOutRedirectUri.Should().Be(oktaMvcOptions.PostLogoutRedirectUri);
            oidcOptions.GetClaimsFromUserInfoEndpoint.Should().Be(oktaMvcOptions.GetClaimsFromUserInfoEndpoint);
            oidcOptions.CallbackPath.Value.Should().Be(oktaMvcOptions.CallbackPath);

            var issuer = UrlHelper.CreateIssuerUrl(oktaMvcOptions.OktaDomain, oktaMvcOptions.AuthorizationServerId);

            oidcOptions.Authority.Should().Be(issuer);

            oidcOptions.Scope.ToList().Should().BeEquivalentTo(oktaMvcOptions.Scope);
            oidcOptions.CallbackPath.Value.Should().Be(oktaMvcOptions.CallbackPath);
            oidcOptions.Events.OnRedirectToIdentityProvider.Should().BeNull();

            // Check the event was call once with a null parameter
            oidcOptions.Events.OnTokenValidated(null);
            mockTokenValidatedEvent.Received(1).Invoke(null);

            // UserInfo event is mapped only when GetClaimsFromUserInfoEndpoint = true
            if (oidcOptions.GetClaimsFromUserInfoEndpoint)
            {
                // Check the event was call once with a null parameter
                oidcOptions.Events.OnUserInformationReceived(null);
                mockUserInfoReceivedEvent.Received(1).Invoke(null);
            }
        }
コード例 #8
0
 /// <summary>
 /// Initializes a new <see cref="OpenIdConnectOptions"/>
 /// </summary>
 /// <remarks>
 /// Defaults:
 /// <para>AddNonceToRequest: true.</para>
 /// <para>BackchannelTimeout: 1 minute.</para>
 /// <para>Caption: <see cref="OpenIdConnectDefaults.Caption"/>.</para>
 /// <para>ProtocolValidator: new <see cref="OpenIdConnectProtocolValidator"/>.</para>
 /// <para>RefreshOnIssuerKeyNotFound: true</para>
 /// <para>ResponseType: <see cref="OpenIdConnectResponseTypes.CodeIdToken"/></para>
 /// <para>Scope: <see cref="OpenIdConnectScopes.OpenIdProfile"/>.</para>
 /// <para>TokenValidationParameters: new <see cref="TokenValidationParameters"/> with AuthenticationScheme = authenticationScheme.</para>
 /// <para>UseTokenLifetime: false.</para>
 /// </remarks>
 /// <param name="authenticationScheme"> will be used to when creating the <see cref="System.Security.Claims.ClaimsIdentity"/> for the AuthenticationScheme property.</param>
 public OpenIdConnectOptions(string authenticationScheme)
 {
     AuthenticationScheme = authenticationScheme;
     AutomaticChallenge   = true;
     DisplayName          = OpenIdConnectDefaults.Caption;
     CallbackPath         = new PathString("/signin-oidc");
     Events = new OpenIdConnectEvents();
     Scope.Add("openid");
     Scope.Add("profile");
 }
コード例 #9
0
        private static AuthenticationBuilder AddCodeFlow(AuthenticationBuilder builder, OktaMvcOptions options)
        {
            var events = new OpenIdConnectEvents
            {
                OnRedirectToIdentityProvider = BeforeRedirectToIdentityProviderAsync,
            };

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            builder.AddOpenIdConnect(oidcOptions => OpenIdConnectOptionsHelper.ConfigureOpenIdConnectOptions(options, events, oidcOptions));

            return(builder);
        }
コード例 #10
0
 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);
     };
 }
コード例 #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.AddDebug();

            app.UseIISPlatformHandler();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme = "Cookies", // We can have more than one authentication "system", we need a name to distinguish them

                AutomaticAuthenticate = true,     // Way in - IF true, Convert cookie into identity object
                AutomaticChallenge    = false,    // Way out - IF true, Redirect to challenge URL
            });

            OpenIdConnectEvents events = null;

            app.UseOpenIdConnectAuthentication(options =>
            {
                options.AuthenticationScheme  = "Oidc";
                options.AutomaticAuthenticate = false;
                options.AutomaticChallenge    = true;
                options.SignInScheme          = "Cookies";  // Middle-ware to persist user in a cookie

                options.Authority    = Constants.Authority; // Identity Server
                options.ClientId     = Constants.ClientId;  // This application must be registered in identity server with this id
                options.ResponseType = "code id_token";
                options.GetClaimsFromUserInfoEndpoint = true;

                options.Scope.Add("offline_access"); // this scope is needed to get the refresh token
                options.Scope.Add("role");

                // Used to register events later
                events = options.Events as OpenIdConnectEvents;
            });

            if (events != null)
            {
                events.OnAuthorizationCodeReceived = OnAuthorizationCodeReceived;
            }

            app.UseDeveloperExceptionPage();
            app.UseMvc();

            app.Run(async context =>
            {
                await context.Response.WriteAsync("Path not found: " + context.Request.Path);
            });
        }
コード例 #12
0
    /// <summary>
    /// Initializes a new <see cref="OpenIdConnectOptions"/>
    /// </summary>
    /// <remarks>
    /// Defaults:
    /// <para>AddNonceToRequest: true.</para>
    /// <para>BackchannelTimeout: 1 minute.</para>
    /// <para>ProtocolValidator: new <see cref="OpenIdConnectProtocolValidator"/>.</para>
    /// <para>RefreshOnIssuerKeyNotFound: true</para>
    /// <para>ResponseType: <see cref="OpenIdConnectResponseType.IdToken"/></para>
    /// <para>Scope: <see cref="OpenIdConnectScope.OpenIdProfile"/>.</para>
    /// <para>TokenValidationParameters: new <see cref="TokenValidationParameters"/> with AuthenticationScheme = authenticationScheme.</para>
    /// <para>UseTokenLifetime: false.</para>
    /// </remarks>
    public OpenIdConnectOptions()
    {
        CallbackPath           = new PathString("/signin-oidc");
        SignedOutCallbackPath  = new PathString("/signout-callback-oidc");
        RemoteSignOutPath      = new PathString("/signout-oidc");
        SecurityTokenValidator = _defaultHandler;

        Events = new OpenIdConnectEvents();
        Scope.Add("openid");
        Scope.Add("profile");

        ClaimActions.DeleteClaim("nonce");
        ClaimActions.DeleteClaim("aud");
        ClaimActions.DeleteClaim("azp");
        ClaimActions.DeleteClaim("acr");
        ClaimActions.DeleteClaim("iss");
        ClaimActions.DeleteClaim("iat");
        ClaimActions.DeleteClaim("nbf");
        ClaimActions.DeleteClaim("exp");
        ClaimActions.DeleteClaim("at_hash");
        ClaimActions.DeleteClaim("c_hash");
        ClaimActions.DeleteClaim("ipaddr");
        ClaimActions.DeleteClaim("platf");
        ClaimActions.DeleteClaim("ver");

        // http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
        ClaimActions.MapUniqueJsonKey("sub", "sub");
        ClaimActions.MapUniqueJsonKey("name", "name");
        ClaimActions.MapUniqueJsonKey("given_name", "given_name");
        ClaimActions.MapUniqueJsonKey("family_name", "family_name");
        ClaimActions.MapUniqueJsonKey("profile", "profile");
        ClaimActions.MapUniqueJsonKey("email", "email");

        _nonceCookieBuilder = new OpenIdConnectNonceCookieBuilder(this)
        {
            Name         = OpenIdConnectDefaults.CookieNoncePrefix,
            HttpOnly     = true,
            SameSite     = SameSiteMode.None,
            SecurePolicy = CookieSecurePolicy.SameAsRequest,
            IsEssential  = true,
        };
    }
コード例 #13
0
        private static AuthenticationBuilder AddCodeFlow(AuthenticationBuilder builder, OktaMvcOptions options)
        {
            var events = new OpenIdConnectEvents
            {
                OnRedirectToIdentityProvider = BeforeRedirectToIdentityProviderAsync,
            };

            if (options.AuthenticationTicketExpiryInMinutes.HasValue)
            {
                events.OnTicketReceived = async(context) =>
                {
                    context.Properties.ExpiresUtc = DateTime.UtcNow.AddMinutes(options.AuthenticationTicketExpiryInMinutes.Value);
                };
            }

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            builder.AddOpenIdConnect(oidcOptions => OpenIdConnectOptionsHelper.ConfigureOpenIdConnectOptions(options, events, oidcOptions));

            return(builder);
        }
コード例 #14
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
#if (IndividualAuth)
                app.UseDatabaseErrorPage();
#endif
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

#if (IndividualAuth)
            app.UseIdentity();

            // Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715

#elseif (OrganizationalAuth)
            app.UseCookieAuthentication();

            app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
            {
                ClientId = Configuration["Authentication:AzureAd:ClientId"],
    #if (OrgReadAccess)
                ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"],
    #endif
    #if (MultiOrgAuth)
                Authority = Configuration["Authentication:AzureAd:AADInstance"] + "Common",
    #elseif (SingleOrgAuth)
                Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"],
    #endif
#endif
#if (MultiOrgAuth)
                CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"],
    #if (OrgReadAccess)
                ResponseType = OpenIdConnectResponseType.CodeIdToken,
    #endif

                TokenValidationParameters = new TokenValidationParameters
                {
                    // Instead of using the default validation (validating against a single issuer value, as we do in line of business apps),
                    // we inject our own multitenant validation logic
                    ValidateIssuer = false,

                    // If the app is meant to be accessed by entire organizations, add your issuer validation logic here.
                    //IssuerValidator = (issuer, securityToken, validationParameters) => {
                    //    if (myIssuerValidationLogic(issuer)) return issuer;
                    //}
                },
                Events = new OpenIdConnectEvents
                {
                    OnTicketReceived = (context) =>
                    {
                        // If your authentication logic is based on users then add your logic here
                        return Task.FromResult(0);
                    },
                    OnAuthenticationFailed = (context) =>
                    {
                        context.Response.Redirect("/Home/Error");
                        context.HandleResponse(); // Suppress the exception
                        return Task.FromResult(0);
                    },
                    // If your application needs to do authenticate single users, add your user validation below.
                    //OnTokenValidated = (context) =>
                    //{
                    //    return myUserValidationLogic(context.Ticket.Principal);
                    //}
                }
#elseif (SingleOrgAuth)
    #if (OrgReadAccess)
                CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"],
                ResponseType = OpenIdConnectResponseType.CodeIdToken
    #else
                CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"]
    #endif
#endif
#if (OrganizationalAuth)
            });
コード例 #15
0
        /// <summary>
        /// Configure an OpenIdConnectOptions object based on user's configuration.
        /// </summary>
        /// <param name="oktaMvcOptions">The <see cref="OktaMvcOptions"/> options.</param>
        /// <param name="events">The OpenIdConnect events.</param>
        /// <param name="oidcOptions">The OpenIdConnectOptions to configure.</param>
        public static void ConfigureOpenIdConnectOptions(OktaMvcOptions oktaMvcOptions, OpenIdConnectEvents events, OpenIdConnectOptions oidcOptions)
        {
            var issuer = UrlHelper.CreateIssuerUrl(oktaMvcOptions.OktaDomain, oktaMvcOptions.AuthorizationServerId);

            oidcOptions.ClientId                      = oktaMvcOptions.ClientId;
            oidcOptions.ClientSecret                  = oktaMvcOptions.ClientSecret;
            oidcOptions.Authority                     = issuer;
            oidcOptions.CallbackPath                  = new PathString(oktaMvcOptions.CallbackPath);
            oidcOptions.SignedOutCallbackPath         = new PathString(OktaDefaults.SignOutCallbackPath);
            oidcOptions.SignedOutRedirectUri          = oktaMvcOptions.PostLogoutRedirectUri;
            oidcOptions.ResponseType                  = OpenIdConnectResponseType.Code;
            oidcOptions.GetClaimsFromUserInfoEndpoint = oktaMvcOptions.GetClaimsFromUserInfoEndpoint;
            oidcOptions.SecurityTokenValidator        = new StrictSecurityTokenValidator();
            oidcOptions.SaveTokens                    = true;
            oidcOptions.UseTokenLifetime              = false;
            oidcOptions.BackchannelHttpHandler        = new UserAgentHandler(
                "okta-aspnetcore",
                typeof(OktaAuthenticationOptionsExtensions).Assembly.GetName().Version);

            var hasDefinedScopes = oktaMvcOptions.Scope?.Any() ?? false;

            if (hasDefinedScopes)
            {
                oidcOptions.Scope.Clear();
                foreach (var scope in oktaMvcOptions.Scope)
                {
                    oidcOptions.Scope.Add(scope);
                }
            }

            oidcOptions.TokenValidationParameters = new DefaultTokenValidationParameters(oktaMvcOptions, issuer)
            {
                ValidAudience = oktaMvcOptions.ClientId,
                NameClaimType = "name",
            };

            oidcOptions.Events.OnRedirectToIdentityProvider = events.OnRedirectToIdentityProvider;

            if (oktaMvcOptions.OnTokenValidated != null)
            {
                oidcOptions.Events.OnTokenValidated = oktaMvcOptions.OnTokenValidated;
            }

            if (oktaMvcOptions.GetClaimsFromUserInfoEndpoint && oktaMvcOptions.OnUserInformationReceived != null)
            {
                oidcOptions.Events.OnUserInformationReceived = oktaMvcOptions.OnUserInformationReceived;
            }

            if (oktaMvcOptions.GetClaimsFromUserInfoEndpoint)
            {
                oidcOptions.ClaimActions.Add(new MapAllClaimsAction());
            }
        }
コード例 #16
0
        public OpenIDAuthentication(string authenticationScheme, object config, ILoggerFactory logger)
        {
            _logger = logger.CreateLogger("Authentication(" + authenticationScheme + ")");
            _authenticationScheme = authenticationScheme;
            _config = config as Dictionary <string, object>;
            if (Object.ReferenceEquals(_config, null))
            {
                throw new System.ArgumentException(String.Format("Authentication {0}, there is no valid configuration object {1}", authenticationScheme, config));
            }
            if (_config.ContainsKey("UseAadGraph") &&
                String.Compare(_config["UseAadGraph"] as string, "true", true) == 0)
            {
                _bUseAadGraph = true;
            }
            else
            {
                _bUseAadGraph = false;
            }
            if (_config.ContainsKey("UseToken") &&
                String.Compare(_config["UseToken"] as string, "true", true) == 0)
            {
                _bUseToken = true;
            }
            else
            {
                _bUseToken = false;
            }
            if (_config.ContainsKey("UseIdToken") &&
                String.Compare(_config["UseIdToken"] as string, "true", true) == 0)
            {
                _bUseIdToken = true;
            }
            else
            {
                _bUseIdToken = false;
            }


            if (_config.ContainsKey("DisplayName"))
            {
                _displayName = _config["DisplayName"] as string;
            }
            if (_config.ContainsKey("ClientId"))
            {
                _clientId = _config["ClientId"] as string;
            }
            if (_bUseAadGraph && String.IsNullOrEmpty(_clientId))
            {
                throw new System.ArgumentException(String.Format("Authentication {0}, there is clientId"));
            }
            if (_config.ContainsKey("ClientSecret"))
            {
                _clientSecret = _config["ClientSecret"] as string;
            }
            if (_bUseAadGraph && String.IsNullOrEmpty(_clientSecret))
            {
                throw new System.ArgumentException(String.Format("Authentication {0}, there is ClientSecret"));
            }
            if (_config.ContainsKey("AuthorityFormat"))
            {
                _authorityFormat = _config["AuthorityFormat"] as string;
            }
            if (String.IsNullOrEmpty(_authorityFormat))
            {
                throw new System.ArgumentException(String.Format("Authentication {0}, mendatory configuration AuthorityFormat is missing."));
            }
            if (_config.ContainsKey("Tenant"))
            {
                _tenant = _config["Tenant"] as string;
            }
            if (_bUseAadGraph && String.IsNullOrEmpty(_tenant))
            {
                throw new System.ArgumentException(String.Format("Authentication {0}, mendatory configuration Tenant is missing."));
            }
            if (_config.ContainsKey("AzureResourceURL"))
            {
                _AadResourceURL = _config["AzureResourceURL"] as string;
            }
            if (_config.ContainsKey("Scope"))
            {
                _scope = _config["Scope"] as string;
            }
            if (_config.ContainsKey("RedirectUri"))
            {
                _redirectURL = _config["RedirectUri"] as string;
            }
            if (_config.ContainsKey("GraphBaseEndpoint"))
            {
                _graphBasePoint = _config["GraphBaseEndpoint"] as string;
            }
            if (_bUseAadGraph && String.IsNullOrEmpty(_graphBasePoint))
            {
                throw new System.ArgumentException(String.Format("Authentication {0}, need GraphBaseEndpoint."));
            }
            if (_config.ContainsKey("GraphApiVersion"))
            {
                _graphApiVersion = _config["GraphApiVersion"] as string;
            }
            if (_bUseAadGraph && String.IsNullOrEmpty(_graphApiVersion))
            {
                throw new System.ArgumentException(String.Format("Authentication {0}, need GraphApiVersion."));
            }
            if (_config.ContainsKey("Domains"))
            {
                _domains = _config["Domains"] as Dictionary <string, object>;
            }

            _logger.LogInformation("Use AadGraph {0}, ClientId {1}, ClientSecret{2}, AuthorityFormat {3}, Tenant {4}, AzureResourceURL {5}, Scope {6}, RedirectURL {7}, GraphBaseEndpoint {8}, GraphApiVersion {9}",
                                   _bUseAadGraph, _clientId, _clientSecret,
                                   _authorityFormat, _tenant, _AadResourceURL, _scope, _redirectURL,
                                   _graphBasePoint, _graphApiVersion);


            AuthenticationScheme = _authenticationScheme;
            ClientId             = _clientId;
            DisplayName          = _displayName;
            CallbackPath         = new PathString("/signin-" + _authenticationScheme);
            // AutomaticChallenge = true;

            if (!String.IsNullOrEmpty(_clientSecret))
            {
                ClientSecret = _clientSecret;
            }

            if (!String.IsNullOrEmpty(_scope))
            {
                foreach (var scope in _scope.Split(new char[] { ' ' }))
                {
                    Scope.Add(scope);
                }
            }
            if (_bUseAadGraph || _bUseToken)
            {
                ResponseType = OpenIdConnectResponseType.CodeIdToken;
            }
            if (_bUseIdToken)
            {
                ResponseType = OpenIdConnectResponseType.IdToken;
            }

            Authority = String.Format(_authorityFormat, _tenant);

            PostLogoutRedirectUri         = "/";
            GetClaimsFromUserInfoEndpoint = true;

            /*
             * openIDOpt.TokenValidationParameters = new TokenValidationParameters
             * {
             *  // instead of using the default validation (validating against a single issuer value, as we do in line of business apps),
             *  // we inject our own multitenant validation logic
             *  ValidateIssuer = false
             * };*/

            var ev = new OpenIdConnectEvents();

            if (_bUseAadGraph)
            {
                ev.OnAuthorizationCodeReceived  = OnAuthorizationCodeReceived;
                ev.OnRedirectToIdentityProvider = OnRedirectToIdentityProvider;
            }
            if (_bUseAadGraph || _bUseToken || _bUseIdToken)
            {
                ev.OnTokenValidated = OnTokenValidated;
            }

            ev.OnRemoteFailure = OnAuthenticationFailed;



            Events = ev;
        }
        /// <summary>
        /// Adds services necessary for authentication using provider idams stub
        /// </summary>
        /// <param name="services"></param>
        /// <param name="cookieAuthenticationOptions"></param>
        /// <param name="events"></param>
        /// <returns></returns>
        public static IServiceCollection AddProviderIdamsStubAuthentication(this IServiceCollection services, Action <CookieAuthenticationOptions> cookieAuthenticationOptions, OpenIdConnectEvents events = null)
        {
            services.AddAuthentication(options =>
            {
                options.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme    = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddCookie(cookieAuthenticationOptions)
            .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
            {
                options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.Authority    = "https://das-at-pidams-as.azurewebsites.net/";
                options.ClientId     = "openIdConnectClient";
                options.Scope.Add("openid");
                options.Scope.Add("idams");
                options.ResponseType         = "id_token";
                options.UseTokenLifetime     = false;
                options.RequireHttpsMetadata = false;
                options.Events = events;
            });

            return(services);
        }
コード例 #18
0
 public void ConfigureEvents(OpenIdConnectEvents events)
 {
     events.OnRedirectToIdentityProviderForSignOut += OnRedirectToIdentityProviderForSignOut;
     events.OnTokenValidated += OnTokenValidated;
 }