///  <summary>
        ///  Configure ActiveDirectory sign-in
        ///  </summary>
        ///  <param name="app"></param>
        ///  <param name="tenant"></param>
        ///  <param name="clientId"></param>
        ///  <param name="postLoginRedirectUri">
        ///  The URL that will be redirected to after login is successful, example: http://mydomain.com/umbraco/;
        ///  </param>
        ///  <param name="issuerId">
        /// 
        ///  This is the "Issuer Id" for you Azure AD application. This a GUID value and can be found
        ///  in the Azure portal when viewing your configured application and clicking on 'View endpoints'
        ///  which will list all of the API endpoints. Each endpoint will contain a GUID value, this is
        ///  the Issuer Id which must be used for this value.        
        /// 
        ///  If this value is not set correctly then accounts won't be able to be detected 
        ///  for un-linking in the back office. 
        /// 
        ///  </param>
        /// <param name="caption"></param>
        /// <param name="style"></param>
        /// <param name="icon"></param>
        /// <remarks>
        ///  ActiveDirectory account documentation for ASP.Net Identity can be found:
        ///  https://github.com/AzureADSamples/WebApp-WebAPI-OpenIDConnect-DotNet
        ///  </remarks>
        public static void ConfigureBackOfficeAzureActiveDirectoryAuth(this IAppBuilder app, 
            string tenant, string clientId, string postLoginRedirectUri, Guid issuerId,
            string caption = "Active Directory", string style = "btn-microsoft", string icon = "fa-windows")
        {
            var authority = string.Format(
                CultureInfo.InvariantCulture,
                "https://login.windows.net/{0}",
                tenant);

            var adOptions = new OpenIdConnectAuthenticationOptions
            {
                SignInAsAuthenticationType = Constants.Security.BackOfficeExternalAuthenticationType,
                ClientId = clientId,
                Authority = authority
            };

            adOptions.ForUmbracoBackOffice(style, icon);
            adOptions.Caption = caption;
            //Need to set the auth tyep as the issuer path
            adOptions.AuthenticationType = string.Format(
                CultureInfo.InvariantCulture,
                "https://sts.windows.net/{0}/",
                issuerId);
            app.UseOpenIdConnectAuthentication(adOptions);
        }
Example #2
0
        private void ConfigureAuth(IAppBuilder app)
        {
            var clientId = ConfigurationManager.AppSettings["ida:ClientID"];

            //fixed address for multitenant apps in the public cloud
            const string authority = "https://login.microsoftonline.com/common/";

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            var openIdConnectAuthenticationOptions = new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                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,
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    RedirectToIdentityProvider = context => RedirectToIdentityProvider(context),
                    // we use this notification for injecting our custom logic
                    SecurityTokenValidated = context => SecurityTokenValidated(context),
                    AuthenticationFailed = context => AuthenticationFailed(context)
                }
            };
            app.UseOpenIdConnectAuthentication(openIdConnectAuthenticationOptions);
        }
