public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

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

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
                {
                    ClientId = "implicitclient",
                    Authority = Constants.BaseAddress,
                    RedirectUri = "http://localhost:2671/",
                    ResponseType = "id_token",
                    Scope = "openid email",

                    SignInAsAuthenticationType = "Cookies",

                    // sample how to access token on form (when adding the token response type)
                    //Notifications = new OpenIdConnectAuthenticationNotifications
                    //{
                    //    SecurityTokenValidated = async n =>
                    //        {
                    //            var token = n.ProtocolMessage.AccessToken;

                    //            if (!string.IsNullOrEmpty(token))
                    //            {
                    //                n.AuthenticationTicket.Identity.AddClaim(
                    //                    new Claim("access_token", token));
                    //            }
                    //        }
                    //}
                });
        }
Example #2
1
        public void Configuration(IAppBuilder app)
        {
            AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

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

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority = "https://localhost:44300/identity",
                ClientId = "mvc",
                RedirectUri = "http://localhost:26214/",
                Scope = "openid profile sampleApi",
                ResponseType = "id_token token",

                SignInAsAuthenticationType = "Cookies",

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        var nid = new ClaimsIdentity(
                            n.AuthenticationTicket.Identity.AuthenticationType,
                            Constants.ClaimTypes.GivenName,
                            Constants.ClaimTypes.Role);

                        // get userinfo data
                        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()));

                        n.AuthenticationTicket = new AuthenticationTicket(
                            nid,
                            n.AuthenticationTicket.Properties);
                    }
                }
            });
        }
Example #3
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = authority,
                    PostLogoutRedirectUri = postLogoutRedirectUri,
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthenticationFailed = context =>
                        {
                            context.HandleResponse();
                            context.Response.Redirect("/Error?message=" + context.Exception.Message);
                            return Task.FromResult(0);
                        },
                        MessageReceived = x =>
                        {
                            var x1 = x;
                            return Task.FromResult(0);
                        }
                    }
                });
        }
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
                {
                    Authority = "https://login.microsoftonline.com/tushartest.onmicrosoft.com/",
                    ClientId = "ba7651c2-53c2-442a-97c2-3d60ea42f403",
                    RedirectUri = "http://localhost:42023"
                });

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

            // 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();
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            ApplicationDbContext db = new ApplicationDbContext();

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = Authority,
                    PostLogoutRedirectUri = postLogoutRedirectUri,

                    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 signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                            AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                            AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                            code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                            return Task.FromResult(0);
                        }
                    }
                });
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            //Configure OpenIDConnect, register callbacks for OpenIDConnect Notifications
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = ConfigHelper.ClientId,
                    Authority = ConfigHelper.Authority,
                    PostLogoutRedirectUri = ConfigHelper.PostLogoutRedirectUri,
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthorizationCodeReceived = context =>
                        {
                            ClientCredential credential = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
                            string userObjectId = context.AuthenticationTicket.Identity.FindFirst(Globals.ObjectIdClaimType).Value;
                            AuthenticationContext authContext = new AuthenticationContext(ConfigHelper.Authority, new TokenDbCache(userObjectId));
                            AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                                context.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, ConfigHelper.GraphResourceId);

                            return Task.FromResult(0);
                        },

                        AuthenticationFailed = context =>
                        {
                            context.HandleResponse();
                            context.Response.Redirect("/Error/ShowError?signIn=true&errorMessage=" + context.Exception.Message);
                            return Task.FromResult(0);
                        }
                    }
                });
        }
    public void ConfigureAuth(IAppBuilder app) {
      app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
      app.UseCookieAuthentication(new CookieAuthenticationOptions());

      app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions {
        ClientId = SettingsHelper.ClientId,
        Authority = SettingsHelper.AzureADAuthority,
        Notifications = new OpenIdConnectAuthenticationNotifications() {
          AuthorizationCodeReceived = (context) => {
            string code = context.Code;

            ClientCredential creds = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
            string userObjectId = context.AuthenticationTicket.Identity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;

            EFADALTokenCache cache = new EFADALTokenCache(userObjectId);
            AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, cache);

            Uri redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
            AuthenticationResult authResult = authContext.AcquireTokenByAuthorizationCode(code, redirectUri, creds, SettingsHelper.AzureAdGraphResourceId);

            return Task.FromResult(0);
          },
          AuthenticationFailed = (context) => {
            context.HandleResponse();
            return Task.FromResult(0);
          }
        },
        TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters {
          ValidateIssuer = false
        }
      });
    }
Example #8
0
        public void Configuration(IAppBuilder app)
        {
            app.Map("/identity", idsrvApp =>
            {
                idsrvApp.UseIdentityServer(new IdentityServerOptions
                {
                    SiteName = "Embedded IdentityServer",
                    SigningCertificate = this.LoadCertificate(),

                    Factory = new IdentityServerServiceFactory()
                                .UseInMemoryUsers(Users.Get())
                                .UseInMemoryClients(Clients.Get())
                                .UseInMemoryScopes(StandardScopes.All)
                });
            });

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

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
                {
                    Authority = Config.authorityLink, 
                    ClientId = Config.clientId, 
                    RedirectUri = Config.host, 
                    ResponseType = "id_token", 

                    SignInAsAuthenticationType = "Cookies"
                    
                });
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, "common", "/v2.0"),
                    Scope = "openid offline_access",
                    RedirectUri = redirectUri,
                    PostLogoutRedirectUri = redirectUri,
                    TokenValidationParameters = new TokenValidationParameters
                    {
                        IssuerValidator = ProxyIssuerValidator,
                    },
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthenticationFailed = OnAuthenticationFailed,
                        AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                    }
                });
        }
Example #10
0
        public void Configuration(IAppBuilder app)
        {
            app.Map("/identity", idsrvApp => idsrvApp.UseIdentityServer(new IdentityServerOptions
            {
                SiteName = "Embedded IdentityServer",
                IssuerUri = "https://idsrv3/embedded",
                SigningCertificate = LoadCertificate(),

                Factory = InMemoryFactory.Create(
                    users: Users.Get(),
                    clients: Clients.Get(),
                    scopes: Scopes.Get())
            }));

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

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority = "https://localhost:44304/identity",

                ClientId = "mvc",
                Scope = "openid profile roles",
                RedirectUri = "https://localhost:44304/",

                SignInAsAuthenticationType = "Cookies"
            });

            app.UseResourceAuthorization(new AuthorizationManager());
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = "95dcbcfd-5a64-4efe-a5e3-f4ed2043c46c",
                Authority = "https://login.microsoftonline.com/DeveloperTenant.onmicrosoft.com",
                PostLogoutRedirectUri = "https://localhost:44300/"
            }
            );
            // If you want to connect to ADFS (from ADFS 2.x onward) instead of Azure AD:
            // 1- comment out the call to UseOpenIdConnectAuthentication
            // 2- uncomment the call to UseWsFederationAuthentication below
            // 3- assign to Wtrealm and MetadataAddress the values provisioned for your app
            // 4- go to AccountController and follow the suggestions in the comments there
            // please refer to Chapter 5 of http://amzn.to/1QS5kQK for more details.

            //app.UseWsFederationAuthentication(
            //new WsFederationAuthenticationOptions
            //{
            //    Wtrealm = "http://myapp/whatever",
            //    MetadataAddress =
            //"https://sts.contoso.com/federationmetadata/2007-06/federationmetadata.xml"
            //}

        }
Example #12
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

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

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = "implicitclient-cardeal",
                Authority = Constants.BaseAddress,
                RedirectUri = "http://localhost:57871/",
                ResponseType = "id_token token",
                Scope = "openid email write",
                SignInAsAuthenticationType = "Cookies",

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = SecurityTokenValidated
                }
            });

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
Example #13
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 #14
0
        public void Configuration(IAppBuilder app)
        {
            var _eventNotification = new NotificationService();
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            GlobalConfiguration.Configuration.UseSqlServerStorage("PaytimeAzureDbContext");

            RecurringJob.AddOrUpdate(() => _eventNotification.GenerateNotification(), Cron.Daily(_cronHour, _cronMinutes));
            //RecurringJob.AddOrUpdate(() => _eventNotification.GenerateNotification(), Cron.Daily(09, 45));

            app.UseHangfireDashboard();
            app.UseHangfireServer();

            // Authentication
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = authority,
                    PostLogoutRedirectUri = postLogoutRedirectUri,
                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters()
                    {
                        ValidateIssuer = false,
                        RoleClaimType = "roles"
                    }
                });
        }
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

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

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
                {
                    ClientId = "implicitclient",
                    Authority = Constants.BaseAddress,
                    RedirectUri = "http://localhost:2671/",
                    ResponseType = "id_token token",
                    Scope = "openid email write",

                    SignInAsAuthenticationType = "Cookies",

                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        SecurityTokenValidated = async n =>
                            {
                                var token = n.ProtocolMessage.AccessToken;

                                // persist access token in cookie
                                if (!string.IsNullOrEmpty(token))
                                {
                                    n.AuthenticationTicket.Identity.AddClaim(
                                        new Claim("access_token", token));
                                }
                            }
                    }
                });
        }
        public void ConfigureAuth(IAppBuilder app, IConfigurationProvider configProvider)
        {
            string aadClientId = configProvider.GetConfigurationSettingValue("ida.AADClientId");
            string aadInstance = configProvider.GetConfigurationSettingValue("ida.AADInstance");
            string aadTenant = configProvider.GetConfigurationSettingValue("ida.AADTenant");
            string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, aadTenant);

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = aadClientId,
                    Authority = authority,
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthenticationFailed = context =>
                        {
                            string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;

                            context.ProtocolMessage.RedirectUri = appBaseUrl + "/";
                            context.HandleResponse();
                            context.Response.Redirect(context.ProtocolMessage.RedirectUri);

                            return Task.FromResult(0);
                        }
                    }
                });
        }
Example #17
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = "cb4b16f7-304e-4195-8ac1-ee9b068dee93",
                    Authority = "https://login.windows-ppe.net/common/v2.0",
                    PostLogoutRedirectUri = "https://localhost:44327/",

                    // For MS STS, send scope=openid
                    Scope = "openid",

                    // Treat as multi-tenant, disable issuer validation.
                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters {
                        ValidateIssuer = false
                    },

                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthenticationFailed = context =>
                        {
                            context.HandleResponse();
                            context.Response.Redirect("/Error?message=" + context.Exception.Message);
                            return Task.FromResult(0);
                        }
                    }
                });
        }
Example #18
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = "mvc",
                Authority = ExpenseTrackerConstants.IdSrv,
                RedirectUri = ExpenseTrackerConstants.ExpenseTrackerClient,
                SignInAsAuthenticationType = "Cookies",

                ResponseType = "code id_token token",
                Scope = "openid profile",

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {

                    MessageReceived = async n =>
                    {
                        EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.IdToken);
                        EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.AccessToken);

                        var userInfo = await EndpointAndTokenHelper.CallUserInfoEndpoint(n.ProtocolMessage.AccessToken);

                    }

                }

                });
        }
Example #19
0
        public void ConfigAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions {});

            //[email protected]
            //Azure680628
            app.Use(async (context, next) =>
            {
                await next.Invoke();
            });

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    // Client Id of Application
                    ClientId = "24e8d712-4765-48f1-9698-9e335da6f780",

                    // The authority provides a discoverable openid service
                    //https://login.windows.net/JohnsonAzureAD.onmicrosoft.com/.well-known/openid-configuration

                    // The keys
                    //https://login.windows.net/common/discovery/keys

                    Authority = "https://login.windows.net/JohnsonAzureAD.onmicrosoft.com",
                    PostLogoutRedirectUri = "http://localhost:53509/"
                });

            app.Use(async (context, next) =>
            {
               await next.Invoke();
            });
        }
