private void SetNotifications() { Notifications = new OpenIdConnectAuthenticationNotifications() { RedirectToIdentityProvider = (context) => { Logger.Debug("*** RedirectToIdentityProvider"); return(Task.FromResult(0)); }, MessageReceived = (context) => { Logger.Debug("*** MessageReceived"); return(Task.FromResult(0)); }, SecurityTokenReceived = (context) => { Logger.Debug("*** SecurityTokenReceived"); return(Task.FromResult(0)); }, SecurityTokenValidated = (context) => { Logger.Debug("*** SecurityTokenValidated"); return(Task.FromResult(0)); }, AuthorizationCodeReceived = async notification => { await AccessTokenHandler.GetAccessToken(notification); }, AuthenticationFailed = (context) => { Logger.Debug("*** AuthenticationFailed"); return(Task.FromResult(0)); }, }; }
public void SetAuthenticationModeToPassiveWhenLoginModeIsSelfHosted() { var oktaMvcOptions = new OktaMvcOptions() { PostLogoutRedirectUri = "http://postlogout.com", OktaDomain = "http://myoktadomain.com", ClientId = "foo", ClientSecret = "bar", RedirectUri = "/redirectUri", Scope = new List <string> { "openid", "profile", "email" }, LoginMode = LoginMode.SelfHosted, }; var notifications = new OpenIdConnectAuthenticationNotifications { RedirectToIdentityProvider = null, }; var oidcOptions = OpenIdConnectAuthenticationOptionsBuilder.BuildOpenIdConnectAuthenticationOptions( oktaMvcOptions, notifications); oidcOptions.AuthenticationMode.Should().Be(AuthenticationMode.Passive); }
public void Configuration(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions() { CookieSecure = CookieSecureOption.Always }); app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); var options = new OpenIdConnectAuthenticationOptions { ClientId = clientAppId, Authority = authority, TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false }, RedirectUri = replyUrl }; var notifications = new OpenIdConnectAuthenticationNotifications { AuthorizationCodeReceived = AuthCodeReceived, AuthenticationFailed = AuthFailed, }; options.Notifications = notifications; app.UseOpenIdConnectAuthentication(options); }
public static void Configuration(IAppBuilder app) { var appConfiguration = SampleAppConfiguration.CreateFromConfigFile(prefix: "JayLabs"); var jwtOptions = SampleJwtOptions.JwtOptions; var jwtBearerOptions = new JwtBearerTokenAuthenticationOptions(jwtOptions); jwtBearerOptions.JwtBearerOptions.Provider = new SampleOAuthBearerAuthenticationProvider(); app.UseJwtBearerAuthenticationWithTokenProvider(jwtBearerOptions); var customProviderOptions = SampleOptionsHelper.CreateOptions(jwtOptions); app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions { AccessTokenFormat = jwtBearerOptions.JwtFormat, ApplicationCanDisplayErrors = true, Provider = new CustomOAuthProvider(customProviderOptions), //TODO JwtOptions is placeholder AuthorizeEndpointPath = new PathString("/authorize"), AllowInsecureHttp = appConfiguration.AllowInsecureHttp, AccessTokenProvider = new JwtBearerTokenProvider(jwtOptions) }); var createConsentOptions = new CreateConsentOptions { CreateConsentAsync = (response, redirectUri) => { var consentUrl = new Uri(string.Format("/consent?redirectUri={0}&consentParamName={1}", Uri.EscapeDataString(redirectUri.ToString()), Uri.EscapeDataString(customProviderOptions.HandleConsentOptions.ConsentParameterName)), UriKind.Relative); response.Redirect(consentUrl.ToString()); return(Task.FromResult(0)); } }; var consentBuilder = new ConsentBuilder(createConsentOptions, customProviderOptions.HandleConsentOptions, jwtOptions); var notifications = new OpenIdConnectAuthenticationNotifications { AuthorizationCodeReceived = consentBuilder.HandleOpenIdAuthorizationCodeAsync }; var openIdConnectOptions = new OpenIdConnectAuthenticationOptions { ClientId = appConfiguration.OpenIdClientId, Authority = appConfiguration.OpenIdAuthority, CallbackPath = new PathString("/openid"), Notifications = notifications, AuthenticationMode = AuthenticationMode.Active }; app.UseOpenIdConnectAuthentication(openIdConnectOptions); app.SetDefaultSignInAsAuthenticationType(OpenIdConnectAuthenticationDefaults.AuthenticationType); }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions() { CookieName = "SeparateClient" }); OpenIdConnectAuthenticationNotifications notifications = new OpenIdConnectAuthenticationNotifications() { AuthorizationCodeReceived = (context) => { // Obtain access token for the current application using the authorization code ClientCredential credential = new ClientCredential(context.Options.ClientId, context.Options.ClientSecret); string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; AuthenticationContext authContext = new AuthenticationContext(context.Options.Authority, new NaiveSessionCache(userObjectID, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase)); AuthenticationResult result = authContext.AcquireTokenByAuthorizationCodeAsync(context.ProtocolMessage.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, context.Options.ClientId).Result; // Obtain and cache access tokens for additional resources using the access token // from the application as an assertion UserAssertion userAssertion = new UserAssertion(result.AccessToken); AuthenticationResult serviceResult = authContext.AcquireTokenAsync(_serviceResourceId, credential, userAssertion).Result; AuthenticationResult graphResult = authContext.AcquireTokenAsync(_graphResourceId, credential, userAssertion).Result; return(Task.FromResult(0)); }, AuthenticationFailed = context => { context.HandleResponse(); context.Response.Redirect("/Home/Error?message=" + context.Exception.Message); return(Task.FromResult(0)); }, SecurityTokenValidated = context => { // Add custom claims here context.AuthenticationTicket.Identity.AddClaim(new Claim(ClaimTypes.Role, "Admin")); return(Task.FromResult(0)); } }; // If a domain has been configured, pass a domain hint to the identity provider to bypass home realm discovery if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ida:Domain"])) { notifications.RedirectToIdentityProvider = (context) => { context.ProtocolMessage.DomainHint = ConfigurationManager.AppSettings["ida:Domain"]; return(Task.FromResult(0)); }; } app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = _clientId, ClientSecret = _clientSecret, Authority = _authority, Notifications = notifications }); }
private static void AddOpenIdConnectAuthentication(IAppBuilder app, OktaMvcOptions options) { // Stop the default behavior of remapping JWT claim names to legacy MS/SOAP claim names JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); var notifications = new OpenIdConnectAuthenticationNotifications { RedirectToIdentityProvider = BeforeRedirectToIdentityProviderAsync, }; app.UseOpenIdConnectAuthentication(OpenIdConnectAuthenticationOptionsBuilder.BuildOpenIdConnectAuthenticationOptions(options, notifications)); }
public StepikOAuthAuthenticationOptions(string authenticationType, string scope, string relativeRedirectUri, Func <AuthorizationCodeReceivedNotification, Task> authorizationCodeReceived) : base(authenticationType) { Caption = authenticationType; RedirectUri = GetAbsoluteRedirectUri(relativeRedirectUri); CallbackPath = new PathString(relativeRedirectUri); AuthenticationMode = AuthenticationMode.Active; Scope = scope; ResponseType = "code"; Notifications = new OpenIdConnectAuthenticationNotifications(); Notifications.AuthorizationCodeReceived = authorizationCodeReceived; }
public static void UseOpenIdConnectAuthentications(IAppBuilder app, string signInAsType) { var options = new OpenIdConnectAuthenticationOptions { AuthenticationType = "icad", Caption = "Sign In", Scope = "openid email", ClientId =, Authority = "https://login.windows.net/common/", PostLogoutRedirectUri = "http://*****:*****@Options}", options); app.UseOpenIdConnectAuthentication(options); } }
public void ConfigureAuth(IAppBuilder app) { ApplicationDbContext db = new ApplicationDbContext(); app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); OpenIdConnectAuthenticationOptions options = new OpenIdConnectAuthenticationOptions(); options.ClientId = SettingsHelper.ClientId; options.Authority = SettingsHelper.AzureADAuthority; options.PostLogoutRedirectUri = SettingsHelper.LogoutAuthority; OpenIdConnectAuthenticationNotifications notifications = new OpenIdConnectAuthenticationNotifications(); notifications.AuthorizationCodeReceived = (context) => { string code = context.Code; AuthenticationHelper authHelper = new AuthenticationHelper(); String signInUserId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthAuthority); AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), authHelper.GetClientAssertionCertificate(), null); return(Task.FromResult(0)); }; notifications.RedirectToIdentityProvider = (context) => { string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase; context.ProtocolMessage.RedirectUri = appBaseUrl + "/"; context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl; return(Task.FromResult(0)); }; notifications.AuthenticationFailed = (context) => { context.HandleResponse(); return(Task.FromResult(0)); }; options.Notifications = notifications; app.UseOpenIdConnectAuthentication(options); }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions() { CookieName = "AllInOne" }); OpenIdConnectAuthenticationNotifications notifications = new OpenIdConnectAuthenticationNotifications() { AuthorizationCodeReceived = (context) => { // Obtain access token for the Azure AD Graph API var code = context.Code; ClientCredential credential = new ClientCredential(_clientId, _clientSecret); string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; AuthenticationContext authContext = new AuthenticationContext(_authority, new NaiveSessionCache(userObjectID, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase)); AuthenticationResult graphResult = authContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, _graphResourceId).Result; return(Task.FromResult(0)); }, AuthenticationFailed = context => { context.HandleResponse(); context.Response.Redirect("/Home/Error?message=" + context.Exception.Message); return(Task.FromResult(0)); } }; // If a domain has been configured, pass a domain hint to the identity provider to bypass home realm discovery if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ida:Domain"])) { notifications.RedirectToIdentityProvider = (context) => { context.ProtocolMessage.DomainHint = ConfigurationManager.AppSettings["ida:Domain"]; return(Task.FromResult(0)); }; } app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = _clientId, Authority = _authority, Notifications = notifications }); }
public void BuildOpenIdConnectAuthenticationOptionsCorrectly() { var mockTokenEvent = Substitute.For <Func <SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>, Task> >(); var oktaMvcOptions = new OktaMvcOptions() { PostLogoutRedirectUri = "http://postlogout.com", OktaDomain = "http://myoktadomain.com", ClientId = "foo", ClientSecret = "bar", RedirectUri = "/redirectUri", Scope = new List <string> { "openid", "profile", "email" }, SecurityTokenValidated = mockTokenEvent, }; var notifications = new OpenIdConnectAuthenticationNotifications { RedirectToIdentityProvider = null, }; var oidcOptions = OpenIdConnectAuthenticationOptionsBuilder.BuildOpenIdConnectAuthenticationOptions( oktaMvcOptions, notifications); oidcOptions.ClientId.Should().Be(oktaMvcOptions.ClientId); oidcOptions.ClientSecret.Should().Be(oktaMvcOptions.ClientSecret); oidcOptions.PostLogoutRedirectUri.Should().Be(oktaMvcOptions.PostLogoutRedirectUri); oidcOptions.AuthenticationMode.Should().Be(AuthenticationMode.Active); var issuer = UrlHelper.CreateIssuerUrl(oktaMvcOptions.OktaDomain, oktaMvcOptions.AuthorizationServerId); oidcOptions.Authority.Should().Be(issuer); oidcOptions.RedirectUri.Should().Be(oktaMvcOptions.RedirectUri); oidcOptions.Scope.Should().Be(string.Join(" ", oktaMvcOptions.Scope)); // Check the event was call once with a null parameter oidcOptions.Notifications.SecurityTokenValidated(null); mockTokenEvent.Received(1).Invoke(null); }
private void SetNotifications() { Notifications = new OpenIdConnectAuthenticationNotifications() { RedirectToIdentityProvider = (context) => { Debug.WriteLine("*** RedirectToIdentityProvider"); return(Task.FromResult(0)); }, MessageReceived = (context) => { Debug.WriteLine("*** MessageReceived"); return(Task.FromResult(0)); }, SecurityTokenReceived = (context) => { Debug.WriteLine("*** SecurityTokenReceived"); return(Task.FromResult(0)); }, SecurityTokenValidated = (context) => { Debug.WriteLine("*** SecurityTokenValidated"); var ticket = context.AuthenticationTicket; return(Task.FromResult(0)); }, AuthorizationCodeReceived = (context) => { Debug.WriteLine("*** AuthorizationCodeReceived"); return(Task.FromResult(0)); }, AuthenticationFailed = (context) => { Debug.WriteLine("*** AuthenticationFailed"); return(Task.FromResult(0)); }, }; }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); string authority = ConfigurationHelper.AADInstance + ConfigurationHelper.TenantId; string clientId = ConfigurationHelper.ClientId; string clientSecret = ConfigurationHelper.ClientSecret; OpenIdConnectAuthenticationNotifications notifications = new OpenIdConnectAuthenticationNotifications { AuthorizationCodeReceived = async(context) => { var code = context.Code; string signedInUserId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; AuthenticationContext authContext = new AuthenticationContext(authority); ClientCredential credential = new ClientCredential(clientId, clientSecret); AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential).ConfigureAwait(false); } }; app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = clientId, Authority = authority, RedirectUri = ConfigurationHelper.RedirectUri, PostLogoutRedirectUri = ConfigurationHelper.PostLogoutRedirectUri, Scope = OpenIdConnectScope.OpenIdProfile, ResponseType = OpenIdConnectResponseType.IdToken, TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = false }, Notifications = notifications } ); }
/// <summary> /// Creates a new instance of OpenIdConnectAuthenticationOptions. /// </summary> /// <param name="oktaMvcOptions">The <see cref="OktaMvcOptions"/> options.</param> /// <param name="notifications">The OpenIdConnectAuthenticationNotifications notifications.</param> /// <returns>A new instance of OpenIdConnectAuthenticationOptions.</returns> public static OpenIdConnectAuthenticationOptions BuildOpenIdConnectAuthenticationOptions(OktaMvcOptions oktaMvcOptions, OpenIdConnectAuthenticationNotifications notifications) { var issuer = UrlHelper.CreateIssuerUrl(oktaMvcOptions.OktaDomain, oktaMvcOptions.AuthorizationServerId); var httpClient = new HttpClient(new UserAgentHandler("okta-aspnet", typeof(OktaMiddlewareExtensions).Assembly.GetName().Version)); var configurationManager = new ConfigurationManager <OpenIdConnectConfiguration>( issuer + "/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever(), new HttpDocumentRetriever(httpClient)); var tokenValidationParameters = new DefaultTokenValidationParameters(oktaMvcOptions, issuer) { NameClaimType = "name", ValidAudience = oktaMvcOptions.ClientId, // CLIST: 2019-11-08 - save the claims token into the bootstrap context for k2 SaveSigninToken = true, }; var tokenExchanger = new TokenExchanger(oktaMvcOptions, issuer, configurationManager); var definedScopes = oktaMvcOptions.Scope?.ToArray() ?? OktaDefaults.Scope; var scopeString = string.Join(" ", definedScopes); var oidcOptions = new OpenIdConnectAuthenticationOptions { ClientId = oktaMvcOptions.ClientId, ClientSecret = oktaMvcOptions.ClientSecret, Authority = issuer, RedirectUri = oktaMvcOptions.RedirectUri, ResponseType = OpenIdConnectResponseType.CodeIdToken, Scope = scopeString, PostLogoutRedirectUri = oktaMvcOptions.PostLogoutRedirectUri, TokenValidationParameters = tokenValidationParameters, SecurityTokenValidator = new StrictSecurityTokenValidator(), AuthenticationMode = (oktaMvcOptions.LoginMode == LoginMode.SelfHosted) ? AuthenticationMode.Passive : AuthenticationMode.Active, Notifications = new OpenIdConnectAuthenticationNotifications { AuthorizationCodeReceived = tokenExchanger.ExchangeCodeForTokenAsync, RedirectToIdentityProvider = notifications.RedirectToIdentityProvider, }, }; if (oktaMvcOptions.SecurityTokenValidated != null) { oidcOptions.Notifications.SecurityTokenValidated = oktaMvcOptions.SecurityTokenValidated; } return(oidcOptions); }
public void ConfigureAuth(IAppBuilder app) { // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888 // http://appetere.com/post/getting-started-with-openid-connect app.SetDefaultSignInAsAuthenticationType("External Bearer"); var notifications = new OpenIdConnectAuthenticationNotifications() { RedirectToIdentityProvider = (context) => { Debug.WriteLine("*** RedirectToIdentityProvider"); return(Task.FromResult(0)); }, MessageReceived = (context) => { Debug.WriteLine("*** MessageReceived"); return(Task.FromResult(0)); }, SecurityTokenReceived = (context) => { Debug.WriteLine("*** SecurityTokenReceived"); return(Task.FromResult(0)); }, SecurityTokenValidated = (context) => { Debug.WriteLine("*** SecurityTokenValidated"); return(Task.FromResult(0)); }, AuthorizationCodeReceived = (context) => { Debug.WriteLine("*** AuthorizationCodeReceived"); return(Task.FromResult(0)); }, AuthenticationFailed = (context) => { Debug.WriteLine("*** AuthenticationFailed"); return(Task.FromResult(0)); }, }; // https://www.microsoftpressstore.com/articles/article.aspx?p=2473126&seqNum=2 app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { // For debugging - remove for production Notifications = notifications, ClientId = "347457883359-64didimqg2m9ci0o007lng94uf01pkqv.apps.googleusercontent.com", // rasor's public ClientSecret = "1kKy4GKzHisovEt6eoX34ZTW", // https://accounts.google.com/.well-known/openid-configuration Authority = "https://accounts.google.com", RedirectUri = "https://localhost/Client/", // "id_token" just returns the ID token. // "id_token token" also returns the ID token and the access token ResponseType = "id_token token", // ResponseMode = "fragment", Scope = "openid email profile", // CallbackPath = new PathString("/openid"), // This rest server is not supposed to do the login for the client - only to verify bearer token // Don't redirect outgoing 401 to login AuthenticationMode = AuthenticationMode.Passive }); DebugOwin(app, "2", "Oidc"); }
public void Configuration(IAppBuilder app) { // turn off mapping of claims to .NET ClaimTypes JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>(); // configuration for anti-CSRF protection AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject; // if the request path starts with "/identity", execute the app configured via configuration parameter // instead of continuing to the next component in the pipeline app.Map("/identity", idsrvApp => { var identityServerOptions = new IdentityServerOptions { SiteName = "Embedded IdentityServer", SigningCertificate = CertHelper.LoadCertificate($@"{AppDomain.CurrentDomain.BaseDirectory}bin\"), Factory = new IdentityServerServiceFactory() .UseInMemoryUsers(Users.Get()) .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()) }; idsrvApp.UseIdentityServer(identityServerOptions); }); // configure OWIN middleware // OWIN middleware sits in the pipeline and operates independently, has no knowledge of MVC // configured using IAppBuilder app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" }); // claims transformation var notifications = new OpenIdConnectAuthenticationNotifications { SecurityTokenValidated = 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 newIdentity = new ClaimsIdentity( id.AuthenticationType, Constants.ClaimTypes.GivenName, Constants.ClaimTypes.Role); newIdentity.AddClaim(givenName); newIdentity.AddClaim(familyName); newIdentity.AddClaim(sub); newIdentity.AddClaims(roles); // add some other app specific claim newIdentity.AddClaim(new Claim("app_specific", "some data")); n.AuthenticationTicket = new AuthenticationTicket(newIdentity, n.AuthenticationTicket.Properties); return(Task.FromResult(0)); } }; // do things related to OpenID Connect flows var openIdConnectOptions = new OpenIdConnectAuthenticationOptions { Authority = ConfigSSL.IdentityServerIdentityIP, ClientId = "mvc", Scope = "openid profile roles", RedirectUri = ConfigSSL.IdentityServerBaseIP, ResponseType = "id_token", SignInAsAuthenticationType = "Cookies", UseTokenLifetime = false, // notification that you can use to do claims transformation // the resulting claims will be stored in the cookie Notifications = notifications }; app.UseOpenIdConnectAuthentication(openIdConnectOptions); }