Example #3
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            OpenIdConnectAuthenticationOptions b2coptions = new OpenIdConnectAuthenticationOptions
            {
                // Standard OWIN OIDC parameters
                Authority = String.Format(aadInstance, tenant),
                ClientId = clientId,
                RedirectUri = redirectUri,
                PostLogoutRedirectUri = redirectUri,
                Notifications = new OpenIdConnectAuthenticationNotifications
                { 
                    AuthenticationFailed = AuthenticationFailed,
                },

                // Required for AAD B2C
                Scope = "openid",
                ConfigurationManager = new B2CConfigurationManager(String.Format(aadInstance + "{1}", tenant, discoverySuffix)),

                // Optional - used for displaying the user's name in the navigation bar when signed in.
                TokenValidationParameters = new TokenValidationParameters
                {  
                    NameClaimType = "name",
                },

                AuthenticationType = "OpenIdConnect-B2C",
            };

            // Required for AAD B2C
            app.Use(typeof(B2COpenIdConnectAuthenticationMiddleware), app, b2coptions);

            OpenIdConnectAuthenticationOptions b2eoptions = new OpenIdConnectAuthenticationOptions
            {
                Authority = String.Format(aadInstance, "common"),
                ClientId = clientId,
                RedirectUri = redirectUri,
                PostLogoutRedirectUri = redirectUri,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = AuthenticationFailed,
                },

                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                },

                AuthenticationType = "OpenIdConnect-B2E",
            };

            app.UseOpenIdConnectAuthentication(b2eoptions);
        }
        /// <summary>
        /// Adds the <see cref="OpenIdConnectAuthenticationMiddleware"/> into the OWIN runtime.
        /// </summary>
        /// <param name="app">The <see cref="IAppBuilder"/> passed to the configuration method</param>
        /// <param name="openIdConnectOptions">A <see cref="OpenIdConnectAuthenticationOptions"/> contains settings for obtaining identities using the OpenIdConnect protocol.</param>
        /// <returns>The updated <see cref="IAppBuilder"/></returns>
        public static IAppBuilder UseOpenIdConnectAuthentication(this IAppBuilder app, OpenIdConnectAuthenticationOptions openIdConnectOptions)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }

            if (openIdConnectOptions == null)
            {
                throw new ArgumentNullException("openIdConnectOptions");
            }

            return app.Use(typeof(OpenIdConnectAuthenticationMiddleware), app, openIdConnectOptions);
        }