Example #20
0
        public void ConfigureAuth(IAppBuilder app)
        {
            
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            //app.UseCookieAuthentication(new CookieAuthenticationOptions {
            //    CookieManager = new Components.SystemWebCookieManager()
            //});

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = MSGraphAPISettings.ClientId,
                    Authority = MSGraphAPISettings.AADInstance + "common",
                    TokenValidationParameters = new System.IdentityModel.Tokens.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()
                    {
                        SecurityTokenValidated = (context) => 
                        {
                            return Task.FromResult(0);
                        },
                        AuthorizationCodeReceived = (context) =>
                        {
                            var code = context.Code;

                            ClientCredential credential = new ClientCredential(
                                MSGraphAPISettings.ClientId,
                                MSGraphAPISettings.ClientSecret);
                            string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(
                                ClaimTypes.NameIdentifier).Value;
                            string tenantId = context.AuthenticationTicket.Identity.FindFirst(
                                "http://schemas.microsoft.com/identity/claims/tenantid").Value;

                            AuthenticationContext authContext = new AuthenticationContext(
                                MSGraphAPISettings.AADInstance + tenantId,
                                new SessionADALCache(signedInUserID));
                            AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                                code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
                                credential, MSGraphAPISettings.MicrosoftGraphResourceId);

                            return Task.FromResult(0);
                        },
                        AuthenticationFailed = (context) =>
                        {
                            context.OwinContext.Response.Redirect("/Home/Error?message=" + context.Exception.Message);
                            context.HandleResponse(); // Suppress the exception
                            return Task.FromResult(0);
                        }
                    }
                });

        }
Example #21
0
        public void Configuration(IAppBuilder app) {
            AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            app.Map("/identity", idsrvApp => {
                idsrvApp.UseIdentityServer(new IdentityServerOptions {
                    SiteName = "Embedded IdentityServer",
                    SigningCertificate = LoadCertificate(),
                    Factory = InMemoryFactory.Create(
                        users: Users.Get(),
                        clients: Clients.Get(),
                        scopes: Scopes.Get())
                });
            });

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

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions {
                Authority = "https://localhost:44301/identity",
                ClientId = "mvc",
                Scope = "openid profile roles",
                RedirectUri = "https://localhost:44301/",
                ResponseType = "id_token",
                SignInAsAuthenticationType = "Cookies",
                UseTokenLifetime = false,
                Notifications = new OpenIdConnectAuthenticationNotifications {
                    SecurityTokenValidated = async n => {
                        var id = n.AuthenticationTicket.Identity;

                        // we want to keep first name, last name, subject and roles
                        var givenName = id.FindFirst(Constants.ClaimTypes.GivenName);
                        var familyName = id.FindFirst(Constants.ClaimTypes.FamilyName);
                        var sub = id.FindFirst(Constants.ClaimTypes.Subject);
                        var roles = id.FindAll(Constants.ClaimTypes.Role);

                        // create new identity and set name and role claim type
                        var nid = new ClaimsIdentity(
                            id.AuthenticationType,
                            Constants.ClaimTypes.GivenName,
                            Constants.ClaimTypes.Role);

                        nid.AddClaim(givenName);
                        nid.AddClaim(familyName);
                        nid.AddClaim(sub);
                        nid.AddClaims(roles);

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

                        n.AuthenticationTicket = new AuthenticationTicket(
                            nid,
                            n.AuthenticationTicket.Properties);
                    }
                }
            });
        }
        internal static void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                CookieManager = new SystemWebCookieManager()
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
            {
                Authority = OfficeSettings.Authority,
                ClientId = OfficeSettings.ClientId,

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    AuthorizationCodeReceived = async (context) =>
                    {
                        string code = context.Code;
                        ClientCredential credential = new ClientCredential(OfficeSettings.ClientId,
                                                              OfficeSettings.ClientSecret);
                        string signInUserId = context.AuthenticationTicket
                                                      .Identity
                                                      .FindFirst(ClaimTypes.NameIdentifier)
                                                      .Value;

                        AuthenticationContext ctx = new AuthenticationContext(OfficeSettings.Authority,
                                                            new ADALTokenCache(signInUserId));

                        var result = await ctx.AcquireTokenByAuthorizationCodeAsync(code,
                                                                              new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
                                                                              credential,
                                                                              OfficeSettings.GraphResourceId);

                        return;
                    },
                    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);
                    },
                    AuthenticationFailed = (context) =>
                    {
                        if (context.Exception.Message.StartsWith("OICE_20004") || context.Exception.Message.Contains("IDX10311"))
                        {
                            context.SkipToNextMiddleware();
                            return Task.FromResult(0);
                        }
                        context.HandleResponse();
                        context.Response.Redirect("/Home/Error?message=" + context.Exception.Message);
                        return Task.FromResult(0);
                    }
                }
            });
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                //Implement our own cookie manager to work around the infinite
                //redirect loop issue
                CookieManager = new SystemWebCookieManager()
            });

            string clientID = ConfigurationManager.AppSettings["ida:ClientID"];
            string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
            string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
            string clientSecret = ConfigurationManager.AppSettings["ida:AppKey"];
            string graphResourceID = ConfigurationManager.AppSettings["ida:GraphResourceID"];

            string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientID,
                    Authority = authority,

                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        // when an auth code is received...
                        AuthorizationCodeReceived = (context) =>
                        {
                            // get the OpenID Connect code passed from Azure AD on successful auth
                            string code = context.Code;

                            // create the app credentials & get reference to the user
                            ClientCredential creds = new ClientCredential(clientID, clientSecret);
                            string signInUserId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                            // use the OpenID Connect code to obtain access token & refresh token...
                            //  save those in a persistent store...
                            AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCache(signInUserId));

                            // obtain access token for the AzureAD graph
                            Uri redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
                            AuthenticationResult authResult = authContext.AcquireTokenByAuthorizationCode(code, redirectUri, creds, graphResourceID);

                            // successful auth
                            return Task.FromResult(0);
                        },
                        AuthenticationFailed = (context) =>
                        {
                            context.HandleResponse();
                            return Task.FromResult(0);
                        }
                    }

                });
        }
Example #24
0
        // 認証設定の詳細については、http://go.microsoft.com/fwlink/?LinkId=301864 を参照してください
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = authority,
                    PostLogoutRedirectUri = postLogoutRedirectUri
                });

            //// 1 要求につき 1 インスタンスのみを使用するように DB コンテキスト、ユーザー マネージャー、サインイン マネージャーを構成します。
            //app.CreatePerOwinContext(ApplicationDbContext.Create);
            //app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            //app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            //// アプリケーションが Cookie を使用して、サインインしたユーザーの情報を格納できるようにします
            //// また、サードパーティのログイン プロバイダーを使用してログインするユーザーに関する情報を、Cookie を使用して一時的に保存できるようにします
            //// サインイン Cookie の設定
            //app.UseCookieAuthentication(new CookieAuthenticationOptions
            //{
            //    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            //    LoginPath = new PathString("/Account/Login"),
            //    Provider = new CookieAuthenticationProvider
            //    {
            //        // ユーザーがログインするときにセキュリティ スタンプを検証するように設定します。
            //        // これはセキュリティ機能の 1 つであり、パスワードを変更するときやアカウントに外部ログインを追加するときに使用されます。
            //        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            //            validateInterval: TimeSpan.FromMinutes(30),
            //            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            //    }
            //});
            //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            //// 2 要素認証プロセスの中で 2 つ目の要素を確認するときにユーザー情報を一時的に保存するように設定します。
            //app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            //// 2 つ目のログイン確認要素 (電話や電子メールなど) を記憶するように設定します。
            //// このオプションをオンにすると、ログイン プロセスの中の確認の第 2 ステップは、ログインに使用されたデバイスに保存されます。
            //// これは、ログイン時の「このアカウントを記憶する」オプションに似ています。
            //app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // 次の行のコメントを解除して、サード パーティのログイン プロバイダーを使用したログインを有効にします
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

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

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");
        }
        /// <summary>
        /// Configures OpenIDConnect Authentication & Adds Custom Application Authorization Logic on User Login.
        /// </summary>
        /// <param name="app">The application represented by a <see cref="IAppBuilder"/> object.</param>
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            //Configure OpenIDConnect, register callbacks for OpenIDConnect Notifications
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = ConfigHelper.ClientId,
                    //Authority = String.Format(CultureInfo.InvariantCulture, ConfigHelper.AadInstance, ConfigHelper.Tenant), // For Single-Tenant
                    Authority = ConfigHelper.CommonAuthority, // For Multi-Tenant
                    PostLogoutRedirectUri = ConfigHelper.PostLogoutRedirectUri,

                    // Here, we've disabled issuer validation for the multi-tenant sample.  This enables users
                    // from ANY tenant to sign into the application (solely for the purposes of allowing the sample
                    // to be run out-of-the-box.  For a real multi-tenant app, reference the issuer validation in 
                    // WebApp-MultiTenant-OpenIDConnect-DotNet.  If you're running this sample as a single-tenant
                    // app, you can delete the ValidateIssuer property below.
                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                    {
                        ValidateIssuer = false, // For Multi-Tenant Only
                        RoleClaimType = "roles",
                    },

                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthorizationCodeReceived = context =>
                        {
                            // Get Access Token for User's Directory
                            string userObjectId = context.AuthenticationTicket.Identity.FindFirst(Globals.ObjectIdClaimType).Value;
                            string tenantId = context.AuthenticationTicket.Identity.FindFirst(Globals.TenantIdClaimType).Value;
                            ClientCredential credential = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
                            AuthenticationContext authContext = new AuthenticationContext(
                                String.Format(CultureInfo.InvariantCulture, ConfigHelper.AadInstance, tenantId),
                                new TokenDbCache(userObjectId));
                            AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                                context.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
                                credential, ConfigHelper.GraphResourceId);

                            return Task.FromResult(0);
                        },

                        AuthenticationFailed = context =>
                        {
                            context.HandleResponse();
                            context.Response.Redirect("/Error/ShowError?signIn=true&errorMessage=" + context.Exception.Message);
                            return Task.FromResult(0);
                        }
                    }
                });
        }
