public override void Configure(IAppBuilder app) { if (String.IsNullOrEmpty(FederationSettings.MetadataAddress)) { throw new ArgumentException("Missing federation declaration in config", "FederationMetadataAddress"); } if (String.IsNullOrEmpty(FederationSettings.Realm)) { throw new ArgumentException("Missing federation declaration in config", "FederationRealm"); } app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions { MetadataAddress = FederationSettings.MetadataAddress, Wtrealm = FederationSettings.Realm, Notifications = new WsFederationAuthenticationNotifications() { RedirectToIdentityProvider = (context) => { if (context.OwinContext.Response.StatusCode == (int)HttpStatusCode.Unauthorized && context.Request.Headers.ContainsKey("AuthNoRedirect")) { context.HandleResponse(); } return Task.FromResult(0); } } }); }
public void ConfigAuth(IAppBuilder app) { // Enable cross site api requests app.UseCors(CorsOptions.AllowAll); app.SetDefaultSignInAsAuthenticationType("ServerCookie"); // Insert a new cookies middleware in the pipeline to store // the user identity returned by the external identity provider. app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationMode = AuthenticationMode.Passive, AuthenticationType = "ServerCookie", ExpireTimeSpan = TimeSpan.FromMinutes(5), LoginPath = new PathString(Paths.LoginPath), LogoutPath = new PathString(Paths.LogoutPath), }); // Enable the External Sign In Cookie. app.SetDefaultSignInAsAuthenticationType("External"); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "External", AuthenticationMode = AuthenticationMode.Passive, CookieName = CookieAuthenticationDefaults.CookiePrefix + "External", ExpireTimeSpan = TimeSpan.FromMinutes(5), }); // Enable Google authentication. // app.UseGoogleAuthentication(); app.UseGoogleAuthentication( clientId: "972173821914-o8c0p9k9rud1rkhgojao78mopbn0ai75.apps.googleusercontent.com", clientSecret: "1URA1emGNfoKN5a2HB57gts7"); /** To put the resource server on the same server, this is way to apply authentication on a particular path app.Map("/api", map => { var configuration = new HttpConfiguration(); configuration.MapHttpAttributeRoutes(); configuration.EnsureInitialized(); map.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { AuthenticationMode = AuthenticationMode.Active }); map.UseWebApi(configuration); }); * **/ }
// 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 Configuration(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType("ExternalCookie"); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "ExternalCookie", AuthenticationMode = AuthenticationMode.Passive, CookieName = ".AspNet.ExternalCookie", ExpireTimeSpan = TimeSpan.FromMinutes(5), }); var options = new GitHubAuthenticationOptions { ClientId = "your cliend in", ClientSecret = "your client secret", Provider = new GitHubAuthenticationProvider { OnAuthenticated = context => { context.Identity.AddClaim(new Claim("urn:token:github", context.AccessToken)); return Task.FromResult(true); } } }; app.UseGitHubAuthentication(options); app.MapSignalR(); }
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); } } }); }
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" //} }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType("ExternalCookie"); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "ExternalCookie", AuthenticationMode = AuthenticationMode.Passive, CookieName = ".AspNet.ExternalCookie", ExpireTimeSpan = TimeSpan.FromMinutes(5), }); var options = new GitHubAuthenticationOptions { ClientId = ConfigurationManager.AppSettings["ClientId"], ClientSecret = ConfigurationManager.AppSettings["ClientSecret"], Provider = new GitHubAuthenticationProvider { OnAuthenticated = context => { context.Identity.AddClaim(new Claim("urn:github:token", context.AccessToken)); context.Identity.AddClaim(new Claim("urn:github:username", context.UserName)); return Task.FromResult(true); } } }; options.Scope.Add("user:email"); options.Scope.Add("repo"); app.UseGitHubAuthentication(options); }
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); } } }); }
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); } } }); }
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 ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); var authServicesOptions = new KentorAuthServicesAuthenticationOptions(false) { SPOptions = CreateSPOptions() //SPOptions = new SPOptions //{ // EntityId = new EntityId(localMetaUri), // ReturnUrl = returnUrl, // WantAssertionsSigned = true //}, //AuthenticationType = adfsType, //Caption = adfsType, }; Uri metadataURI = new Uri(metaUri); var idp = new IdentityProvider(new EntityId(entityId), authServicesOptions.SPOptions) { AllowUnsolicitedAuthnResponse = true, Binding = Saml2BindingType.HttpRedirect, MetadataLocation = metadataURI.ToString(), LoadMetadata = true }; //idp.SigningKeys.AddConfiguredKey( // new X509Certificate2( // HostingEnvironment.MapPath( // "~/App_Data/AzureApp_signing.cer"))); authServicesOptions.IdentityProviders.Add(idp); app.UseKentorAuthServicesAuthentication(authServicesOptions); }
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 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(); }); }
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 } }); }
public override void Configure(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions() { AuthenticationType = CookieAuthenticationDefaults.AuthenticationType, LoginPath = new PathString("/Home/WindowsLogin"), Provider = new Microsoft.Owin.Security.Cookies.CookieAuthenticationProvider() { OnApplyRedirect = context => { if (context.Request.Path != WindowsAuthenticationOptions.DefaultRedirectPath && !context.Request.Headers.ContainsKey("AuthNoRedirect")) { context.Response.Redirect(context.RedirectUri); } } } }); app.UseWindowsAuthentication(new WindowsAuthenticationOptions { GetClaimsForUser = username => { return GetClaimsForUser(username); } }); }
public void Configuration(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider() }); app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions { MetadataAddress = String.Format("https://{0}/wsfed/{1}/FederationMetadata/2007-06/FederationMetadata.xml", ConfigurationManager.AppSettings["auth0:Domain"], ConfigurationManager.AppSettings["auth0:ClientId"]), Wtrealm = "urn:" + ConfigurationManager.AppSettings["auth0:ApplicationName"], Notifications = new WsFederationAuthenticationNotifications { SecurityTokenValidated = notification => { notification.AuthenticationTicket.Identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Auth0")); return Task.FromResult(true); } } }); }
private void ConfigureAuth(IAppBuilder app) { var cookieOptions = new CookieAuthenticationOptions { LoginPath = new PathString("/Account/Login"), }; app.UseCookieAuthentication(cookieOptions); app.SetDefaultSignInAsAuthenticationType(cookieOptions.AuthenticationType); /* app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions { ClientId = "", ClientSecret = "" }); */ app.UseEnumAuthentication(new EnumAuthenticationOptions { //put here your client id and client secret ClientId = "", ClientSecret = "" }); }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { const string SignInAsAuthenticationType = "PingFederate"; app.SetDefaultSignInAsAuthenticationType(SignInAsAuthenticationType); // Enable the application to use a cookie to store information for the signed in user app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = SignInAsAuthenticationType, LoginPath = new PathString("/Account/Login") }); // Use a cookie to temporarily store information about a user logging in with a third party login provider // app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); const string PingServerUrl = "https://your-ping-federate-server.com"; app.UsePingFederateAuthentication(new PingFederateAuthenticationOptions() { ClientId = "id", ClientSecret = "super_secret", PingFederateUrl = PingServerUrl, ////DiscoverMetadata = false, // Set to false to avoid discovering metatada, you need to set the Endpoints manually. (shown below) SignInAsAuthenticationType = SignInAsAuthenticationType, // if DiscoveryMetadata = false then uncomment this ////Endpoints = new PingFederateAuthenticationOptions.PingFederateAuthenticationEndpoints() //// { //// AuthorizationEndpoint = PingServerUrl + PingFederateAuthenticationOptions.AuthorizationEndpoint, //// TokenEndpoint = PingServerUrl + PingFederateAuthenticationOptions.TokenEndpoint, //// UserInfoEndpoint = PingServerUrl + PingFederateAuthenticationOptions.UserInfoEndpoint //// } }); }
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, } }); }
public void Configuration(IAppBuilder app) { // use default sign in with application cookies app.SetDefaultSignInAsAuthenticationType("ApplicationCookie"); // set up the cookie aut app.UseCookieAuthentication(new CookieAuthenticationOptions() { AuthenticationType = "ApplicationCookie", LoginPath = new PathString("/api/account/ntlmlogin"), ReturnUrlParameter = "redirectUrl", Provider = new CookieAuthenticationProvider() { OnApplyRedirect = ctx => { if (!ctx.Request.IsNtlmAuthenticationCallback()) { ctx.Response.Redirect(ctx.RedirectUri); } } } }); // Enable NTLM authentication app.UseNtlmAuthentication(Options); // configure web api var config = new HttpConfiguration(); config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }); app.UseWebApi(config); }
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); }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = _appConfig.ClientID, Authority = Constants.Authentication.CommonAuthority, PostLogoutRedirectUri = _appConfig.PostLogoutRedirectURI, 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() { // 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(_appConfig.ClientID,_appConfig.ClientSecret); 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.microsoftonline.com/{0}", tenantID), new ADALTokenCache(signedInUserID)); AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode( code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, Constants.Authentication.GraphServiceUrl); 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) => { System.Diagnostics.Trace.TraceError(context.Exception.ToString()); string redirectPath = string.Format("/Error/?errorMessage={0}", context.Exception.Message); context.OwinContext.Response.Redirect(redirectPath); // context.OwinContext.Response.Redirect("/Error/Index"); context.HandleResponse(); // Suppress the exception return Task.FromResult(0); } } }); }
public void ConfigureAuth(IAppBuilder app) { string ClientId = ConfigurationManager.AppSettings["ClientID"]; string Authority = string.Format(ConfigurationManager.AppSettings["Authority"], ConfigurationManager.AppSettings["AADId"]); string AzureResourceManagerIdentifier = ConfigurationManager.AppSettings["AzureResourceManagerIdentifier"]; app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions { }); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = ClientId, Authority = Authority, 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; object obj = null; if (context.OwinContext.Environment.TryGetValue("DomainHint", out obj)) { string domainHint = obj as string; if (domainHint != null) { context.ProtocolMessage.SetParameter("domain_hint", domainHint); } } 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 = AzureResourceManagerIdentifier; return Task.FromResult(0); }, AuthorizationCodeReceived = (context) => { X509Certificate2 keyCredential = new X509Certificate2(HttpContext.Current.Server.MapPath (ConfigurationManager.AppSettings["KeyCredentialPath"]), "", X509KeyStorageFlags.MachineKeySet); ClientAssertionCertificate clientAssertion = new ClientAssertionCertificate(ClientId, keyCredential); string signedInUserUniqueName = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value .Split('#')[context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1]; var tokenCache = new ADALTokenCache(signedInUserUniqueName); tokenCache.Clear(); AuthenticationContext authContext = new AuthenticationContext(Authority, tokenCache); AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode( context.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), clientAssertion); return Task.FromResult(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); } } }); }
private void ConfigureAuth(IAppBuilder app) { var cookieOptions = new CookieAuthenticationOptions { LoginPath = new PathString("/Member/Login") }; app.UseCookieAuthentication(cookieOptions); app.SetDefaultSignInAsAuthenticationType(cookieOptions.AuthenticationType); }
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); } } }); }
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 { // NOTE: [ap] different types of notifications AuthenticationFailed = context => { try { context.HandleResponse(); context.Response.Redirect("/Error?message=" + context.Exception.Message); return Task.FromResult(0); } catch (Exception ex) { throw; } }, // we use this notification for injecting our custom logic SecurityTokenValidated = (context) => { try { // retriever caller data from the incoming principal string issuer = context.AuthenticationTicket.Identity.FindFirst("iss").Value; string UPN = context.AuthenticationTicket.Identity.FindFirst(System.IdentityModel.Claims.ClaimTypes.Name).Value; string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; ClaimsIdentity claimsId = context.AuthenticationTicket.Identity; claimsId.AddClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role, "Admin", ClaimValueTypes.String)); return Task.FromResult(0); } catch (Exception ex) { throw; } }, } }); }
// This method is auto-detected by the OWIN pipeline. DO NOT RENAME IT! public static void Configuration(IAppBuilder app) { // Get config var config = Container.Kernel.Get<ConfigurationService>(); var auth = Container.Kernel.Get<AuthenticationService>(); // Setup telemetry var instrumentationKey = config.Current.AppInsightsInstrumentationKey; if (!string.IsNullOrEmpty(instrumentationKey)) { TelemetryConfiguration.Active.InstrumentationKey = instrumentationKey; } // Configure logging app.SetLoggerFactory(new DiagnosticsLoggerFactory()); // Remove X-AspNetMvc-Version header MvcHandler.DisableMvcResponseHeader = true; if (config.Current.RequireSSL) { // Put a middleware at the top of the stack to force the user over to SSL // if authenticated. app.UseForceSslWhenAuthenticated(config.Current.SSLPort); } // Get the local user auth provider, if present and attach it first Authenticator localUserAuther; if (auth.Authenticators.TryGetValue(Authenticator.GetName(typeof(LocalUserAuthenticator)), out localUserAuther)) { // Configure cookie auth now localUserAuther.Startup(config, app); } // Attach external sign-in cookie middleware app.SetDefaultSignInAsAuthenticationType(AuthenticationTypes.External); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = AuthenticationTypes.External, AuthenticationMode = AuthenticationMode.Passive, CookieName = ".AspNet." + AuthenticationTypes.External, ExpireTimeSpan = TimeSpan.FromMinutes(5) }); // Attach non-cookie auth providers var nonCookieAuthers = auth .Authenticators .Where(p => !String.Equals( p.Key, Authenticator.GetName(typeof(LocalUserAuthenticator)), StringComparison.OrdinalIgnoreCase)) .Select(p => p.Value); foreach (var auther in nonCookieAuthers) { auther.Startup(config, app); } }
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); } } }); }
/* * Configure the OWIN middleware */ public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { // Generate the metadata address using the tenant and policy information MetadataAddress = String.Format(AadInstance, Tenant, DefaultPolicy), // These are standard OpenID Connect parameters, with values pulled from web.config ClientId = ClientId, RedirectUri = RedirectUri, PostLogoutRedirectUri = RedirectUri, // Specify the callbacks for each type of notifications Notifications = new OpenIdConnectAuthenticationNotifications { RedirectToIdentityProvider = OnRedirectToIdentityProvider, AuthorizationCodeReceived = OnAuthorizationCodeReceived, AuthenticationFailed = OnAuthenticationFailed, }, // Specify the claims to validate TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name" }, // Specify the scope by appending all of the scopes requested into one string (separated by a blank space) Scope = $"openid profile offline_access {ReadTasksScope} {WriteTasksScope}" } ); //var tenant = ConfigurationManager.AppSettings["ida:Tenant"]; //app.UseWindowsAzureActiveDirectoryBearerAuthentication( // new WindowsAzureActiveDirectoryBearerAuthenticationOptions // { // Audience = "false",//ConfigurationManager.AppSettings["Audience"], // Tenant = tenant // }); }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); // Custom middleware initialization app.UseOAuth2CodeRedeemer( new OAuth2CodeRedeemerOptions { ClientId = clientId, ClientSecret = appKey, RedirectUri = redirectUri } ); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { // The `Authority` represents the v2.0 endpoint - https://login.microsoftonline.com/common/v2.0 // The `Scope` describes the initial permissions that your app will need. See https://azure.microsoft.com/documentation/articles/active-directory-v2-scopes/ ClientId = clientId, Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, "common", "/v2.0"), RedirectUri = redirectUri, Scope = "openid profile offline_access Mail.Read", PostLogoutRedirectUri = redirectUri, TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, // In a real application you would use IssuerValidator for additional checks, like making sure the user's organization has signed up for your app. // IssuerValidator = (issuer, token, tvp) => // { // //if(MyCustomTenantValidation(issuer)) // return issuer; // //else // // throw new SecurityTokenInvalidIssuerException("Invalid issuer"); // }, }, Notifications = new OpenIdConnectAuthenticationNotifications { AuthorizationCodeReceived = OnAuthorization, AuthenticationFailed = OnAuthenticationFailed } }); }
public void ConfigureAuth(IAppBuilder app) { app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { ClientId = _clientId, ClientSecret = _clientSecret, Authority = _authority, RedirectUri = _redirectUri, ResponseType = OpenIdConnectResponseType.CodeIdToken, Scope = OpenIdConnectScope.OpenIdProfile + " " + OpenIdConnectScope.Email, TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name" }, Notifications = new OpenIdConnectAuthenticationNotifications { AuthorizationCodeReceived = async n => { // Exchange code for access and ID tokens var tokenClient = new TokenClient($"{_authority}/oauth2/v1/token", _clientId, _clientSecret); var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(n.Code, _redirectUri); if (tokenResponse.IsError) { throw new Exception(tokenResponse.Error); } var userInfoClient = new UserInfoClient($"{_authority}/oauth2/v1/userinfo"); var userInfoResponse = await userInfoClient.GetAsync(tokenResponse.AccessToken); var claims = new List <Claim>(userInfoResponse.Claims) { new Claim("id_token", tokenResponse.IdentityToken), new Claim("access_token", tokenResponse.AccessToken) }; n.AuthenticationTicket.Identity.AddClaims(claims); }, }, }); }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); // Custom middleware initialization. This is activated when the code obtained from a code_grant is present in the querystring (&code=<code>). app.UseOAuth2CodeRedeemer( new OAuth2CodeRedeemerOptions { ClientId = AuthenticationConfig.ClientId, ClientSecret = AuthenticationConfig.ClientSecret, RedirectUri = AuthenticationConfig.RedirectUri } ); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { // The `Authority` represents the v2.0 endpoint - https://login.microsoftonline.com/common/v2.0 Authority = AuthenticationConfig.Authority, ClientId = AuthenticationConfig.ClientId, RedirectUri = AuthenticationConfig.RedirectUri, PostLogoutRedirectUri = AuthenticationConfig.RedirectUri, Scope = AuthenticationConfig.BasicSignInScopes + " Mail.Read", // a basic set of permissions for user sign in & profile access "openid profile offline_access" TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, // In a real application you would use IssuerValidator for additional checks, like making sure the user's organization has signed up for your app. // IssuerValidator = (issuer, token, tvp) => // { // //if(MyCustomTenantValidation(issuer)) // return issuer; // //else // // throw new SecurityTokenInvalidIssuerException("Invalid issuer"); // }, //NameClaimType = "name", }, Notifications = new OpenIdConnectAuthenticationNotifications() { AuthorizationCodeReceived = OnAuthorizationCodeReceived, AuthenticationFailed = OnAuthenticationFailed, } }); }
public void ConfigureAuth(IAppBuilder app) { // configure the authentication type & settings app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); // configure the OWIN OpenId Connect options app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { ClientId = SettingsHelper.ClientId, Authority = SettingsHelper.AzureADAuthority, 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(SettingsHelper.ClientId, SettingsHelper.ClientSecret); string userObjectId = context.AuthenticationTicket.Identity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value; // use the OpenID Connect code to obtain access token & refresh token... // save those in a persistent store... EFADALTokenCache sampleCache = new EFADALTokenCache(userObjectId); AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, sampleCache); // 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, SettingsHelper.AzureAdGraphResourceId); // successful auth return(Task.FromResult(0)); }, AuthenticationFailed = (context) => { context.HandleResponse(); return(Task.FromResult(0)); } }, TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuer = false } }); }
/// <summary> /// Configure Authentication to authenticate the user. /// </summary> /// <param name="app">Initializes a new instance of the type app builder.</param> /// <param name="container">dependency injection container.</param> public void ConfigureAuth(IAppBuilder app, Autofac.IContainer container) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); var validUpns = ConfigurationManager.AppSettings["ValidUpns"] ?.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries) ?.Select(s => s.Trim()) ?? Array.Empty <string>(); app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions("AppLogin") { ClientId = clientId, Authority = authority, PostLogoutRedirectUri = postLogoutRedirectUri, Notifications = new OpenIdConnectAuthenticationNotifications() { SecurityTokenValidated = (context) => { var upnClaim = context?.AuthenticationTicket?.Identity?.Claims? .FirstOrDefault(c => c.Type == ClaimTypes.Upn); var upn = upnClaim?.Value; if (string.IsNullOrWhiteSpace(upn) || !validUpns.Contains(upn, StringComparer.OrdinalIgnoreCase)) { context.OwinContext.Response.Redirect("/Account/InvalidUser"); context.HandleResponse(); } return(Task.CompletedTask); }, RedirectToIdentityProvider = (context) => { if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication) { context.ProtocolMessage.Prompt = OpenIdConnectPrompt.Login; } return(Task.CompletedTask); }, }, }); AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Upn; }
// For more information on configuring authentication, please visit 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, Notifications = new OpenIdConnectAuthenticationNotifications { AuthenticationFailed = context => { context.HandleResponse(); context.Response.Redirect("/Error?message=" + context.Exception.Message); return(Task.FromResult(0)); } } }); // Enable the application to use bearer tokens to authenticate users // app.UseOAuthBearerTokens(OAuthOptions); // 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 = "" //}); }
public void Configuration(IAppBuilder app) { if (HttpContext.Current.IsDebuggingEnabled) { RedirectUri = "http://localhost:44302/"; } app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = AppId, Authority = "https://login.microsoftonline.com/common/v2.0", Scope = "openid offline_access profile email " + string.Join(" ", Scopes), RedirectUri = RedirectUri, PostLogoutRedirectUri = "/", TokenValidationParameters = new TokenValidationParameters { // For demo purposes only, see below ValidateIssuer = false // In a real multitenant app, you would add logic to determine whether the // issuer was from an authorized tenant //ValidateIssuer = true, //IssuerValidator = (issuer, token, tvp) => //{ // if (MyCustomTenantValidation(issuer)) // { // return issuer; // } // else // { // throw new SecurityTokenInvalidIssuerException("Invalid issuer"); // } //} }, Notifications = new OpenIdConnectAuthenticationNotifications { AuthenticationFailed = OnAuthenticationFailed, AuthorizationCodeReceived = OnAuthorizationCodeReceived } } ); }
public void Configuration(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType("ApplicationCookie"); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "ApplicationCookie", LoginPath = new PathString("/Account/Login"), }); //app.UseExternalSignInCookie("ExternalCookie"); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "", // ClientSecret = "", //}); }
public void ConfigureAuth(IAppBuilder app) { //ApplicationDbContext db = new ApplicationDbContext(); app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); //Authentication settings if (!string.IsNullOrEmpty(AzureADSettings.TenantId)) { OpenIdHelper.UseWithAzureAD(app); } else { OpenIdHelper.UseWithADFS(app); } }
public void ConfigureOAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(DefaultAuthenticationTypes.ExternalCookie); OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), Provider = new SimpleAuthorizationServerProvider() }; // Token Generation app.UseOAuthAuthorizationServer(OAuthServerOptions); app.UseOAuthBearerAuthentication(OAuthBearerOptions); }
public void Configuration(IAppBuilder app) { ApplicationConfig.RegisterConfig("development"); app.SetDefaultSignInAsAuthenticationType("ExternalCookie"); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "ExternalCookie", AuthenticationMode = AuthenticationMode.Active, CookieName = ".AspNet.ExternalCookie", LoginPath = new PathString("/Account/AuthorizeSSO"), ExpireTimeSpan = TimeSpan.FromMinutes(5) }); app.UseCloudFoundryOpenIdConnect(ApplicationConfig.Configuration, "CloudFoundry", ApplicationConfig.LoggerFactory); // AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier; }
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)); } } }); }
public void ConfigureAuth(IAppBuilder app) { var cookieName = ConfigurationManager.AppSettings["ApplicationName"].ToString(); var cookieOptions = new CookieAuthenticationOptions { LoginPath = new PathString("/Account/Login"), AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, SlidingExpiration = false, ExpireTimeSpan = TimeSpan.FromHours(24), CookieName = cookieName }; app.SetDefaultSignInAsAuthenticationType(cookieOptions.AuthenticationType); app.UseCookieAuthentication(cookieOptions); AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier; }
public void Configuration(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType("ExternalCookie"); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "ExternalCookie", AuthenticationMode = AuthenticationMode.Passive, CookieName = ".AspNet.ExternalCookie", ExpireTimeSpan = TimeSpan.FromMinutes(5), }); IAuthOptionsFactory authOptions = new AuthOptionsFactory(); app.UseMicrosoftAccountAuthentication(authOptions.GetMicrosoftAuthOptions()); app.UseGoogleAuthentication(authOptions.GetGoogleAuthOptions()); app.UseGitHubAuthentication(authOptions.GetGithubAuthOptions()); app.UseFacebookAuthentication(authOptions.GetFacebookAuthOptions()); app.UseLinkedInAuthentication(authOptions.GetLinkedinAuthOptions()); }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "ApplicationCookie", LoginPath = new PathString("/account/login") }); // Enable the External Sign In Cookie. app.SetDefaultSignInAsAuthenticationType("External"); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "External", AuthenticationMode = AuthenticationMode.Passive, CookieName = CookieAuthenticationDefaults.CookiePrefix + "External", ExpireTimeSpan = TimeSpan.FromMinutes(5), }); }
public void Configuration(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOktaMvc(new OktaMvcOptions() { OktaDomain = ConfigurationManager.AppSettings["okta:OktaDomain"], ClientId = ConfigurationManager.AppSettings["okta:ClientId"], ClientSecret = ConfigurationManager.AppSettings["okta:ClientSecret"], RedirectUri = ConfigurationManager.AppSettings["okta:RedirectUri"], PostLogoutRedirectUri = ConfigurationManager.AppSettings["okta:PostLogoutRedirectUri"], Scope = new List <string> { "openid", "profile", "email" }, }); }
private void OpenIdConfiguration(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication ( new OpenIdConnectAuthenticationOptions { ClientId = strClientId, Authority = strAuthority, PostLogoutRedirectUri = strRedirectUri } ); app.UseStageMarker(PipelineStage.Authenticate); }
public void ConfigurePowerBI(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions { }); //app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); //app.UseCookieAuthentication(new CookieAuthenticationOptions { }); //app.UsePowerBIAuthentication((options) => //{ // options.ClientId = ConfigurationManager.AppSettings["powerbi:ClientId"]; // options.ClientSecret = ConfigurationManager.AppSettings["powerbi:ClientSecret"]; // options.SuccessRedirectUri = new System.Uri(ConfigurationManager.AppSettings["powerbi:RedirectUri"]); // options.Issuer = ConfigurationManager.AppSettings["powerbi:Issuer"]; // options.ValidateIssuer = false; // Set to true in a production scenario //}); }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = "818e9037-fc84-46f9-88dd-f8f4738f4e01",//"95dcbcfd-5a64-4efe-a5e3-f4ed2043c46c", // Authority = "https://login.microsoftonline.com/DeveloperTenant.onmicrosoft.com", // using the common endpoint for the multitenant scenarios. Authority = "https://login.microsoftonline.com/common", // code for taking control of the issuer validation logic TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters { // uncomment this assignment if you want to test sign in form a different tenant without coding custom issuer validation yet ValidateIssuer = false, // pseudo - code as a placeholder for your own issuer validation logic // IssuerValidator = (issuer, token, tvp) => // { // //if(db.Issuers.FirstOrDefault(b => (b.Issuer == issuer)) == null) // return issuer; // //else // // throw new SecurityTokenInvalidIssuerException("Invalid issuer"); // }, // this assignment makes the incoming Azure AD roles claims available for use with [Authorize] and IsInRole // RoleClaimType = "roles", // this assignment makes the incoming Azure AD groups claims available for use with [Authorize] and IsInRole // RoleClaimType = "groups", }, PostLogoutRedirectUri = "https://localhost:44300/", Notifications = new OpenIdConnectAuthenticationNotifications() { RedirectToIdentityProvider = (context) => { // uncomment the line below for triggering the admin consent flow at sign in time // context.ProtocolMessage.Prompt = "admin_consent"; return(Task.FromResult(0)); }, }, } ); }
/// <summary> /// Configures authentication. /// </summary> /// <param name="app">The application.</param> private void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { // Generate the metadata address using the tenant and policy information MetadataAddress = VeracityIntegrationOptions.MetaDataAddress, Authority = VeracityIntegrationOptions.Authority, ClientId = VeracityIntegrationOptions.ClientId, RedirectUri = VeracityIntegrationOptions.RedirectUri, PostLogoutRedirectUri = VeracityIntegrationOptions.PostLogoutRedirectUri, Notifications = new OpenIdConnectAuthenticationNotifications { AuthorizationCodeReceived = this.OnAuthorizationCodeReceivedAsync, AuthenticationFailed = this.OnAuthenticationFailed }, ResponseType = OpenIdConnectResponseType.CodeIdToken, TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, IssuerValidator = (issuer, token, tokenValidationParameters) => { if (issuer.StartsWith(VeracityIntegrationOptions.Issuer, System.StringComparison.OrdinalIgnoreCase)) { return(issuer); } throw new SecurityTokenInvalidIssuerException("Invalid issuer"); }, NameClaimType = "UserId" }, Scope = $"openid offline_access {VeracityIntegrationOptions.VeracityPlatformServiceScopes}" }); // set the OWIN pipeline stage to Authenticate - this allows for authorization to be set in web.config // e.g. To only allow authenticated users add the following // <authorization> // <deny users = "?" /> // </authorization> app.UseStageMarker(PipelineStage.Authenticate); }
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, RedirectUri = "https://localhost:44322/", PostLogoutRedirectUri = ConfigHelper.PostLogoutRedirectUri, TokenValidationParameters = new TokenValidationParameters { SaveSigninToken = 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(ConfigHelper.ClientId, ConfigHelper.AppKey); AuthenticationContext authContext = new AuthenticationContext(ConfigHelper.Authority, new ADALTokenCache(Util.GetSignedInUsersObjectIdFromClaims())); AuthenticationResult result = authContext.AcquireTokenByAuthorizationCodeAsync( code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, ConfigHelper.GraphResourceId).Result; return(System.Threading.Tasks.Task.FromResult(0)); }, AuthenticationFailed = context => { context.HandleResponse(); context.Response.Redirect("/Error/ShowError?signIn=true&errorMessage=" + context.Exception.Message); return(System.Threading.Tasks.Task.FromResult(0)); } } }); }
public void ConfigureAuth(IAppBuilder app) { // By default, the claims mapping will map claim names in the old format to accommodate older SAML applications. // 'http://schemas.microsoft.com/ws/2008/06/identity/claims/role' instead of 'roles' // This flag ensures that the ClaimsIdentity claims collection will be built from the claims in the token JwtSecurityTokenHandler.DefaultMapInboundClaims = false; app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = "65ea8d4b-24a0-4be1-b33c-151fa39f0ff1", Authority = "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/", // 72f988bf-86f1-41af-91ab-2d7cd011db47/", RedirectUri = "https://localhost:44326", PostLogoutRedirectUri = "https://localhost:44326", TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, NameClaimType = "upn", RoleClaimType = "roles", // The claim in the Jwt token where App roles are provided. }, Notifications = new OpenIdConnectAuthenticationNotifications() { AuthenticationFailed = context => { context.HandleResponse(); context.Response.Redirect("/Error/ShowError?signIn=true&errorMessage=" + context.Exception.Message); return(System.Threading.Tasks.Task.FromResult(0)); } } }); /*app.UseWindowsAzureActiveDirectoryBearerAuthentication( * new WindowsAzureActiveDirectoryBearerAuthenticationOptions * { * Audience = ConfigurationManager.AppSettings["ida:Audience"], * Tenant = ConfigurationManager.AppSettings["ida:Tenant"] * });*/ }
/* * Configure the OWIN middleware */ public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions { // ASP.NET web host compatible cookie manager CookieManager = new SystemWebChunkingCookieManager() }); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { // Generate the metadata address using the tenant and policy information MetadataAddress = String.Format(Globals.WellKnownMetadata, Globals.Tenant, Globals.DefaultPolicy), // These are standard OpenID Connect parameters, with values pulled from web.config ClientId = Globals.ClientId, RedirectUri = Globals.RedirectUri, PostLogoutRedirectUri = Globals.RedirectUri, // Specify the callbacks for each type of notifications Notifications = new OpenIdConnectAuthenticationNotifications { RedirectToIdentityProvider = OnRedirectToIdentityProvider, AuthorizationCodeReceived = OnAuthorizationCodeReceived, AuthenticationFailed = OnAuthenticationFailed, }, // Specify the claim type that specifies the Name property. TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name", ValidateIssuer = false }, // Specify the scope by appending all of the scopes requested into one string (separated by a blank space) Scope = $"openid profile offline_access {Globals.ReadTasksScope} {Globals.WriteTasksScope}", // ASP.NET web host compatible cookie manager CookieManager = new SystemWebCookieManager() } ); }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { // The `Authority` represents the Microsoft v2.0 authentication and authorization service. // The `Scope` describes the permissions that your app will need. See https://azure.microsoft.com/documentation/articles/active-directory-v2-scopes/ ClientId = appId, Authority = "https://login.microsoftonline.com/common/v2.0", PostLogoutRedirectUri = redirectUri, RedirectUri = redirectUri, Scope = "openid email profile offline_access " + graphScopes, TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false }, Notifications = new OpenIdConnectAuthenticationNotifications { AuthorizationCodeReceived = async(context) => { var code = context.Code; string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; TokenCache userTokenCache = new SessionTokenCache(signedInUserID, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication( appId, redirectUri, new ClientCredential(appSecret), userTokenCache, null); string[] scopes = graphScopes.Split(new char[] { ' ' }); AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes); UserScopes = result.Scopes; }, AuthenticationFailed = this.OnAuthenticationFailedAsync, } }); }
public void Configuration(IAppBuilder app) { // Configure Auth0 parameters string auth0Domain = ConfigurationManager.AppSettings["auth0:Domain"]; string auth0ClientId = ConfigurationManager.AppSettings["auth0:ClientId"]; string auth0ClientSecret = ConfigurationManager.AppSettings["auth0:ClientSecret"]; // Enable Kentor Cookie Saver middleware app.UseKentorOwinCookieSaver(); // Set Cookies as default authentication type app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = CookieAuthenticationDefaults.AuthenticationType, LoginPath = new PathString("/Account/Login") }); // Configure Auth0 authentication var options = new Auth0AuthenticationOptions() { Domain = auth0Domain, ClientId = auth0ClientId, ClientSecret = auth0ClientSecret, SaveIdToken = true, // Scope = { "openid", "profile" }, // If you want to request an access_token to pass to an API, then replace the audience below to // pass your API Identifier instead of the /userinfo endpoint Provider = new Auth0AuthenticationProvider() { OnApplyRedirect = context => { string userInfoAudience = $"https://{auth0Domain}/userinfo"; // string userInfoAudience = "http://localhost/lobbyapi"; string redirectUri = context.RedirectUri + "&audience=" + WebUtility.UrlEncode(userInfoAudience); context.Response.Redirect(redirectUri); } } }; app.UseAuth0Authentication(options); }
/// <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 { // //AuthenticationType = "AzureAd", //Caption = "Office 365", //AuthenticationMode = AuthenticationMode.Passive, //SignInAsAuthenticationType = signInAsType, // Sets the ClientId, authority, RedirectUri as obtained from web.config. ClientId = clientId, Authority = authority, RedirectUri = redirectUrl, // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page PostLogoutRedirectUri = redirectUrl, //Scope is the requested scope: OpenIdConnectScopes.OpenIdProfileis equivalent to the string 'openid profile': in the consent screen, this will result in 'Sign you in and read your profile' Scope = OpenIdConnectScopes.OpenIdProfile, // ResponseType is set to request the id_token - which contains basic information about the signed-in user ResponseType = OpenIdConnectResponseTypes.IdToken, // ValidateIssuer set to false to allow 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 or Id (example: contoso.onmicrosoft.com) // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters() { ValidateIssuer = true }, // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method Notifications = new OpenIdConnectAuthenticationNotifications { AuthenticationFailed = OnAuthenticationFailed } } ); }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = appId, Authority = "https://login.microsoftonline.com/common/v2.0", Scope = $"openid email profile offline_access {graphScopes}", RedirectUri = redirectUri, PostLogoutRedirectUri = redirectUri, // ResponseType = OpenIdConnectResponseType.Code,// Microsoft.Graph.ResponseType.None, TokenValidationParameters = new TokenValidationParameters { // For demo purposes only, see below ValidateIssuer = false // In a real multi-tenant app, you would add logic to determine whether the // issuer was from an authorized tenant //ValidateIssuer = true, //IssuerValidator = (issuer, token, tvp) => //{ // if (MyCustomTenantValidation(issuer)) // { // return issuer; // } // else // { // throw new SecurityTokenInvalidIssuerException("Invalid issuer"); // } //} }, Notifications = new OpenIdConnectAuthenticationNotifications { AuthenticationFailed = OnAuthenticationFailedAsync, AuthorizationCodeReceived = OnAuthorizationCodeReceivedAsync } } ); }
// public static readonly string authority = aadInstance + tenantId; public void ConfigureAuth(IAppBuilder app) { // Configure the db context, user manager and role manager to use a single instance per request app.CreatePerOwinContext(SilicusIdentityDbContext.Create); app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create); app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/CandidateLogin"), Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = clientId, Authority = authority, PostLogoutRedirectUri = postLogoutRedirectUri, RedirectUri = postLogoutRedirectUri, Notifications = new OpenIdConnectAuthenticationNotifications { AuthenticationFailed = context => { context.HandleResponse(); context.Response.Redirect("/Error?message=" + context.Exception.Message); return(Task.FromResult(0)); } } }); }
protected override void AttachToOwinApp(IGalleryConfigurationService config, IAppBuilder app) { var cookieSecurity = CookieSecureOption.Always; var options = new CookieAuthenticationOptions { AuthenticationType = AuthenticationTypes.LocalUser, AuthenticationMode = AuthenticationMode.Active, CookieHttpOnly = true, CookieSecure = cookieSecurity, LoginPath = new PathString("/users/account/LogOn"), ExpireTimeSpan = TimeSpan.FromHours(6), SlidingExpiration = true }; BaseConfig.ApplyToOwinSecurityOptions(options); app.UseCookieAuthentication(options); app.SetDefaultSignInAsAuthenticationType(AuthenticationTypes.LocalUser); }