Example #5
0
        public void ConfigureAuth(IAppBuilder app)
        {
            ApplicationDbContext db = new ApplicationDbContext();

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            OpenIdConnectAuthenticationOptions options = new OpenIdConnectAuthenticationOptions();
            options.ClientId = SettingsHelper.ClientId;
            options.Authority = SettingsHelper.AzureADAuthority;
            options.PostLogoutRedirectUri = SettingsHelper.LogoutAuthority;

            OpenIdConnectAuthenticationNotifications notifications = new OpenIdConnectAuthenticationNotifications();
            notifications.AuthorizationCodeReceived = (context) =>
            {
                string code = context.Code;

                AuthenticationHelper authHelper = new AuthenticationHelper();
                
                String signInUserId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthAuthority);
                AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), authHelper.GetClientAssertionCertificate(), null);

                return Task.FromResult(0);
            };

            notifications.RedirectToIdentityProvider = (context) =>
            {
                string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                context.ProtocolMessage.RedirectUri = appBaseUrl + "/";
                context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;

                return Task.FromResult(0);
            };

            notifications.AuthenticationFailed = (context) =>
            {
                context.HandleResponse();
                return Task.FromResult(0);
            };

            options.Notifications = notifications;

            app.UseOpenIdConnectAuthentication(options);
        }
        public IEnumerable<OwinMiddlewareRegistration> GetOwinMiddlewares() {
            var middlewares = new List<OwinMiddlewareRegistration>();

            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

            var openIdOptions = new OpenIdConnectAuthenticationOptions {
                ClientId = _azureClientId,
                Authority = string.Format(CultureInfo.InvariantCulture, _azureADInstance, _azureTenant),
                PostLogoutRedirectUri = _logoutRedirectUri,
                Notifications = new OpenIdConnectAuthenticationNotifications ()
            };

            var cookieOptions = new CookieAuthenticationOptions();

            var bearerAuthOptions = new WindowsAzureActiveDirectoryBearerAuthenticationOptions {
                TokenValidationParameters = new TokenValidationParameters {
                    ValidAudience = string.Format(_sslEnabled ? "https://{0}/{1}" : "http://{0}/{1}", _azureTenant, _azureAppName)
                }
            };

            if (_azureWebSiteProtectionEnabled) {
                middlewares.Add(new OwinMiddlewareRegistration {
                    Priority = "9",
                    Configure = app => { app.SetDataProtectionProvider(new MachineKeyProtectionProvider()); }
                });
            }

            middlewares.Add(new OwinMiddlewareRegistration {
                Priority = "10",
                Configure = app => {
                    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

                    app.UseCookieAuthentication(cookieOptions);

                    app.UseOpenIdConnectAuthentication(openIdOptions);

                    //This is throwing an XML DTD is prohibited error?
                    //app.UseWindowsAzureActiveDirectoryBearerAuthentication(bearerAuthOptions);
                }
            });

            return middlewares;
        }
        /// <summary>
        /// Configures the application to use Azure AD with Power BI
        /// </summary>
        /// <param name="app">The OWIN app builder</param>
        /// <param name="options">The autheentication options</param>
        /// <returns>The OWIN app build</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static IAppBuilder UsePowerBIAuthentication(this IAppBuilder app, PowerBIAuthenticationOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            ValidateOptions(options);

            var openIdAuthOptions = new OpenIdConnectAuthenticationOptions
            {
                ClientId = options.ClientId,
                ClientSecret = options.ClientSecret,
                Authority = options.Authority,
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidIssuer = options.Issuer,
                    ValidateIssuer = options.ValidateIssuer
                },
                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    AuthorizationCodeReceived = (context) =>
                    {
                        OnAuthorizationCodeReceived(context, options);
                        return Task.FromResult(0);
                    },
                    AuthenticationFailed = (context) =>
                    {
                        var redirectUri = options.ErrorRedirectUri ?? new Uri("/", UriKind.Relative);
                        context.OwinContext.Response.Redirect(redirectUri.ToString());
                        context.HandleResponse();
                        return Task.FromResult(0);
                    }
                }
            };

            app.UseOpenIdConnectAuthentication(openIdAuthOptions);
            ConfigureTokenManager();

            return app;
        }
        public static void ConfigureAuth(IAppBuilder app, OpenIdConnectAuthenticationOptions options)
        {
            if(string.IsNullOrEmpty(options.RedirectUri))
            {
                if(!string.IsNullOrEmpty(AppSettings.ReplyUri))
                {
                    options.RedirectUri = AppSettings.ReplyUri;
                }
                else
                {
                    var url = HttpContext.Current.Request.Url;
                    var port = "";
                    if ((url.Scheme == "http" && url.Port != 80) || (url.Scheme == "https" && url.Port != 443))
                    {
                        port = ":" + url.Port;
                    }

                    options.RedirectUri = string.Format("{0}://{1}{2}/", url.Scheme, url.Host, port);
                }
            }
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            if(null == options)
            {
                options = new OpenIdConnectAuthenticationOptions();
            }

            if (string.IsNullOrEmpty(options.ClientId)) options.ClientId = AppSettings.ClientId;
            if (string.IsNullOrEmpty(options.Authority)) options.Authority = AppSettings.Authority;
            if (string.IsNullOrEmpty(options.PostLogoutRedirectUri)) options.PostLogoutRedirectUri = AppSettings.PostLogoutRedirectUri;
            if (null == options.Notifications) options.Notifications = new OpenIdConnectAuthenticationNotifications();

            if (null == options.Notifications.RedirectToIdentityProvider) options.Notifications.RedirectToIdentityProvider = Startup.DefaultRedirectToIdentityProvider;

            app.UseOpenIdConnectAuthentication(options);
        }
        public static void ConfigureAuth(
            IAppBuilder app,
            [Optional] Func<AuthorizationCodeReceivedNotification, Task> authorizationCodeReceived,
            [Optional] Func<RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>, Task> redirectToIdentityProvider,
            [Optional] Func<AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>, Task> authenticationFailed
        )
        {
            var options = new OpenIdConnectAuthenticationOptions()
            {
                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    AuthorizationCodeReceived = authorizationCodeReceived,
                    RedirectToIdentityProvider = redirectToIdentityProvider,
                    AuthenticationFailed = authenticationFailed
                }
            };

            if(null == options.Notifications.AuthorizationCodeReceived)
            {
                options.Notifications.AuthorizationCodeReceived = (context) =>
                {
                    CheckConfig();

                    var code = context.Code;
                    ClientCredential credential = new ClientCredential(AppSettings.ClientId, AppSettings.ClientSecret);
                    String signInUserId = context.AuthenticationTicket.Identity.NameIdentifier();//.FindFirst(ClaimTypes.NameIdentifier).Value;

                    AuthenticationContext authContext = new AuthenticationContext(AppSettings.Authority, new AdalTokenCache(signInUserId));
                    AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, AppSettings.GraphResourceId);

                    return Task.FromResult(0);
                };
            }

            ConfigureAuth(app, options);
        }