Example #26
0
        public void Configuration(IAppBuilder app)
        {
            LogProvider.SetCurrentLogProvider(new TraceSourceLogProvider());

            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
            app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.UseOpenIdConnectAuthentication(new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationOptions
            {
                AuthenticationType = "oidc",
                Authority = "https://localhost:44337/ids",
                ClientId = "idmgr_client",
                RedirectUri = "https://localhost:44337",
                ResponseType = "id_token",
                UseTokenLifetime = false,
                Scope = "openid idmgr",
                SignInAsAuthenticationType = "Cookies"
            });

            app.Map("/idm", idm =>
            {
                var factory = new IdentityManagerServiceFactory();

                var rand = new System.Random();
                var users = Users.Get(rand.Next(5000, 20000));
                var roles = Roles.Get(rand.Next(15));

                factory.Register(new Registration<ICollection<InMemoryUser>>(users));
                factory.Register(new Registration<ICollection<InMemoryRole>>(roles));
                factory.IdentityManagerService = new Registration<IIdentityManagerService, InMemoryIdentityManagerService>();

                idm.UseIdentityManager(new IdentityManagerOptions
                {
                    Factory = factory,
                    SecurityConfiguration = new HostSecurityConfiguration
                    {
                        HostAuthenticationType = "Cookies",
                        //AdditionalSignOutType = "oidc"
                    }
                });
            });

            // this configures an embedded IdentityServer to act as an external authentication provider
            // when using IdentityManager in Token security mode. normally you'd configure this elsewhere.
            app.Map("/ids", ids =>
            {
                IdSvrConfig.Configure(ids);
            });
        }
        public void ConfigOpenIdConnect(IAppBuilder app)
        {
            // this is implicit flow as response type is 'id_token'
            // no access token is returned if only id_token is asked
            // key is retrieved from http://localhost:62733/.well-known/jwks

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AuthenticationType = OpenIdConnectAuthenticationDefaults.AuthenticationType,
                SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType(),

                ClientId = Clients.Client3.Id,
                //Implicit flow does not do client authentication
                //  ClientSecret = Clients.Client3.Secret,
                RedirectUri = Clients.Client3.RedirectUrl,
                // Only ask for id_token (/or token) nothing else as an implicit client
                ResponseType = "id_token token",
                Scope = "openid email",

                // Note: setting the Authority allows the OIDC client middleware to automatically
                // retrieve the identity provider's configuration and spare you from setting
                // the different endpoints URIs or the token validation parameters explicitly.
                Authority = Paths.OpenIdConnectServerBaseAddress,

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async (n) =>
                    {
                        // Also the id token already loaded into Identity
                        // identity already populated with claims from id token
                        var token = n.ProtocolMessage.IdToken;
                        if (!string.IsNullOrEmpty(token))
                        {
                            n.AuthenticationTicket.Identity.AddClaim(
                                new Claim("id_token", token));
                        }

                        // Also the access token already loaded into Identity
                        // no refresh token issued in this case

                        var accesstoken = n.ProtocolMessage.AccessToken;
                        if (!string.IsNullOrEmpty(accesstoken))
                        {
                            n.AuthenticationTicket.Identity.AddClaim(
                                new Claim("access_token", accesstoken));
                        }

                    }
                }
            });
        }
        public void Configuration(IAppBuilder app) {
            AntiForgeryConfig.UniqueClaimTypeIdentifier = "sub";
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

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

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions {
                    ClientId = "hybridclient",
                    Authority = IdServBaseUri,
                    RedirectUri = ClientUri,
                    PostLogoutRedirectUri = ClientUri,
                    ResponseType = "code id_token token",
                    Scope = "openid profile email roles offline_access",
                    SignInAsAuthenticationType = "Cookies",
                    Notifications =
                        new OpenIdConnectAuthenticationNotifications {
                            AuthorizationCodeReceived = async n => {
                                var identity = n.AuthenticationTicket.Identity;
                                var nIdentity = new ClaimsIdentity(identity.AuthenticationType, "email", "role");

                                var userInfoClient = new UserInfoClient(
                                    new Uri(userInfoEndpoint),
                                    n.ProtocolMessage.AccessToken);

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

                                var tokenClient = new OAuth2Client(new Uri(tokenEndpoint), "hybridclient", "idsrv3test");
                                var response = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri);

                                nIdentity.AddClaim(new Claim("access_token", response.AccessToken));
                                nIdentity.AddClaim(
                                    new Claim("expires_at", DateTime.UtcNow.AddSeconds(response.ExpiresIn).ToLocalTime().ToString(CultureInfo.InvariantCulture)));
                                nIdentity.AddClaim(new Claim("refresh_token", response.RefreshToken));
                                nIdentity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

                                n.AuthenticationTicket = new AuthenticationTicket(
                                    nIdentity,
                                    n.AuthenticationTicket.Properties);
                            },
                            RedirectToIdentityProvider = async n => {
                                if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest) {
                                    var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token").Value;
                                    n.ProtocolMessage.IdTokenHint = idTokenHint;
                                }
                            }
                        }
                });
        }
Example #29
0
 public void ConfigureAuth(IAppBuilder app)
 {
     app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
     app.UseCookieAuthentication(new CookieAuthenticationOptions());
     app.UseOpenIdConnectAuthentication(
         new OpenIdConnectAuthenticationOptions
         {
             ClientId = (string)ConfigurationManager.AppSettings["ClientId"],
             //ClientId = "f9c75c65-f4cf-4bff-9c3c-630c624ae933", //Dev
             //ClientId = "f8c4b355-6a27-4d46-9e7c-698b13aeeb5b", //Release
             Authority = "https://login.windows.net/paultdhotmail.onmicrosoft.com"
         });
 }
Example #30
0
        public void Configuration(IAppBuilder app)
        {
            AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.File(@"c:\logs\sts.identityserver.txt")
                         .CreateLogger();

            IContainer container = AutofacConfig.ConfigureContainer();

            app.UseAutofacMiddleware(container);

            app.Map("/identity", coreApp =>
            {
                var factory = new IdentityServerServiceFactory()
                              .UseInMemoryClients(Clients.Get())
                              .UseInMemoryScopes(Scopes.Get());
                //.UseInMemoryUsers(Users.Get());


                factory.UserService = new Registration <IUserService, UserService>();

                var options = new IdentityServerOptions
                {
                    SiteName              = "Duy Tan Security Token Service",
                    SigningCertificate    = Certificate.Get(),
                    Factory               = factory,
                    RequireSsl            = false,
                    EnableWelcomePage     = true,
                    AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions
                    {
                        EnablePostSignOutAutoRedirect = true,
                        EnableSignOutPrompt           = true
                    },
                    EventsOptions = new EventsOptions
                    {
                        RaiseSuccessEvents     = true,
                        RaiseErrorEvents       = true,
                        RaiseFailureEvents     = true,
                        RaiseInformationEvents = true
                    }
                };

                coreApp.UseIdentityServer(options);
            });

            app.UseResourceAuthorization(new AuthorizationManager());

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority          = "http://localhost:58891/identity",
                AuthenticationType = "oidc",
                ClientId           = "mvc",
                Scope        = "openid profile roles sampleApi",
                ResponseType = "id_token token",
                RedirectUri  = "http://localhost:58891",
                // PostLogoutRedirectUri = "http://localhost:58891",
                SignInAsAuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                UseTokenLifetime           = false,

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        var nid = new ClaimsIdentity(
                            n.AuthenticationTicket.Identity.AuthenticationType,
                            Constants.ClaimTypes.GivenName,
                            Constants.ClaimTypes.Role);

                        // get userinfo data
                        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);
                    },

                    AuthenticationFailed = n => {
                        return(Task.FromResult(0));
                    },

                    RedirectToIdentityProvider = n =>
                    {
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (idTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                            }
                        }

                        return(Task.FromResult(0));
                    }
                }
            });
        }
Example #31
0
        public void ConfigureAADAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions {
            });

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                Caption   = "Microsoft Work or school account",
                ClientId  = Constants.AADClientId,
                Authority = Constants.Authority,
                TokenValidationParameters = new System.IdentityModel.Tokens.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) =>
                    {
                        // 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;
                        CookieService cookieService = new CookieService();
                        string hint = cookieService.GetCookiesOfEmail();
                        if (!string.IsNullOrEmpty(hint))
                        {
                            context.ProtocolMessage.LoginHint = hint;
                        }
                        return(Task.FromResult(0));
                    },
                    AuthorizationCodeReceived = async(context) =>
                    {
                        var identity = context.AuthenticationTicket.Identity;

                        // Get token with authorization code
                        var redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
                        var credential  = new ClientCredential(Constants.AADClientId, Constants.AADClientSecret);
                        var authContext = AuthenticationHelper.GetAuthenticationContext(identity, Permissions.Delegated);
                        var authResult  = await authContext.AcquireTokenByAuthorizationCodeAsync(context.Code, redirectUri, credential, Constants.Resources.MSGraph);

                        // Get user's roles and add them to claims
                        var graphServiceClient = authResult.CreateGraphServiceClient();
                        var graphClient        = new MSGraphClient(graphServiceClient);
                        var user = await graphClient.GetCurrentUserAsync();
                        foreach (var role in user.Roles)
                        {
                            identity.AddClaim(ClaimTypes.Role, role);
                        }
                    },
                    AuthenticationFailed = (context) =>
                    {
                        var redirectUrl = "/Error?message=" + Uri.EscapeDataString(context.Exception.Message);
                        context.OwinContext.Response.Redirect(redirectUrl);
                        context.HandleResponse();     // Suppress the exception
                        return(Task.FromResult(0));
                    }
                }
            });
        }
Example #32
0
        //private string ConnectionString = "server=localhost;Database=IdentityServerSampleDb;Trusted_Connection=True";

        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888


            app.Map("/identity", (idsrv) =>
            {
                //EntityFrameworkServiceOptions efConfig = new EntityFrameworkServiceOptions
                //{
                //    ConnectionString = ConnectionString,
                //    //SynchronousReads = true
                //};

                IdentityServerServiceFactory Factory = new IdentityServerServiceFactory()
                                                       .UseInMemoryClients(Clients.Get())
                                                       .UseInMemoryUsers(Users.Get())
                                                       .UseInMemoryScopes(Scopes.Get());

                //Factory.RegisterConfigurationServices(efConfig);
                //Factory.RegisterOperationalServices(efConfig);

                //Factory.ConfigureClientStoreCache();
                //Factory.ConfigureScopeStoreCache();

                idsrv.UseIdentityServer(new IdentityServerOptions
                {
                    RequireSsl         = true,
                    SiteName           = "IdentityServer3Sample",
                    IssuerUri          = Authority,
                    Factory            = Factory,
                    PublicOrigin       = BaseUri,
                    SigningCertificate = GetCertificate(),

                    AuthenticationOptions = new AuthenticationOptions
                    {
                        EnablePostSignOutAutoRedirect = true,
                        //IdentityProviders = ConfigureIdentityProviders
                    }
                });
            });

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority         = Authority,
                DelayLoadMetadata = true,
                ValidationMode    = ValidationMode.Both,
                RequiredScopes    = new[] { "api" },
            });
            app.UseWebApi(WebApiConfig.Register());

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
                                     //LogoutPath = new PathString("https://identity-dev.com/")
            });


            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId                   = "mvc",
                Authority                  = Authority,
                RedirectUri                = BaseUri,
                ResponseType               = "token id_token",
                Scope                      = "openid api manager employee",
                ClientSecret               = "secret",
                UseTokenLifetime           = false,
                SignInAsAuthenticationType = "Cookies",
                PostLogoutRedirectUri      = "https://identity-dev.com/"
            });

            RouteConfig.RegisterRoutes(RouteTable.Routes);

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.RollingFile(pathFormat: @"IdSvrAdmin-{Date}.log")
                         .CreateLogger();

            //LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider());
        }