Example #10
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            OpenIdConnectAuthenticationOptions options = new OpenIdConnectAuthenticationOptions
            {
                // These are standard OpenID Connect parameters, with values pulled from web.config
                ClientId = clientId,
                RedirectUri = redirectUri,
                PostLogoutRedirectUri = redirectUri,
                Notifications = new OpenIdConnectAuthenticationNotifications
                { 
                    AuthenticationFailed = AuthenticationFailed,
                    RedirectToIdentityProvider = OnRedirectToIdentityProvider,
                },
                Scope = "openid",
                ResponseType = "id_token",

                // The PolicyConfigurationManager takes care of getting the correct Azure AD authentication
                // endpoints from the OpenID Connect metadata endpoint.  It is included in the PolicyAuthHelpers folder.
                ConfigurationManager = new PolicyConfigurationManager(
                    String.Format(CultureInfo.InvariantCulture, aadInstance, tenant, "/v2.0", OIDCMetadataSuffix),
                    new string[] { SignUpPolicyId, SignInPolicyId, ProfilePolicyId }),

                // This piece is optional - it is used for displaying the user's name in the navigation bar.
                TokenValidationParameters = new TokenValidationParameters
                {  
                    NameClaimType = "name",
                },
            };

            app.UseOpenIdConnectAuthentication(options);
                
        }
Example #11
0
 public MyOpenIDConnectAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app,
     OpenIdConnectAuthenticationOptions options) : base(next, app, options)
 {
     _logger = app.CreateLogger<MyOpenIDConnectAuthenticationMiddleware>();
 }
Example #12
0
        private static void ConfigureAzureAdProvider(IAppBuilder app, string signInAsType)
        {
            var aad = new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType = "aad",
                Caption = "Azure AD",
                SignInAsAuthenticationType = signInAsType,
                Authority = "https://login.windows.net/xxxxxxxxxxxxxxx",
                ClientId = "cdb67f7b-0a52-450b-a555-fe01ee12abc2",
                RedirectUri = "https://secured.local:449/identityserver/core/aadcb",
                PostLogoutRedirectUri = "https://secured.local:449/spaclient",
                Scope = "openid profile email roles",
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = n =>
                    {
                        var email = GetEmailAddress(n.ProtocolMessage.IdToken);
                        if (!string.IsNullOrWhiteSpace(email))
                        {
                            var emailClaim = new Claim(Constants.ClaimTypes.Email, email);
                            n.AuthenticationTicket.Identity.AddClaim(emailClaim);
                        }

                        return Task.FromResult(0);
                    }
                }
            };

            app.UseOpenIdConnectAuthentication(aad);
        }
Example #13
0
        // We need to update these values each time we receive a new token, so the SingleSignOut
        // javascript has access to the correct values.
        public async static Task SecurityTokenValidated(SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
        {
            // Get Tenant-Specific Metadata (Authorization Endpoint), needed for making prompt=none request in RedirectToIdentityProvider
            OpenIdConnectAuthenticationOptions tenantSpecificOptions = new OpenIdConnectAuthenticationOptions();
            tenantSpecificOptions.Authority = AADInstance + notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            tenantSpecificOptions.ConfigurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(tenantSpecificOptions.Authority + "/.well-known/openid-configuration");
            OpenIdConnectConfiguration tenantSpecificConfig = await tenantSpecificOptions.ConfigurationManager.GetConfigurationAsync(notification.Request.CallCancelled);
            notification.AuthenticationTicket.Identity.AddClaim(new Claim("issEndpoint", tenantSpecificConfig.AuthorizationEndpoint, ClaimValueTypes.String, "WebApp-Distributed-SignOut-DotNet"));

            CheckSessionIFrame = notification.AuthenticationTicket.Properties.Dictionary[OpenIdConnectSessionProperties.CheckSessionIFrame];
            return;
        }
Example #14
0
 public OpenIdConnectAuthenticationPatchedMiddleware(Microsoft.Owin.OwinMiddleware next, Owin.IAppBuilder app, Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationOptions options)
     : base(next, app, options)
 {
     this._logger = Microsoft.Owin.Logging.AppBuilderLoggerExtensions.CreateLogger <OpenIdConnectAuthenticationPatchedMiddleware>(app);
 }
        private void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
        {
            string clientId = Constants.ClientId; // your client ID as configured in Azure
            string redirectUri = "https://localhost:44300/identity/signin-azuread"; // the reply URL as configured in Azure
            string postLogoutRedirectUri = "https://localhost:44300"; // an appropriate page for your project

            OpenIdConnectAuthenticationOptions options = new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType = "AzureAd",
                Caption = "Sign in with Azure AD",
                Scope = "openid email",
                ClientId = clientId,
                Authority = "https://login.windows.net/common/",
                PostLogoutRedirectUri = postLogoutRedirectUri,
                RedirectUri = redirectUri,
                AuthenticationMode = AuthenticationMode.Passive,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false
                },
                SignInAsAuthenticationType = signInAsType // this MUST come after TokenValidationParameters
            };
            app.UseOpenIdConnectAuthentication(options);
        }
Example #16
0
 public static IAppBuilder UseOpenIdConnectAuthenticationPatched(this IAppBuilder app, Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationOptions openIdConnectOptions)
 {
     if (app == null)
     {
         throw new System.ArgumentNullException("app");
     }
     if (openIdConnectOptions == null)
     {
         throw new System.ArgumentNullException("openIdConnectOptions");
     }
     System.Type type     = typeof(OpenIdConnectAuthenticationPatchedMiddleware);
     object[]    objArray = new object[] { app, openIdConnectOptions };
     return(app.Use(type, objArray));
 }
        public static IAppBuilder UseCookieAuthAgainstTokenServer(this IAppBuilder app, UseCookieAuthAgainstTokenServerOptions options)
        {
            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypeKeys.Subject;
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

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

            var openIdConnectAuthenticationOptions = new OpenIdConnectAuthenticationOptions
            {
                Authority = options.TokenServerEndpoint,
                ClientId = options.ClientId,
                ClientSecret = options.ClientSecret,
                RedirectUri = options.RedirectUriAfterLogin,
                PostLogoutRedirectUri = options.RedirectUriAfterLogout,
                ResponseType = options.ResponseType.AsString(),
                Scope = string.Join(" ", options.Scopes),
                SignInAsAuthenticationType = "Cookies",
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async notification =>
                    {
                        var claimsIdentity = notification.AuthenticationTicket.Identity;
                        var transformedIdentity = new ClaimsIdentity(
                            claimsIdentity.AuthenticationType,
                            ClaimTypeKeys.GivenName,
                            ClaimTypeKeys.Role);

                        transformedIdentity.AddClaim(new Claim("id_token", notification.ProtocolMessage.IdToken));
                        if (notification.ProtocolMessage.AccessToken != null)
                            transformedIdentity.AddClaim(new Claim("token", notification.ProtocolMessage.AccessToken));

                        var claimsOfInterest = claimsIdentity.Claims.Where(c => options.ClaimTypesOfInterest.Contains(c.Type));
                        transformedIdentity.AddClaims(claimsOfInterest);

                        notification.AuthenticationTicket = new AuthenticationTicket(
                            transformedIdentity,
                            notification.AuthenticationTicket.Properties);

                        if (options.OnTransformingValidatedIdentity != null)
                        {
                            var additionalClaims = await options.OnTransformingValidatedIdentity(claimsIdentity).ConfigureAwait(false);
                            if(additionalClaims != null && additionalClaims.Any())
                                transformedIdentity.AddClaims(additionalClaims);
                        }

                        if (options.OnLookupUserInfo != null && notification.ProtocolMessage.AccessToken != null)
                        {
                            var additionalClaims = await options.OnLookupUserInfo(notification.ProtocolMessage.AccessToken).ConfigureAwait(false);
                            if (additionalClaims != null && additionalClaims.Any())
                                transformedIdentity.AddClaims(additionalClaims);
                        }
                    },
                    RedirectToIdentityProvider = notification =>
                    {
                        if (notification.ProtocolMessage.RequestType != OpenIdConnectRequestType.LogoutRequest)
                            return Task.CompletedTask;

                        var idToken = notification.OwinContext.Authentication.User.FindFirst("id_token");
                        if (idToken != null)
                            notification.ProtocolMessage.IdTokenHint = idToken.Value;

                        return Task.CompletedTask;
                    }
                }
            };
            app.UseOpenIdConnectAuthentication(openIdConnectAuthenticationOptions);

            return app;
        }