Example #33
0
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            app.SetDefaultSignInAsAuthenticationType(DefaultAuthenticationTypes.ApplicationCookie);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

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

            var msalClient = ConfidentialClientApplicationBuilder
                             .Create(clientId)
                             .WithClientSecret(clientSecret)
                             .WithAuthority(Authority)
                             .WithRedirectUri(redirectUrl)
                             .Build();

            var msalCache = new MSALPerUserMemoryTokenCache(msalClient.UserTokenCache);

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
            {
                // todo: check authority --> do we need multitenant? or should we be single-tenant
                AuthenticationType = OpenIdConnectAuthenticationDefaults.AuthenticationType,
                Authority          = Authority,
                ClientId           = clientId,
                ClientSecret       = clientSecret,
                //ResponseType = "code",
                MetadataAddress = $"{Authority}/.well-known/openid-configuration",
                Scope           = "openid profile offline_access User.Read",
                RedirectUri     = redirectUrl,
                Notifications   = new OpenIdConnectAuthenticationNotifications()
                {
                    SecurityTokenValidated = x =>
                    {
                        // you can add your own custom or additional claims here to the user's principal

                        return(Task.CompletedTask);
                    },
                    AuthorizationCodeReceived = async x =>
                    {
                        // redeeming authorization_code & storing it in a cache
                        var authCodeResult = msalClient.AcquireTokenByAuthorizationCode(new[] { "User.Read" }, x.Code);
                        var result         = await authCodeResult.ExecuteAsync();
                        return;
                    }
                }
            });

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

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

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Example #34
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId  = SettingsHelper.ClientId,
                Authority = SettingsHelper.Authority,

                //TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                //{
                //    // Use the default validation (validating against a single issuer value, in line of business apps (single tenant apps))
                //    //
                //    // NOTE:
                //    // * In a multitenant scenario, you can never validate against a fixed issuer string, as every tenant will send a different one.
                //    // * If you don’t care about validating tenants, as is the case for apps giving access to 1st party resources, you just turn off validation.
                //    // * If you do care about validating tenants, think of the case in which your app sells access to premium content and you want to limit access only to the tenant that paid a fee,
                //    //       you still need to turn off the default validation but you do need to add logic that compares the incoming issuer to a list of tenants that paid you,
                //    //       and block access if that’s not the case.
                //    // * Refer to the following sample for a custom validation logic: https://github.com/AzureADSamples/WebApp-WebAPI-MultiTenant-OpenIdConnect-DotNet

                //    ValidateIssuer = true
                //},

                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(SettingsHelper.ClientId, SettingsHelper.AppKey);
                        String UserObjectId         = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                        AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, new ADALTokenCache(UserObjectId));

                        AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, SettingsHelper.AADGraphResourceId);

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


                    RedirectToIdentityProvider = (context) =>
                    {
                        // 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;

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

                    AuthenticationFailed = (context) =>
                    {
                        // Suppress the exception if you don't want to see the error
                        context.HandleResponse();

                        return(Task.FromResult(0));
                    }
                }
            });
        }
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

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

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId              = "katanaclient",
                Authority             = Constants.BaseAddress,
                RedirectUri           = "http://localhost:2672/",
                PostLogoutRedirectUri = "http://localhost:2672/",
                ResponseType          = "code id_token token",
                Scope = "openid email profile read write offline_access",

                SignInAsAuthenticationType = "Cookies",

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async n =>
                    {
                        // filter "protocol" claims
                        var claims = new List <Claim>(from c in n.AuthenticationTicket.Identity.Claims
                                                      where c.Type != "iss" &&
                                                      c.Type != "aud" &&
                                                      c.Type != "nbf" &&
                                                      c.Type != "exp" &&
                                                      c.Type != "iat" &&
                                                      c.Type != "nonce" &&
                                                      c.Type != "c_hash" &&
                                                      c.Type != "at_hash"
                                                      select c);

                        // get userinfo data
                        var userInfoClient = new UserInfoClient(
                            new Uri(Constants.UserInfoEndpoint),
                            n.ProtocolMessage.AccessToken);

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

                        // get access and refresh token
                        var tokenClient = new OAuth2Client(
                            new Uri(Constants.TokenEndpoint),
                            "katanaclient",
                            "secret");

                        var response = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri);

                        claims.Add(new Claim("access_token", response.AccessToken));
                        claims.Add(new Claim("expires_at", DateTime.Now.AddSeconds(response.ExpiresIn).ToLocalTime().ToString()));
                        claims.Add(new Claim("refresh_token", response.RefreshToken));
                        claims.Add(new Claim("id_token", n.ProtocolMessage.IdToken));

                        n.AuthenticationTicket = new AuthenticationTicket(new ClaimsIdentity(claims.Distinct(new ClaimComparer()), n.AuthenticationTicket.Identity.AuthenticationType), n.AuthenticationTicket.Properties);
                    },

                    RedirectToIdentityProvider = async n =>
                    {
                        // if signing out, add the id_token_hint
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token").Value;
                            n.ProtocolMessage.IdTokenHint = idTokenHint;
                        }
                    },
                }
            });
        }
Example #36
0
        public void Configuration(IAppBuilder app)
        {
            //app.Use(async (Context, next) =>
            //{
            //    //logger.Debug("after OIDC, before app handler");
            //    await next.Invoke();
            //    //logger.Debug("after OIDC, after app handler");
            //    Console.WriteLine("Done with first MW");
            //});
            app.SetDefaultSignInAsAuthenticationType(DefaultAuthenticationTypes.ApplicationCookie);

            app.Use(async(Context, next) =>
            {
                //logger.Debug("after OIDC, before app handler");
                await next.Invoke();
                //logger.Debug("after OIDC, after app handler");
                Console.WriteLine("Done with Second MW");
            });
            app.UseCookieAuthentication(new CookieAuthenticationOptions {
            });
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
            {
                ClientId           = "dhc.admin",
                AuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                //     AuthenticationMode=AuthenticationMode.Active,
                //AuthenticationMode = AuthenticationMode.Active,
                Authority   = "http://localhost:7000/",
                RedirectUri = "http://localhost:7000/signin-oidc",
                //PostLogoutRedirectUri = "http://localhost:5000/signout-callback-oidc",
                ResponseType = "code id_token",
                Scope        = "openid profile",
                //AuthenticationMode = AuthenticationMode.Passive,
                //AuthenticationType = OpenIdConnectAuthenticationDefaults.AuthenticationType,
                RequireHttpsMetadata = false,
                ClientSecret         = "49C1A7E1-0C79-4A89-A3D6-A37998FB86B0",
                UseTokenLifetime     = false,
                Notifications        = new OpenIdConnectAuthenticationNotifications()
                {
                    MessageReceived = n =>
                    {
                        return(Task.FromResult(0));
                    },
                    AuthenticationFailed = n =>
                    {
                        return(Task.FromResult(0));
                    },
                    AuthorizationCodeReceived = n =>
                    {
                        return(Task.FromResult(0));
                    },
                    SecurityTokenReceived = n =>
                    {
                        return(Task.FromResult(0));
                    },
                    SecurityTokenValidated = n =>
                    {
                        return(Task.FromResult(0));
                    },
                    RedirectToIdentityProvider = (n) =>
                    {
                        return(Task.FromResult(0));
                    }
                }
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            app.Use(async(Context, next) =>
            {
                //logger.Debug("after OIDC, before app handler");
                await next.Invoke();
                //logger.Debug("after OIDC, after app handler");
            });
        }
        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 #38
0
        public void Configuration(IAppBuilder app)
        {
            Log.Logger = StandardLoggerConfigurator
                         .GetLoggerConfig().MinimumLevel
                         .Debug()
                         .CreateLogger();

            Log.Logger.Information("Starting...");
            Log.Logger.Information("Version is... " + ConfigurationManager.AppSettings["ReleaseNumber"]);

            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap <Event, EventViewModel>()
                .ForMember(x => x.ViewModelMode, x => x.Ignore())
                .ForMember(x => x.CarEmail, x => x.Ignore())
                .ForMember(x => x.CarName, x => x.Ignore())
                .ForMember(x => x.CarPhone, x => x.Ignore());
            });

            Mapper.Configuration.AssertConfigurationIsValid();

            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            AntiForgeryConfig.UniqueClaimTypeIdentifier =
                JwtClaimTypes.Name;

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies",
                ExpireTimeSpan     = new TimeSpan(0, 30, 0),
                SlidingExpiration  = true
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId    = ClientId,
                Authority   = ConfigurationManager.AppSettings["IdentityServerApplicationUrl"],
                RedirectUri = ConfigurationManager.AppSettings["UrlRideShareWeb"],
                SignInAsAuthenticationType = "Cookies",
                ResponseType          = "code id_token token",
                Scope                 = "openid profile address gallerymanagement roles offline_access email",
                UseTokenLifetime      = false,
                PostLogoutRedirectUri = ConfigurationManager.AppSettings["UrlRideShareWeb"],

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        TokenHelper.DecodeAndWrite(n.ProtocolMessage.IdToken);
                        TokenHelper.DecodeAndWrite(n.ProtocolMessage.AccessToken);

                        var givenNameClaim = n.AuthenticationTicket
                                             .Identity.FindFirst(JwtClaimTypes.GivenName);

                        var familyNameClaim = n.AuthenticationTicket
                                              .Identity.FindFirst(JwtClaimTypes.FamilyName);

                        var subClaim = n.AuthenticationTicket
                                       .Identity.FindFirst(JwtClaimTypes.Subject);

                        var roleClaim = n.AuthenticationTicket
                                        .Identity.FindFirst(JwtClaimTypes.Role);

                        var emailClaim = n.AuthenticationTicket
                                         .Identity.FindFirst(JwtClaimTypes.Email);

                        // create a new claims, issuer + sub as unique identifier
                        var nameClaim = new Claim(JwtClaimTypes.Name,
                                                  Constants.AndersAtHomeIdentityServerIssuerUri + subClaim.Value);

                        var newClaimsIdentity = new ClaimsIdentity(
                            n.AuthenticationTicket.Identity.AuthenticationType,
                            JwtClaimTypes.Name,
                            JwtClaimTypes.Role);

                        newClaimsIdentity.AddClaim(nameClaim);

                        if (givenNameClaim != null)
                        {
                            newClaimsIdentity.AddClaim(givenNameClaim);
                        }

                        if (familyNameClaim != null)
                        {
                            newClaimsIdentity.AddClaim(familyNameClaim);
                        }

                        if (roleClaim != null)
                        {
                            newClaimsIdentity.AddClaim(roleClaim);
                        }

                        if (emailClaim != null)
                        {
                            newClaimsIdentity.AddClaim(emailClaim);
                        }

                        // request a refresh token
                        var tokenClientForRefreshToken = new TokenClient(
                            ConfigurationManager.AppSettings["IdentityServerApplicationUrl"] + "/connect/token",
                            ClientId,
                            Constants.RideShareWebClientSecret);

                        var refreshResponse = await
                                              tokenClientForRefreshToken.RequestAuthorizationCodeAsync(
                            n.ProtocolMessage.Code,
                            ConfigurationManager.AppSettings["UrlRideShareWeb"]);

                        var expirationDateAsRoundtripString
                            = DateTime.SpecifyKind(DateTime.UtcNow.AddSeconds(refreshResponse.ExpiresIn)
                                                   , DateTimeKind.Utc).ToString("o");


                        newClaimsIdentity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                        newClaimsIdentity.AddClaim(new Claim("refresh_token", refreshResponse.RefreshToken));
                        newClaimsIdentity.AddClaim(new Claim("access_token", refreshResponse.AccessToken));
                        newClaimsIdentity.AddClaim(new Claim("expires_at", expirationDateAsRoundtripString));
                        newClaimsIdentity.AddClaim(new Claim("sub", subClaim.Value));

                        // create a new authentication ticket, overwriting the old one.
                        n.AuthenticationTicket = new AuthenticationTicket(
                            newClaimsIdentity,
                            n.AuthenticationTicket.Properties);
                    },
                    RedirectToIdentityProvider = async n =>
                    {
                        await Task.FromResult(0);

                        // get id token to add as id token hint
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var identityTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (identityTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = identityTokenHint.Value;
                            }
                        }
                        //else if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.AuthenticationRequest)
                        //{
                        //    string existingAcrValues = null;
                        //    if (n.ProtocolMessage.Parameters.TryGetValue("acr_values", out existingAcrValues))
                        //    {
                        //        // add "2fa" - acr_values are separated by a space
                        //        n.ProtocolMessage.Parameters["acr_values"] = existingAcrValues + " 2fa";
                        //    }

                        //    n.ProtocolMessage.Parameters["acr_values"] = "2fa";
                        //}
                    }
                }
            });
        }
Example #39
0
        public void Configuration(IAppBuilder app)
        {
            var identityServerUri = ConfigurationManager.AppSettings[IdentityServerUrlKey];
            var redirectUri       = ConfigurationManager.AppSettings[RedirectUriKey];

            identityServerUri = "https://b3ncr.auth:44340/identity";
            redirectUri       = "https://b3ncr.comms:44341/";

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });
            // Enable the application to use a cookie to store information for the signed in user
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority   = identityServerUri,
                ClientId    = ClientId,
                RedirectUri = redirectUri,
                Scope       = "openid profile sampleApi",
                SignInAsAuthenticationType = "Cookies"
            });

            app.Map("/api", inner =>
            {
                // Web API configuration and services
                var config = new HttpConfiguration();

                JwtSecurityTokenHandler.InboundClaimTypeMap = ClaimMappings.None;

                inner.UseIdentityServerJwt(new JwtTokenValidationOptions
                {
                    Authority = "https://b3ncr.auth:44340/identity"
                });

                // for reference tokens
                inner.UseIdentityServerReferenceToken(new ReferenceTokenValidationOptions
                {
                    Authority = "https://b3ncr.auth:44340/identity"
                });

                // require read OR write scope
                inner.RequireScopes(new ScopeValidationOptions
                {
                    AllowAnonymousAccess = true,
                    Scopes = new[] { "sampleApi" }
                });


                //config.SuppressDefaultHostAuthentication();

                config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

                // Web API routes
                //config.MapHttpAttributeRoutes();

                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                    );

                inner.UseWebApi(config);
            });
        }