Example #18
0
        public static  void Configuration(IAppBuilder app)
        {
            AntiForgeryConfig.UniqueClaimTypeIdentifier = Core.ClaimTypes.Subject;
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
            app.UseResourceAuthorization(
                new AuthorizationManager());

            


            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies",
                AuthenticationMode = AuthenticationMode.Active
            });
            //app.O

            app.SetDefaultSignInAsAuthenticationType("External");

            var openIDConnectOptions = new OpenIdConnectAuthenticationOptions
            {
                // ConfigurationManager = 
                Authority = LG.Owin.Security.Config.ServerSettings.Url,
                ClientId = LG.Owin.Security.Config.ClientSettings.ClientID,
                ClientSecret = "51FC860D-07D3-4296-9147-2E40AC7FF6C8".Sha256(),
                Scope = "openid profile roles all_claims",
                ResponseType = "id_token token",
                RedirectUri = LG.Owin.Security.Config.ClientSettings.ClientUrl,
                SignInAsAuthenticationType = "Cookies",
                UseTokenLifetime = false,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        var nid = new ClaimsIdentity(
                            n.AuthenticationTicket.Identity.AuthenticationType,
                            Core.ClaimTypes.GivenName, Core.ClaimTypes.Role);

                        var userInfoClient = new UserInfoClient(
                            new Uri(n.Options.Authority + "/connect/userinfo"),
                            n.ProtocolMessage.AccessToken);

                        var userInfo = await userInfoClient.GetAsync();
                        userInfo.Claims.ToList().ForEach(
                            ui => nid.AddClaim(new Claim(ui.Item1, ui.Item2)));

                        // keep the id_token for logout
                        nid.AddClaim(new Claim("id_token",
                            n.ProtocolMessage.IdToken));

                        // add access token for sample API
                        nid.AddClaim(new Claim("access_token",
                            n.ProtocolMessage.AccessToken));

                        // keep track of access token expiration
                        nid.AddClaim(new Claim("expires_at",
                            DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));

                        // add some other app specific claim
                        //nid.AddClaim(new Claim("app_specific", "some data"));
                        n.AuthenticationTicket = new AuthenticationTicket(nid, n.AuthenticationTicket.Properties);

                    },
                    RedirectToIdentityProvider = async n =>
                    {
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.AuthenticationRequest)
                        {
                            await GetWaiter();
                            var sb = new StringBuilder();
                            var custom = n.OwinContext.Get<Dictionary<string, string>>("OpenIdConnect.Parameters");
                            if (custom != null)
                            {
                                foreach (var c in custom)
                                {
                                    // ReSharper disable once UseStringInterpolation
                                    sb.Append(string.Format(" {0}={1}", c.Key, c.Value));
                                }
                            }

                            if (sb.Length > 0)
                            {
                                sb.Remove(0, 1);
                            }
                            n.ProtocolMessage.AcrValues = sb.ToString();
                        }
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");
                            if (idTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                            }
                        }
                    }
                }
            };
            app.Use(typeof(MyOpenIDConnectAuthenticationMiddleware),
                app, 
                openIDConnectOptions);
            // app.UseOpenIdConnectAuthentication(openIDConnectOptions);
        }
Example #19
0
 public GenericDiscoverCacheContainer(OpenIdConnectAuthenticationOptions options)
 {
     Options = options;
 }
Example #20
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {

            OpenIdConnectAuthenticationOptions options = new OpenIdConnectAuthenticationOptions
            {
                // These are standard OpenID Connect parameters, with values pulled from web.config
                ClientId = clientId,
                RedirectUri = redirectUri,
                PostLogoutRedirectUri = redirectUri,
                SignInAsAuthenticationType = "Cookies",
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = AuthenticationFailed,
                    RedirectToIdentityProvider = OnRedirectToIdentityProvider,
                    SecurityTokenValidated = message =>
                      {
                          IdToken = message.ProtocolMessage.IdToken;
                          var newJwt = new JwtSecurityTokenHandler().ReadToken(IdToken) as JwtSecurityToken;
                          ClaimsIdentity claimsIdentity = new ClaimsIdentity();                          
                          claimsIdentity.AddClaims(newJwt.Claims);
                          message.OwinContext.Response.Context.Authentication.AuthenticationResponseGrant = new AuthenticationResponseGrant(claimsIdentity, new AuthenticationProperties());
                          message.OwinContext.Response.Context.Authentication.User = new ClaimsPrincipal(claimsIdentity);
                     //     message.AuthenticationTicket = new AuthenticationTicket(claimsIdentity, new AuthenticationProperties() {RedirectUri = "/Home/Claims/"});
                          return Task.FromResult(newJwt);
                      }
                },
                Scope = "openid profile address",
                ResponseType = "id_token",

                // The PolicyConfigurationManager takes care of getting the correct Azure AD authentication
                // endpoints from the OpenID Connect metadata endpoint.  It is included in the PolicyAuthHelpers folder.
                // The first parameter is the metadata URL of your B2C directory
                // The second parameter is an array of the policies that your app will use.
                ConfigurationManager = new PolicyConfigurationManager(
                    String.Format(CultureInfo.InvariantCulture, aadInstance, tenant, "/v2.0", OIDCMetadataSuffix),
                    new string[] { SignUpPolicyId, SignInPolicyId, ProfilePolicyId }),

                // This piece is optional - it is used for displaying the user's name in the navigation bar.
                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                },
            };

            app.UseOpenIdConnectAuthentication(options);
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions() {AuthenticationType = "Cookie"});
        }
        public static void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
        {
            var google = new GoogleOAuth2AuthenticationOptions
            {
                AuthenticationType = "Google",
                Caption = "Google",
                SignInAsAuthenticationType = signInAsType,
                
                ClientId = "767400843187-8boio83mb57ruogr9af9ut09fkg56b27.apps.googleusercontent.com",
                ClientSecret = "5fWcBT0udKY7_b6E3gEiJlze"
            };
            app.UseGoogleAuthentication(google);

            var fb = new FacebookAuthenticationOptions
            {
                AuthenticationType = "Facebook",
                Caption = "Facebook",
                SignInAsAuthenticationType = signInAsType,
                
                AppId = "676607329068058",
                AppSecret = "9d6ab75f921942e61fb43a9b1fc25c63"
            };
            app.UseFacebookAuthentication(fb);

            var twitter = new TwitterAuthenticationOptions
            {
                AuthenticationType = "Twitter",
                Caption = "Twitter",
                SignInAsAuthenticationType = signInAsType,
                
                ConsumerKey = "N8r8w7PIepwtZZwtH066kMlmq",
                ConsumerSecret = "df15L2x6kNI50E4PYcHS0ImBQlcGIt6huET8gQN41VFpUCwNjM"
            };
            app.UseTwitterAuthentication(twitter);

            var adfs = new WsFederationAuthenticationOptions
            {
                AuthenticationType = "adfs",
                Caption = "ADFS",
                SignInAsAuthenticationType = signInAsType,

                MetadataAddress = "https://adfs.leastprivilege.vm/federationmetadata/2007-06/federationmetadata.xml",
                Wtrealm = "urn:idsrv3"
            };
            app.UseWsFederationAuthentication(adfs);

            var aad = new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType = "aad",
                Caption = "Azure AD",
                SignInAsAuthenticationType = signInAsType,

                Authority = "https://login.windows.net/4ca9cb4c-5e5f-4be9-b700-c532992a3705",
                ClientId = "65bbbda8-8b85-4c9d-81e9-1502330aacba",
                RedirectUri = "https://localhost:44333/core/aadcb"
            };

            app.UseOpenIdConnectAuthentication(aad);
        }