Example #40
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();
            AntiForgeryConfig.UniqueClaimTypeIdentifier = "unique_user_key";

            app.UseResourceAuthorization(new AuthorizationManager());

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

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId              = "medicoClientMvc",
                UseTokenLifetime      = false,
                Authority             = Constants.Constants.BaseAddress,
                RedirectUri           = Constants.Constants.BaseAddressMvc,
                PostLogoutRedirectUri = Constants.Constants.BaseAddressMvc,
                ResponseType          = "code id_token token",
                Scope = "openid email profile roles medicoApi offline_access",

                SignInAsAuthenticationType = "Cookies",

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    RedirectToIdentityProvider = n =>
                    {
                        // if signing out, add the id_token_hint
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (idTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                            }
                        }

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

                    MessageReceived = async n =>
                    {
                        EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.IdToken);
                        EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.AccessToken);
                        var userInfo = await EndpointAndTokenHelper.CallUserInfoEndpoint(n.ProtocolMessage.AccessToken);
                    },

                    SecurityTokenValidated = async n =>
                    {
                        var userInfo = await EndpointAndTokenHelper.CallUserInfoEndpoint(n.ProtocolMessage.AccessToken);


                        // use the authorization code to get a refresh token
                        var tokenEndpointClient = new OAuth2Client(
                            new Uri(Constants.Constants.TokenEndpoint),
                            "medicoClientMvc", "secret");

                        var tokenResponse = await tokenEndpointClient.RequestAuthorizationCodeAsync(
                            n.ProtocolMessage.Code, Constants.Constants.BaseAddressMvc);



                        var givenNameClaim = new Claim(
                            Thinktecture.IdentityModel.Client.JwtClaimTypes.GivenName,
                            userInfo.Value <string>("given_name"));

                        var familyNameClaim = new Claim(
                            Thinktecture.IdentityModel.Client.JwtClaimTypes.FamilyName,
                            userInfo.Value <string>("family_name"));

                        var roles = userInfo.Value <JArray>("role").ToList();

                        var newIdentity = new ClaimsIdentity(
                            n.AuthenticationTicket.Identity.AuthenticationType,
                            Thinktecture.IdentityModel.Client.JwtClaimTypes.GivenName,
                            Thinktecture.IdentityModel.Client.JwtClaimTypes.Role);

                        newIdentity.AddClaim(givenNameClaim);
                        newIdentity.AddClaim(familyNameClaim);

                        foreach (var role in roles)
                        {
                            newIdentity.AddClaim(new Claim(
                                                     Thinktecture.IdentityModel.Client.JwtClaimTypes.Role,
                                                     role.ToString()));
                        }

                        var issuerClaim = n.AuthenticationTicket.Identity
                                          .FindFirst(Thinktecture.IdentityModel.Client.JwtClaimTypes.Issuer);
                        var subjectClaim = n.AuthenticationTicket.Identity
                                           .FindFirst(Thinktecture.IdentityModel.Client.JwtClaimTypes.Subject);

                        newIdentity.AddClaim(new Claim("unique_user_key",
                                                       issuerClaim.Value + "_" + subjectClaim.Value));


                        newIdentity.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken));
                        //newIdentity.AddClaim(new Claim("access_token", tokenResponse.AccessToken));
                        newIdentity.AddClaim(new Claim("expires_at",
                                                       DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToLocalTime().ToString()));

                        newIdentity.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));
                        newIdentity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

                        //// use the authorization code to get a refresh token
                        //var oauth2Client = new OAuth2Client(
                        //    new Uri(Constants.Constants.TokenEndpoint),
                        //    "medicoClientMvc", "secret");



                        n.AuthenticationTicket = new AuthenticationTicket(
                            newIdentity,
                            n.AuthenticationTicket.Properties);
                    },
                }
            });
        }
Example #41
0
        public void Configuration(IAppBuilder app)
        {
            //LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider());

            AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            app.Map("/identity", idsrvApp =>
            {
                idsrvApp.UseIdentityServer(new IdentityServerOptions
                {
                    SiteName           = "Embedded IdentityServer",
                    SigningCertificate = LoadCertificate(),

                    Factory = new IdentityServerServiceFactory()
                              .UseInMemoryUsers(Users.Get())
                              .UseInMemoryClients(Clients.Get())
                              .UseInMemoryScopes(Scopes.Get()),

                    AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions
                    {
                        EnablePostSignOutAutoRedirect = true,
                        IdentityProviders             = ConfigureIdentityProviders
                    }
                });
            });

            app.UseResourceAuthorization(new AuthorizationManager());

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


            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority = "https://localhost:44302/identity",

                ClientId     = "mvc",
                Scope        = "openid profile roles sampleApi",
                ResponseType = "id_token token",
                RedirectUri  = "https://localhost:44302/",

                SignInAsAuthenticationType = "Cookies",
                UseTokenLifetime           = false,

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        var nid = new ClaimsIdentity(
                            n.AuthenticationTicket.Identity.AuthenticationType,
                            Constants.ClaimTypes.GivenName,
                            Constants.ClaimTypes.Role);

                        // get userinfo data
                        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 = n =>
                    {
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (idTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                            }
                        }

                        return(Task.FromResult(0));
                    }
                }
            });
        }
        public static void Config(IAppBuilder app, string identityServerUrl)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();
            AntiForgeryConfig.UniqueClaimTypeIdentifier = IdentityModel.JwtClaimTypes.Name;

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority          = identityServerUrl + "/identity",
                AuthenticationType = "oidc",
                ClientId           = "ClientId",
                ClientSecret       = "ClientSecret",
                Scope        = "openid profile email roles WebAPI",
                ResponseType = "id_token token",
                RedirectUri  = identityServerUrl,
                SignInAsAuthenticationType = "Cookies",
                UseTokenLifetime           = false,
                //CallbackPath = new PathString(identityServerUrl + "/identity"),
                //CallbackPath = new PathString("/callback/"),
                //CallbackPath = new PathString("/Home"),
                ProtocolValidator = new OpenIdConnectProtocolValidator
                {
                    RequireNonce = true
                },

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        var nid = new ClaimsIdentity(
                            n.AuthenticationTicket.Identity.AuthenticationType,
                            Constants.ClaimTypes.GivenName,
                            Constants.ClaimTypes.Role);

                        // get userinfo data
                        var endpoint       = n.Options.Authority + "/connect/userinfo";
                        var userInfoClient = new UserInfoClient(endpoint);

                        var userInfo = await userInfoClient.GetAsync(n.ProtocolMessage.AccessToken);
                        userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Type, ui.Value)));

                        nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                        nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));
                        nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));

                        n.AuthenticationTicket = new AuthenticationTicket(nid, n.AuthenticationTicket.Properties);
                    },

                    RedirectToIdentityProvider = context =>
                    {
                        var appBaseUrl  = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                        var queryString = context.Request.Uri.PathAndQuery;
                        context.ProtocolMessage.RedirectUri = appBaseUrl + queryString;

                        if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.AuthenticationRequest)
                        {
                            context.ProtocolMessage.RedirectUri = identityServerUrl;
                            return(Task.FromResult(0));
                        }

                        if (context.ProtocolMessage.RequestType != OpenIdConnectRequestType.LogoutRequest)
                        {
                            return(Task.FromResult(0));
                        }
                        var idTokenHint = context.OwinContext.Authentication.User.FindFirst("id_token");

                        if (idTokenHint != null)
                        {
                            context.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                        }

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

                    AuthenticationFailed = context =>
                    {
                        if (context.Exception is OpenIdConnectProtocolInvalidNonceException)
                        {
                            context.SkipToNextMiddleware();
                            return(Task.FromResult(0));
                        }

                        if (!context.OwinContext.Authentication.User.Identity.IsAuthenticated)
                        {
                            context.HandleResponse();
                            context.Response.Redirect("/");
                            return(Task.FromResult(0));
                        }
                        context.HandleResponse();
                        context.Response.Redirect("/ValidatorError?message=" + context.Exception.Message);
                        return(Task.FromResult(0));
                    }
                }
            });
        }
Example #43
0
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseKentorOwinCookieSaver();

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

            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId              = "mvc.5",
                Authority             = "http://localhost:5000/",
                RedirectUri           = "http://localhost:2000/",
                PostLogoutRedirectUri = "http://localhost:2000/",
                ResponseType          = "code id_token",
                Scope = "openid profile offline_access",

                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role"
                },

                SignInAsAuthenticationType = "Cookies",

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async n =>
                    {
                        // use the code to get the access and refresh token
                        var tokenClient = new TokenClient(
                            "http://localhost:5000/connect/token",
                            "mvc.5",
                            "secret");

                        var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(
                            n.Code, n.RedirectUri);

                        if (tokenResponse.IsError)
                        {
                            throw new Exception(tokenResponse.Error);
                        }

                        // use the access token to retrieve claims from userinfo
                        var userInfoClient = new UserInfoClient(
                            new Uri("http://localhost:5000/connect/userinfo"),
                            tokenResponse.AccessToken);

                        var userInfoResponse = await userInfoClient.GetAsync();

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

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

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

                    RedirectToIdentityProvider = n =>
                    {
                        // if signing out, add the id_token_hint
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (idTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                            }
                        }

                        return(Task.FromResult(0));
                    }
                }
            });
        }
Example #44
0
        public void Configuration(IAppBuilder app)
        {
            string userInfoEndpoint =
                "https://localhost:44336/connect/userinfo";

            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationType = "CookiesMedbullets",
                ExpireTimeSpan     = TimeSpan.FromMinutes(10),
                SlidingExpiration  = true
            });

            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType         = "oidc",
                SignInAsAuthenticationType = "CookiesMedbullets",
                Authority             = "https://localhost:44336/",
                ClientId              = "implicit.medbullets",
                RedirectUri           = "http://localhost:5969/signin-oidc",
                PostLogoutRedirectUri = "http://localhost:5969/",
                ResponseType          = "id_token token",
                Scope            = "openid profile email profile.agent",
                UseTokenLifetime = false,
                Notifications    = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        var claimsToExclude = new[]
                        {
                            "aud", "iss", "nbf", "exp", "nonce", "iat", "at_hash"
                        };

                        var claimsToKeep =
                            n.AuthenticationTicket.Identity.Claims
                            .Where(x => !claimsToExclude.Contains(x.Type))
                            .ToList();
                        claimsToKeep.Add(new Claim("id_token", n.ProtocolMessage.IdToken));

                        if (n.ProtocolMessage.AccessToken != null)
                        {
                            claimsToKeep.Add(new Claim("access_token", n.ProtocolMessage.AccessToken));

                            var userInfoClient = new UserInfoClient(
                                new Uri(userInfoEndpoint),
                                n.ProtocolMessage.AccessToken); // Leverage Implicit flow we request User claims from endpoint usina access token!
                            // But access token came through front channel!
                            var userInfoResponse = await userInfoClient.GetAsync();
                            var userInfoClaims   = userInfoResponse.Claims
                                                   .Where(x => x.Item1 != "sub") // filter sub since we're already getting it from id_token
                                                   .Select(x => new Claim(x.Item1, x.Item2));
                            claimsToKeep.AddRange(userInfoClaims);
                        }

                        var claimsIdentity = new ClaimsIdentity(
                            n.AuthenticationTicket.Identity.AuthenticationType,
                            "name", "role");
                        claimsIdentity.AddClaims(claimsToKeep);

                        n.AuthenticationTicket = new Microsoft.Owin.Security.AuthenticationTicket(
                            claimsIdentity, n.AuthenticationTicket.Properties
                            );
                    },
                    RedirectToIdentityProvider = n =>
                    {
                        if (n.ProtocolMessage.RequestType ==
                            OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idToken = n.OwinContext.Authentication
                                          .User.FindFirst("id_token")?.Value;
                            n.ProtocolMessage.IdTokenHint = idToken;
                        }
                        return(Task.FromResult(0));
                    }
                }
            });
            app.UseStageMarker(PipelineStage.Authenticate);
        }
Example #45
0
        public void Configuration(IAppBuilder app)
        {
            // for the mvc app
            AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

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

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority = "https://localhost:44304/identity",

                ClientId     = "mvc",
                RedirectUri  = "https://localhost:44302/",
                ResponseType = "id_token token",
                Scope        = "openid profile roles sampleApi",

                SignInAsAuthenticationType = "Cookies",
                // UseTokenLifetime = false,

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        var id = n.AuthenticationTicket.Identity;

                        var nid = new ClaimsIdentity(id.AuthenticationType, Constants.ClaimTypes.GivenName, Constants.ClaimTypes.Role);

                        // claims to keep
                        //var givenName = id.FindFirst(Constants.ClaimTypes.GivenName);
                        //var familyName = id.FindFirst(Constants.ClaimTypes.FamilyName);
                        //var sub = id.FindFirst(Constants.ClaimTypes.Subject);
                        //var roles = id.FindAll(Constants.ClaimTypes.Role);

                        //nid.AddClaim(givenName);
                        //nid.AddClaim(familyName);
                        //nid.AddClaim(sub);
                        //nid.AddClaims(roles);

                        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)));

                        nid.AddClaim(new Claim(Constants.TokenTypes.IdentityToken, n.ProtocolMessage.IdToken));
                        nid.AddClaim(new Claim(Constants.TokenTypes.AccessToken, n.ProtocolMessage.AccessToken));
                        nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));

                        n.AuthenticationTicket = new AuthenticationTicket(nid, n.AuthenticationTicket.Properties);
                    },
                    RedirectToIdentityProvider = async n =>
                    {
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst(Constants.TokenTypes.IdentityToken).Value;
                            n.ProtocolMessage.IdTokenHint = idTokenHint;
                        }
                    }
                }
            });

            app.UseResourceAuthorization(new AuthorizationManager());


            //app.Map("/api", apiReq =>
            //    {
            //        apiReq.Use(typeof(CallApiMiddleware));
            //    });
        }
Example #46
0
        public void ConfigureAuth(IAppBuilder app)
        {
            ApplicationDbContext db = new ApplicationDbContext();

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId  = clientId,
                Authority = Authority,

                TokenValidationParameters = new Microsoft.IdentityModel.Tokens.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 needs access to the entire organization, then add the logic
                    // of validating the Issuer here.
                    // IssuerValidator
                },
                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 = async(context) =>
                    {
                        var code = context.Code;
                        ClientCredential credential       = new ClientCredential(clientId, appKey);
                        string signedInUserID             = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                        AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                        AuthenticationResult result       = await authContext.AcquireTokenByAuthorizationCodeAsync(
                            code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
                    },
                    RedirectToIdentityProvider = (context) =>
                    {
                        // 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;
                        return(Task.FromResult(0));
                    },
                    SecurityTokenValidated = (context) =>
                    {
                        // If your authentication logic is based on users then add your logic here
                        // retriever caller data from the incoming principal
                        string issuer   = context.AuthenticationTicket.Identity.FindFirst("iss").Value;
                        string UPN      = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value;
                        string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

                        /*
                         * if (
                         *  // the caller comes from an admin-consented, recorded issuer
                         *  (db.Tenants.FirstOrDefault(a => ((a.IssValue == issuer) && (a.AdminConsented))) == null)
                         *  // the caller is recorded in the db of users who went through the individual onboardoing
                         *  && (db.Users.FirstOrDefault(b => ((b.UPN == UPN) && (b.TenantID == tenantID))) == null)
                         *  )
                         *  // the caller was neither from a trusted issuer or a registered user - throw to block the authentication flow
                         *  throw new System.IdentityModel.Tokens.SecurityTokenValidationException();*/
                        return(Task.FromResult(0));
                    },
                }
            });
        }
Example #47
0
        public void Configuration(IAppBuilder app)
        {
            // Define que a chave do usuário vem da Claim "sub"
            AntiForgeryConfig.UniqueClaimTypeIdentifier = "sub";
            // Desliga o mapeamento automático de Claims do asp.net, os nomes ficam como as
            // Claims do Acesso Cidadão..
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            // Configurar o OWIN para gerenciar autenticação usando Cookies
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            // Configurando para fazer autenticação usando OpenID Connect
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority = Constants.BaseAddress,
                ClientId  = Constants.ClientIdCorporativo,
                //ClientSecret = Constants.ClientSecretCorporativo,
                RedirectUri  = Constants.RedirectUriCorporativo,
                ResponseType = "id_token code",
                // A maioria desses scopes só está disponível para sistemas corporativos do estado
                // e precisa de permissão explicita da área responsável. Fazer requisição devidamente
                // fundamentada de porque a informação é necessária
                Scope = "openid nome email cpf dataNascimento filiacao permissoes roles offline_access api-teste",
                //Essas permissões só podem ser usadas em sistemas corporativos
                //Scope = "openid cpf nome email dataNascimento permissoes roles",

                // Configura o middleware do openid connect para usar o middleware configurado acima
                // para controlar a autenticação usando cookies
                SignInAsAuthenticationType = "Cookies",

                // Essa parte é totalmente opcional
                // Nesse exemplo a gente vai usar ela para apagar algumas claims que vem do Acesso Cidadão
                // e não queremos guardar e para setar o nome da identity
                // Mas também pode ser usada para fazer qualquer tipo de mapeamento das claims que vem do Acesso Cidadão
                // Por exemplo: Trocar o nome, por primeiro nome e sobrenome, mapear as permissões para outra
                // representação e assim por diante
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async n =>
                    {
                        // use the code to get the access and refresh token
                        var tokenClient = new TokenClient(
                            Constants.TokenEndpoint,
                            Constants.ClientIdCorporativo,
                            Constants.ClientSecretCorporativo);

                        var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(
                            n.Code, n.RedirectUri);

                        if (tokenResponse.IsError)
                        {
                            throw new Exception(tokenResponse.Error);
                        }

                        // use the access token to retrieve claims from userinfo
                        var userInfoClient   = new UserInfoClient(Constants.UserInfoEndpoint);
                        var userInfoResponse = await userInfoClient.GetAsync(tokenResponse.AccessToken);

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

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

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

                    RedirectToIdentityProvider = n =>
                    {
                        // if signing out, add the id_token_hint
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (idTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                            }
                        }

                        return(Task.FromResult(0));
                    }
                }
            });
        }
Example #48
0
        /// <summary>
        /// Configure OWIN to use OpenIdConnect
        /// </summary>
        /// <param name="app"></param>
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId              = Constants.Clients.Enrolments,
                ClientSecret          = Constants.Secrets.SharedSecret,
                Authority             = Constants.Urls.IdentityServerProviderUrl,
                RedirectUri           = Constants.Urls.EnrolmentsUrl,
                PostLogoutRedirectUri = Constants.Urls.EnrolmentsUrl,
                Scope = PopulateScopes(),
                SignInAsAuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                ResponseType = OpenIdConnectResponseType.Code,

                UseTokenLifetime = false,
                RedeemCode       = true,
                SaveTokens       = true,


                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = true
                },


                // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
                //Notifications = new OpenIdConnectAuthenticationNotifications
                //{
                //    AuthenticationFailed = OnAuthenticationFailed,
                //    RedirectToIdentityProvider = n =>
                //    {
                //        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
                //        {
                //            // set PKCE parameters
                //            var codeVerifier = CryptoRandom.CreateUniqueId(32);

                //            string codeChallenge;
                //            using (var sha256 = SHA256.Create())
                //            {
                //                var challengeBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier));
                //                codeChallenge = Base64Url.Encode(challengeBytes);
                //            }

                //            n.ProtocolMessage.SetParameter("code_challenge", codeChallenge);
                //            n.ProtocolMessage.SetParameter("code_challenge_method", "S256");

                //            // remember code_verifier (adapted from OWIN nonce cookie)
                //            RememberCodeVerifier(n, codeVerifier);
                //        }

                //        return Task.CompletedTask;
                //    },
                //    AuthorizationCodeReceived = n =>
                //    {
                //        // get code_verifier
                //        var codeVerifier = RetrieveCodeVerifier(n);

                //        // attach code_verifier
                //        n.TokenEndpointRequest.SetParameter("code_verifier", codeVerifier);

                //        return Task.CompletedTask;
                //    }
                //}
            }
                );

            string PopulateScopes()
            {
                var scopes = new List <string>
                {
                    OpenIdConnectScope.OpenIdProfile,
                    OpenIdConnectScope.OfflineAccess,
                    OpenIdConnectScope.Email,
                    Constants.Clients.ApiStudents,
                    Constants.Clients.ApiTeachers,
                    Constants.Clients.ApiCourses,
                    "address",
                    "roles",
                    "country",
                    "custom_ids"
                };

                return(string.Join(" ", scopes.ToArray()));
            }
        }
Example #49
0
        public void Configuration(IAppBuilder app)
        {
            LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider());
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            app.Map("/identity", idsrvApp =>
            {
                idsrvApp.UseIdentityServer(new IdentityServerOptions
                {
                    SiteName           = "Embedded IdentityServer",
                    IssuerUri          = "https://idsrv3/embedded",
                    SigningCertificate = LoadCertificate(),

                    Factory = InMemoryFactory.Create(
                        users: Users.Get(),
                        clients: Clients.Get(),
                        scopes: Scopes.Get())
                });
            });

            app.UseResourceAuthorization(new AuthorizationManager());

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


            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority = "https://localhost:44319/identity",

                ClientId    = "mvc",
                Scope       = "openid profile roles",
                RedirectUri = "https://localhost:44319/",

                SignInAsAuthenticationType = "Cookies",
                UseTokenLifetime           = false,

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        var id = n.AuthenticationTicket.Identity;

                        // we want to keep first name, last name, subject and roles
                        var givenName  = id.FindFirst(Constants.ClaimTypes.GivenName);
                        var familyName = id.FindFirst(Constants.ClaimTypes.FamilyName);
                        var sub        = id.FindFirst(Constants.ClaimTypes.Subject);
                        var roles      = id.FindAll(Constants.ClaimTypes.Role);

                        // create new identity and set name and role claim type
                        var nid = new ClaimsIdentity(
                            id.AuthenticationType,
                            Constants.ClaimTypes.GivenName,
                            Constants.ClaimTypes.Role);

                        nid.AddClaim(givenName);
                        nid.AddClaim(familyName);
                        nid.AddClaim(sub);
                        nid.AddClaims(roles);

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

                        // 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.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token").Value;
                            n.ProtocolMessage.IdTokenHint = idTokenHint;
                        }
                    }
                }
            });
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            string ClientId = ConfigurationManager.AppSettings["ida:ClientID"];
            string Password = ConfigurationManager.AppSettings["ida:Password"];
            string Authority = string.Format(ConfigurationManager.AppSettings["ida:Authority"], "common");
            string GraphAPIIdentifier = ConfigurationManager.AppSettings["ida:GraphAPIIdentifier"];
            string AzureResourceManagerIdentifier = ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"];
                        
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions { });
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = ClientId,
                    Authority = Authority,
                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                    {
                        // we inject our own multitenant validation logic
                        ValidateIssuer = false,
                    },
                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        RedirectToIdentityProvider = (context) =>
                        {
                            // 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 = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path);
                            context.ProtocolMessage.PostLogoutRedirectUri = new UrlHelper(HttpContext.Current.Request.RequestContext).Action
                                ("Index", "Home", null, HttpContext.Current.Request.Url.Scheme);
                            context.ProtocolMessage.Resource = GraphAPIIdentifier;
                            return Task.FromResult(0);
                        },
                        AuthorizationCodeReceived = (context) =>
                        {
                            ClientCredential credential = new ClientCredential(ClientId, Password);
                            string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                            string signedInUserUniqueName = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value.Split('#')[context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];

                            AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantID),
                                new ADALTokenCache(signedInUserUniqueName));

                            //var items = authContext.TokenCache.ReadItems().ToList();

                            AuthenticationResult result1 = authContext.AcquireTokenByAuthorizationCode(
                                context.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential);

                             //items = authContext.TokenCache.ReadItems().ToList();

                             AuthenticationResult result2 = authContext.AcquireTokenSilent(ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"], credential,
                                 new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));

                             //items = authContext.TokenCache.ReadItems().ToList();

                            return Task.FromResult(0);
                        },
                        // we use this notification for injecting our custom logic
                        SecurityTokenValidated = (context) =>
                        {
                            // retriever caller data from the incoming principal
                            string issuer = context.AuthenticationTicket.Identity.FindFirst("iss").Value;
                            if (!issuer.StartsWith("https://sts.windows.net/"))
                                // the caller is not from a trusted issuer - throw to block the authentication flow
                                throw new System.IdentityModel.Tokens.SecurityTokenValidationException();

                            return Task.FromResult(0);
                        },
                        //AuthenticationFailed = (context) =>
                        //{
                        //    context.OwinContext.Response.Redirect(new UrlHelper(HttpContext.Current.Request.RequestContext).
                        //        Action("Index", "Home", null, HttpContext.Current.Request.Url.Scheme));
                        //    context.HandleResponse(); // Suppress the exception
                        //    return Task.FromResult(0);
                        //}
                    }
                });
        }