Example #22
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            OpenIdConnectAuthenticationOptions b2coptions = new OpenIdConnectAuthenticationOptions
            {
                // Standard OWIN OIDC parameters
                Authority = String.Format(aadInstanceB2C, tenantB2C),
                ClientId = clientIdB2C,
                RedirectUri = postLogoutRedirectUriB2C,
                PostLogoutRedirectUri = postLogoutRedirectUriB2C,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = AuthenticationFailed,
                },

                // Required for AAD B2C
                Scope = "openid",
                ConfigurationManager = new B2CConfigurationManager(
                    String.Format(CultureInfo.InvariantCulture, aadInstanceB2C + "{1}", tenantB2C, OIDCMetadataSuffix)),

                //ConfigurationManager = new PolicyConfigurationManager(AuthorityB2C,
                //    new string[] { SignUpPolicyId, SignInPolicyId/*, ProfilePolicyId*/ }),

                // Optional - used for displaying the user's name in the navigation bar when signed in.
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    NameClaimType = "name",
                },

                AuthenticationType = "B2C"
                ,
                ProtocolValidator = new OpenIdConnectProtocolValidator { RequireNonce = false }
            };

            // Required for AAD B2C
            app.Use(typeof(B2COpenIdConnectAuthenticationMiddleware), app, b2coptions);

            //            app.UseOpenIdConnectAuthentication(b2coptions);

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientIdAAD,
                    Authority = AuthorityAAD,
                    PostLogoutRedirectUri = postLogoutRedirectUriAAD,

                    //TokenValidationParameters = new TokenValidationParameters
                    //{
                    //    ValidateIssuer = false,
                    //},
                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        //
                        // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                        //
                        //AuthorizationCodeReceived = (context) =>
                        //{
                        //    var code = context.Code;

                        //    ClientCredential credential = new ClientCredential(clientId, appKey);
                        //    string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                        //    AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));
                        //    AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                        //    return Task.FromResult(0);
                        //},
                        //RedirectToIdentityProvider = (context) =>
                        //{

                        //    if (context.Request.Path.Value == "/Account/ExternalLogin" || (context.Request.Path.Value == "/Account/LogOff" && context.Request.User.Identity.IsExternalUser()))
                        //    {
                        //        // This ensures that the address used for sign in and sign out is picked up dynamically from the request
                        //        // this allows you to deploy your app (to Azure Web Sites, for example)without having to change settings
                        //        // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
                        //        string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                        //        context.ProtocolMessage.RedirectUri = appBaseUrl + "/";
                        //        context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
                        //    }
                        //    else
                        //    {
                        //        //This is to avoid being redirected to the microsoft login page when deep linking and not logged in
                        //        context.State = Microsoft.Owin.Security.Notifications.NotificationResultState.Skipped;
                        //        context.HandleResponse();
                        //    }
                        //    return Task.FromResult(0);
                        //},
                        AuthenticationFailed = context =>
                        {
                            context.HandleResponse();
                            context.Response.Redirect("/Home/Error?message=" + context.Exception.Message);
                            return Task.FromResult(0);
                        }

                    },
                    Description = new AuthenticationDescription() { Caption = "AAD" },
                    AuthenticationType = "AAD"

                });

            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
            });

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication();
        }