Example #51
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationType = "Cookies"
            });

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            //app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            //{
            //    AuthenticationType = "oidc",
            //    SignInAsAuthenticationType = "Cookies",
            //    Authority = "https://localhost:44385/",
            //    ClientId = "mgr.webform",
            //    ClientSecret = "webform_secret",
            //    RedirectUri = "https://localhost:44308/signin-oidc",
            //    PostLogoutRedirectUri = "https://localhost:44308",
            //    ResponseType = "id_token token",
            //    Scope = "openid profile department offline_access",
            //    UseTokenLifetime = false,
            //    SaveTokens = true,
            //    Notifications = new OpenIdConnectAuthenticationNotifications
            //    {
            //        SecurityTokenValidated = async n =>
            //        {
            //            var claims_to_exclude = new[]
            //            {
            //                "aud", "iss", "nbf", "exp", "nonce", "iat", "at_hash"
            //            };

            //            var claims_to_keep =
            //                n.AuthenticationTicket.Identity.Claims
            //                .Where(x => false == claims_to_exclude.Contains(x.Type)).ToList();
            //            claims_to_keep.Add(new Claim("id_token", n.ProtocolMessage.IdToken));

            //            //if (n.ProtocolMessage.AccessToken != null)
            //            //{
            //            //    claims_to_keep.Add(new Claim("access_token", n.ProtocolMessage.AccessToken));
            //            //    using (HttpClient client = new HttpClient())
            //            //    {
            //            //        client.BaseAddress = new Uri("https://localhost:44385/");
            //            //        var discoveryResponse = await client.GetDiscoveryDocumentAsync();
            //            //        var userInfoResponse = await client.GetUserInfoAsync(new UserInfoRequest
            //            //        {
            //            //            Address = discoveryResponse.UserInfoEndpoint,
            //            //            Token = n.ProtocolMessage.AccessToken
            //            //        });
            //            //        var userInfoClaims = userInfoResponse.Claims
            //            //            .Where(x => x.Type != "sub") // filter sub since we're already getting it from id_token
            //            //            .Select(x => new Claim(x.Type, x.Value));
            //            //        claims_to_keep.AddRange(userInfoClaims);
            //            //    }
            //            //    //var userInfoClient = new UserInfoClient(new Uri("https://localhost:44333/core/connect/userinfo"), n.ProtocolMessage.AccessToken);
            //            //    //var userInfoResponse = await userInfoClient.GetAsync();
            //            //    //var userInfoClaims = userInfoResponse.Claims
            //            //    //    .Where(x => x.Item1 != "sub") // filter sub since we're already getting it from id_token
            //            //    //    .Select(x => new Claim(x.Item1, x.Item2));
            //            //    //claims_to_keep.AddRange(userInfoClaims);
            //            //}

            //            var ci = new ClaimsIdentity(
            //                n.AuthenticationTicket.Identity.AuthenticationType,
            //                "name", "role");
            //            ci.AddClaims(claims_to_keep);

            //            n.AuthenticationTicket = new Microsoft.Owin.Security.AuthenticationTicket(
            //                ci, n.AuthenticationTicket.Properties
            //            );
            //        },
            //        RedirectToIdentityProvider = n =>
            //        {
            //            if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
            //            {
            //                var id_token = n.OwinContext.Authentication.User.FindFirst("id_token")?.Value;
            //                n.ProtocolMessage.IdTokenHint = id_token;
            //            }

            //            return Task.FromResult(0);
            //        }
            //    }
            //});
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType         = "oidc",
                SignInAsAuthenticationType = "Cookies",
                Authority             = "https://localhost:44385/",
                ClientId              = "mgr.mainapp",
                ClientSecret          = "mainapp_secret",
                RedirectUri           = "https://localhost:44308/signin-oidc",
                PostLogoutRedirectUri = "https://localhost:44308",
                ResponseType          = "code id_token token",
                Scope         = "openid profile department mgr_mainapi offline_access",
                SaveTokens    = true,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async openIdMessage =>
                    {
                        var claimsToExclude = new[]
                        {
                            "aud", "iss", "nbf", "exp", "nonce", "iat", "at_hash"
                        };

                        var claims =
                            openIdMessage.AuthenticationTicket.Identity.Claims
                            .Where(x => false == claimsToExclude.Contains(x.Type)).ToList();
                        using (HttpClient client = new HttpClient())
                        {
                            client.BaseAddress    = new Uri("https://localhost:44385/");
                            var discoveryResponse = await client.GetDiscoveryDocumentAsync();

                            var responseCodeToken = client.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest
                            {
                                Address      = discoveryResponse.TokenEndpoint,
                                ClientId     = "mgr.mainapp",
                                ClientSecret = "mainapp_secret",
                                GrantType    = "authorization_code",
                                Code         = openIdMessage.Code,
                                RedirectUri  = openIdMessage.RedirectUri
                            }).Result;

                            if (!string.IsNullOrEmpty(responseCodeToken.IdentityToken) &&
                                !string.IsNullOrEmpty(responseCodeToken.AccessToken) &&
                                !string.IsNullOrEmpty(responseCodeToken.RefreshToken))
                            {
                                claims.Add(new Claim("id_token", responseCodeToken.IdentityToken));
                                claims.Add(new Claim("access_token", responseCodeToken.AccessToken));
                                claims.Add(new Claim("refresh_token", responseCodeToken.RefreshToken));
                            }
                            var claimsIdentity = new ClaimsIdentity(
                                openIdMessage.AuthenticationTicket.Identity.AuthenticationType,
                                "name", "role");
                            claimsIdentity.AddClaims(claims);
                            openIdMessage.AuthenticationTicket = new Microsoft.Owin.Security.AuthenticationTicket(claimsIdentity, openIdMessage.AuthenticationTicket.Properties);
                        }
                    },
                    //SecurityTokenValidated = async openIdMessage =>
                    //{

                    //},
                    RedirectToIdentityProvider = n =>
                    {
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
                        {
                            var id_token = n.OwinContext.Authentication.User.FindFirst("id_token")?.Value;
                            n.ProtocolMessage.IdTokenHint = id_token;
                        }

                        return(Task.FromResult(0));
                    }
                }
            });
            app.UseStageMarker(PipelineStage.Authenticate);
        }
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                // Sets the ClientId, authority, RedirectUri as obtained from web.config
                ClientId    = clientId,
                Authority   = authority,
                RedirectUri = redirectUri,
                // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
                PostLogoutRedirectUri = redirectUri,
                Scope = OpenIdConnectScope.OpenIdProfile,
                // ResponseType is set to request the id_token - which contains basic information about the signed-in user
                ResponseType = OpenIdConnectResponseType.IdToken,
                // ValidateIssuer set to false to allow personal and work accounts from any organization to sign in to your application
                // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name
                // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = false
                },
                // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = OnAuthenticationFailed
                }
            }
                );

            // Configure the db context, user manager and role manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);


            //var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
            //ApplicationUserManager manager1 = new ApplicationUserManager()

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                //LoginPath = new PathString("/App_Code/LoginProcess/ProcessLogin"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["globalTimeOut"])),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                },
                ExpireTimeSpan = TimeSpan.FromMinutes(Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["globalTimeOut"])),
                CookieSecure   = CookieSecureOption.Always,
                CookieHttpOnly = true,
                //CookieSameSite = SameSiteMode.Strict,
                //CookieDomain = "Tercera"
            });
            //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // 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(
            //    clientId: "",
            //    clientSecret: "");

            // //to enable signalR in our application.
            //app.MapSignalR();
        }
Example #53
0
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });

            //app.UseCookieAuthentication(new CookieAuthenticationOptions
            //{
            //    AuthenticationType = CookieAuthenticationDefaults.AuthenticationType
            //});

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            // app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.

            // app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);


            //OpenIdConnectConfiguration CriConfig;

            //using (WebClient wc = new WebClient())
            //{
            //    var json = wc.DownloadString("https://intra.cri.epita.net/oidc/.well-known/openid-configuration");
            //    CriConfig = new OpenIdConnectConfiguration(json);
            //}


            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
            {
                Authority    = "https://intra.cri.epita.net/oidc",
                RedirectUri  = "http://localhost:8000/complete/epita/",
                CallbackPath = new PathString("/Home"),
                ClientId     = "031021",
                ClientSecret = "97593354782061112fdeab765fd8faf9694903adfd8fa2d345a46be1",
                Scope        = "epita openid profile email",
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                ResponseType       = "code",
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active
            });
        }
Example #54
0
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301883
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            var extranet_url = new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType = "extranet_sunchemical ",
                ClientId           = "bdbdbdbdbdbdbdb-c63f-476a-9bb0-0281a6d499b",
                ClientSecret       = "b46cb48f-c83b-4101-b907-bf040bb994b",
                RedirectUri        = "http://extranet_sunchemical.com/",
                ResponseType       = "code id_token",
                SaveTokens         = true,
                //UseTokenLifetime=true,
                PostLogoutRedirectUri     = "http://extranet_sunchemical.com/",
                RedeemCode                = true,
                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name"
                },
                Authority = "https://idp.eu-staging.safenetid.com/auth/realms/5M6NSWEHFK-STA"
            };

            var internetconfig = new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType = "sunchemical",
                ClientId           = "abababababababa",
                ClientSecret       = "abavavavavavavavava",
                RedirectUri        = "http://sunchemical.com/",
                ResponseType       = "code id_token",
                SaveTokens         = true,
                //UseTokenLifetime=true,
                PostLogoutRedirectUri     = "http://sunchemical.com/",
                RedeemCode                = true,
                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name"
                },
                Authority = "https://idp.eu-staging.safenetid.com/auth/realms/8AFDSD3FK-STA"
            };


            app.UseOpenIdConnectAuthentication(extranet_url);
            app.UseOpenIdConnectAuthentication(internetconfig);


            System.Net.ServicePointManager.ServerCertificateValidationCallback +=
                delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                         System.Security.Cryptography.X509Certificates.X509Chain chain,
                         System.Net.Security.SslPolicyErrors sslPolicyErrors)
            {
                return(true);    // **** Always accept
            };


            //// Configure the db context, user manager and signin manager to use a single instance per request
            //app.CreatePerOwinContext(ApplicationDbContext.Create);
            //app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            //app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            //// Enable the application to use a cookie to store information for the signed in user
            //// and to use a cookie to temporarily store information about a user logging in with a third party login provider
            //// Configure the sign in cookie
            //app.UseCookieAuthentication(new CookieAuthenticationOptions
            //{
            //    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            //    LoginPath = new PathString("/Account/Login"),
            //    Provider = new CookieAuthenticationProvider
            //    {
            //        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            //            validateInterval: TimeSpan.FromMinutes(30),
            //            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            //    }
            //});
            //// Use a cookie to temporarily store information about a user logging in with a third party login provider
            //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            //// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            //app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            //// Enables the application to remember the second login verification factor such as phone or email.
            //// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            //// This is similar to the RememberMe option when you log in.
            //app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            //// 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(new GoogleOAuth2AuthenticationOptions()
            ////{
            ////    ClientId = "",
            ////    ClientSecret = ""
            ////});
        }
Example #55
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            var authProvider = new CookieAuthenticationProvider
            {
                OnResponseSignIn = ctx =>
                {
                    ctx.Identity = StartupAuth.InitAuth(ctx);
                }
            };
            var cookieOptions = new CookieAuthenticationOptions
            {
                Provider = authProvider
            };

            app.UseCookieAuthentication(cookieOptions);

            // Required for AAD B2C
            // Configure OpenID Connect middleware for each policy
            app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(ProfilePolicyId));
            app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SusiPolicyId));
            app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(ResetPolicyId));

            if (UnifiedSusiPolicyId != null)
            {
                // Required for B2C Unified
                app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(UnifiedSusiPolicyId));
                app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(UnifiedProfilePolicyId));
            }

            // Required for AAD B2E Multitenant
            OpenIdConnectAuthenticationOptions multiOptions = new OpenIdConnectAuthenticationOptions
            {
                Authority     = aadInstanceMulti,
                ClientId      = clientIdB2B,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed       = AuthenticationFailed,
                    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));
                    },
                },
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                },
                AuthenticationType = WutAuthTypes.B2EMulti,
            };

            app.UseOpenIdConnectAuthentication(multiOptions);

            // Required for AAD Host Tenant/B2B
            OpenIdConnectAuthenticationOptions b2bOptions = new OpenIdConnectAuthenticationOptions
            {
                Authority     = string.Format(aadInstanceB2B, tenantB2B),
                ClientId      = clientIdB2B,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed       = AuthenticationFailed,
                    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));
                    },
                },
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                },
                AuthenticationType = WutAuthTypes.B2B,
            };

            app.UseOpenIdConnectAuthentication(b2bOptions);
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            string clientId        = ConfigurationManager.AppSettings["ida:ClientID"];
            string appKey          = ConfigurationManager.AppSettings["ida:Password"];
            string graphResourceID = "https://graph.windows.net";
            //fixed address for multitenant apps in the public cloud
            string Authority = "https://login.windows.net/common/";

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions {
            });

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId  = clientId,
                Authority = Authority,
                TokenValidationParameters = new System.IdentityModel.Tokens.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()
                {
                    AuthorizationCodeReceived = (context) =>
                    {
                        var code = context.Code;

                        ClientCredential credential = new ClientCredential(clientId, appKey);
                        string tenantID             = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                        string signedInUserID       = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                        AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantID), new EFADALTokenCache(signedInUserID));
                        AuthenticationResult result       = authContext.AcquireTokenByAuthorizationCode(
                            code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceID);

                        return(Task.FromResult(0));
                    },
                    RedirectToIdentityProvider = (context) =>
                    {
                        // 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;
                        return(Task.FromResult(0));
                    },
                    // we use this notification for injecting our custom logic
                    SecurityTokenValidated = (context) =>
                    {
                        // retriever caller data from the incoming principal
                        string issuer   = context.AuthenticationTicket.Identity.FindFirst("iss").Value;
                        string UPN      = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value;
                        string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

                        if (
                            // the caller comes from an admin-consented, recorded issuer
                            (db.Tenants.FirstOrDefault(a => ((a.IssValue == issuer) && (a.AdminConsented))) == null)
                            // the caller is recorded in the db of users who went through the individual onboardoing
                            && (db.Users.FirstOrDefault(b => ((b.UPN == UPN) && (b.TenantID == tenantID))) == null)
                            )
                        {
                            // the caller was neither from a trusted issuer or a registered user - throw to block the authentication flow
                            throw new System.IdentityModel.Tokens.SecurityTokenValidationException();
                        }
                        return(Task.FromResult(0));
                    },
                    AuthenticationFailed = (context) =>
                    {
                        context.OwinContext.Response.Redirect("/Home/Error");
                        context.HandleResponse();     // Suppress the exception
                        return(Task.FromResult(0));
                    }
                }
            });
        }
Example #57
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            var authProvider = new CookieAuthenticationProvider
            {
                OnResponseSignIn = ctx =>
                {
                    var task = Task.Run(async() => {
                        await AuthInit(ctx);
                    });
                    task.Wait();
                },
                OnValidateIdentity = ctx =>
                {
                    //good spot to troubleshoot nonces, etc...
                    return(Task.FromResult(0));
                }
            };

            var cookieOptions = new CookieAuthenticationOptions
            {
                Provider      = authProvider,
                CookieManager = new Microsoft.Owin.Host.SystemWeb.SystemWebChunkingCookieManager()
            };

            app.UseCookieAuthentication(cookieOptions);
            Utils.Authority    = Settings.AdminAuthority;
            Utils.ClientId     = Settings.LabAdminClientId;
            Utils.ClientSecret = Settings.LabAdminSecret;

            OpenIdConnectAuthenticationOptions LabAdminOptions = new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType    = CustomAuthType.LabAdmin,
                ClientId              = Settings.LabAdminClientId,
                Authority             = Settings.AdminAuthority,
                PostLogoutRedirectUri = "/",
                Notifications         = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed      = AuthFailed,
                    AuthorizationCodeReceived = async(context) =>
                    {
                        await Utils.OnAuthorizationCodeReceived(context);
                        await AuthInit(context);
                    },
                    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));
                    },
                },
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                }
            };

            app.UseOpenIdConnectAuthentication(LabAdminOptions);

            OpenIdConnectAuthenticationOptions LabUserOptions = new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType    = CustomAuthType.LabUser,
                ClientId              = Settings.LabUserClientId,
                Authority             = Settings.UserAuthority,
                PostLogoutRedirectUri = "/",
                Notifications         = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed       = AuthFailed,
                    RedirectToIdentityProvider = (context) =>
                    {
                        string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                        context.ProtocolMessage.RedirectUri           = appBaseUrl + "/";
                        context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
                        context.ProtocolMessage.Prompt = "login";

                        if (context.Request.Path.Value == "/account/refresh")
                        {
                            context.ProtocolMessage.LoginHint = context.Request.User.Identity.Name;
                            context.ProtocolMessage.Prompt    = "none";
                        }
                        return(Task.FromResult(0));
                    },
                },
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                }
            };

            app.UseOpenIdConnectAuthentication(LabUserOptions);
        }
        /// <summary>
        /// Configures authentication for the application.
        /// </summary>
        /// <param name="app">The application to be configured.</param>
        public void ConfigureAuth(IAppBuilder app)
        {
            IExplorerProvider provider = UnityConfig.Container.Resolve <IExplorerProvider>();

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId  = provider.Configuration.ApplicationId,
                Authority = $"{provider.Configuration.ActiveDirectoryEndpoint}/common",

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = (context) =>
                    {
                        // Track the exceptions using the telemetry provider.
                        provider.Telemetry.TrackException(context.Exception);

                        // Pass in the context back to the app
                        context.OwinContext.Response.Redirect($"/Home/Error?message={context.Exception.Message}");

                        // Suppress the exception
                        context.HandleResponse();

                        return(Task.FromResult(0));
                    },
                    AuthorizationCodeReceived = async(context) =>
                    {
                        string userTenantId         = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                        string signedInUserObjectId = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

                        IGraphClient client = new GraphClient(provider, userTenantId);

                        List <RoleModel> roles = await client.GetDirectoryRolesAsync(signedInUserObjectId).ConfigureAwait(false);

                        foreach (RoleModel role in roles)
                        {
                            context.AuthenticationTicket.Identity.AddClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role, role.DisplayName));
                        }

                        bool isPartnerUser = userTenantId.Equals(
                            provider.Configuration.ApplicationTenantId, StringComparison.CurrentCultureIgnoreCase);

                        string customerId = string.Empty;

                        if (!isPartnerUser)
                        {
                            try
                            {
                                Customer c = await provider.PartnerOperations.GetCustomerAsync(userTenantId).ConfigureAwait(false);
                                customerId = c.Id;
                            }
                            catch (PartnerException ex)
                            {
                                if (ex.ErrorCategory != PartnerErrorCategory.NotFound)
                                {
                                    throw;
                                }
                            }
                        }

                        if (isPartnerUser || !string.IsNullOrWhiteSpace(customerId))
                        {
                            // Add the customer identifier to the claims
                            context.AuthenticationTicket.Identity.AddClaim(new System.Security.Claims.Claim("CustomerId", userTenantId));
                        }
                    },
                    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));
                    }
                },
                TokenValidationParameters = new TokenValidationParameters
                {
                    SaveSigninToken = true,
                    ValidateIssuer  = false
                }
            });
        }
Example #59
0
        public void Run(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            //app.UseCompositeAuthentication(new CompositionAuthenticationOptions
            //{
            //    AuthenticationType = "Composite",
            //    CompositeAuthenticationTypes = new string[]
            //    {
            //        "Certificate",
            //        "Cookies"
            //    }
            //});

            //app.UseClientCertificateAuthentication(new ClientCertificateAuthenticationOptions
            //{
            //    AuthenticationType = "Certificate",
            //    AuthenticationMode = AuthenticationMode.Passive,
            //    Validator = new TestCertificateValidator("issuer")
            //});

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

            app.UseOpenIdConnectAuthentication(new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationOptions
            {
                AuthenticationType = "oidc",
                Authority          = this.identityServerUri,
                ClientId           = "idadmin_client",
                RedirectUri        = this.identityAdminUri,
                ResponseType       = "id_token",
                UseTokenLifetime   = false,
                Scope = "openid idadmin",
                SignInAsAuthenticationType = "Cookies",
                Notifications = new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = n =>
                    {
                        // Add the returned id token from the IdP to the returned ticket so that
                        // it can be retrieved later when we logout (see below)
                        n.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                        return(Task.FromResult(0));
                    },
                    RedirectToIdentityProvider = async n =>
                    {
                        // If we redirect to the IdP to perform a logout, then
                        // before the redirect clear the associated cookie, and send the id_token as a hint
                        // so that the user name can be displayed by the IdP
                        if (n.ProtocolMessage.RequestType == Microsoft.IdentityModel.Protocols.OpenIdConnectRequestType.LogoutRequest)
                        {
                            var result = await n.OwinContext.Authentication.AuthenticateAsync("Cookies");
                            if (result != null)
                            {
                                var id_token = result.Identity.Claims.GetValue("id_token");
                                if (id_token != null)
                                {
                                    n.ProtocolMessage.IdTokenHint           = id_token;
                                    n.ProtocolMessage.PostLogoutRedirectUri = this.identityAdminUri;
                                }
                            }
                        }
                    }
                }
            });

            var options = new EntityFrameworkAdminOptionsService(
                this.apiOnly).GetAdminOptions();

            app.UseIdentityAdmin(options);
        }
Example #60
-1
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" });
            app.UseOpenIdConnectAuthentication(this.OpenIdConnectOptions());
            app.Use(typeof(StatusCodeLoggingMiddleware));
            app.UseNancy();
            app.UseStageMarker(PipelineStage.MapHandler);
        }