public void Can_replace_message() { using (new CultureScope("fr-FR")) { var custom = new CustomLanguageManager(); var msg = custom.GetString("NotNullValidator"); msg.ShouldEqual("foo"); } }
public void Configuration(IAppBuilder app) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }; AntiForgeryConfig.UniqueClaimTypeIdentifier = IdentityServer3.Core.Constants.ClaimTypes.Subject; JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>(); // Adjust the configuration for anti-CSRF protection to the new unique sub claim type JwtSecurityTokenHandler.InboundClaimTypeMap.Clear(); IContainer container = AutofacConfig.ConfigureContainer(); app.UseAutofacMiddleware(container); CustomLanguageManager customLanguageManager = new CustomLanguageManager(container.Resolve <ILanguageManager>()); ValidatorOptions.LanguageManager = customLanguageManager; app.UseResourceAuthorization(new AuthorizationManager()); app.UseKentorOwinCookieSaver(); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" }); object section = ConfigurationManager.GetSection("openIdConnectionOptionSection"); if (section != null) { OpenIdConnectionOption openIdConnectionOption = (section as OpenIdConnectionOptionSection).OpenIdConnectionOption; app.UseOpenIdConnectAuthenticationPatched(new OpenIdConnectAuthenticationOptions { Authority = openIdConnectionOption.Authority, ClientId = openIdConnectionOption.ClientId, Scope = openIdConnectionOption.Scopes, ResponseType = openIdConnectionOption.ResponseType, RedirectUri = openIdConnectionOption.RedirectUri, SignInAsAuthenticationType = openIdConnectionOption.SignInAsAuthenticationType, UseTokenLifetime = openIdConnectionOption.UseTokenLifetime, Notifications = new OpenIdConnectAuthenticationNotifications { SecurityTokenValidated = async n => { ClaimsIdentity nid = new ClaimsIdentity( n.AuthenticationTicket.Identity.AuthenticationType, IdentityServer3.Core.Constants.ClaimTypes.GivenName, IdentityServer3.Core.Constants.ClaimTypes.Role); // get userinfo data #pragma warning disable CS0618 // Type or member is obsolete UserInfoClient userInfoClient = new UserInfoClient( #pragma warning restore CS0618 // Type or member is obsolete n.Options.Authority + "/connect/userinfo"); UserInfoResponse userInfo = await userInfoClient.GetAsync(n.ProtocolMessage.AccessToken); userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Type, ui.Value))); // keep the id_token for logout nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken)); // add access token for sample API nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken)); // keep track of access token expiration nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString())); n.AuthenticationTicket = new AuthenticationTicket( nid, n.AuthenticationTicket.Properties); }, /*AuthenticationFailed = authFailed => * { * if (authFailed.Exception.Message.Contains("IDX21323")) * { * authFailed.HandleResponse(); * authFailed.OwinContext.Authentication.Challenge(); * } * * return Task.FromResult(true); * },*/ RedirectToIdentityProvider = n => { switch (n.ProtocolMessage.RequestType) { case OpenIdConnectRequestType.AuthenticationRequest: // hack to work around session cookie not being removed when expires. this is preventing owin from accepting an open id response n.OwinContext.Authentication.SignOut("Cookies"); break; case OpenIdConnectRequestType.LogoutRequest: string uri = ConfigurationManager.AppSettings["Host"].ToString(); n.ProtocolMessage.RedirectUri = uri; n.ProtocolMessage.PostLogoutRedirectUri = uri; Claim idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token"); if (idTokenHint != null) { n.ProtocolMessage.IdTokenHint = idTokenHint.Value; } break; } return(Task.FromResult(0)); } } }); } }
public void Configuration(IAppBuilder app) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.RollingFile(HttpContext.Current.Request.PhysicalApplicationPath + @"\logs\sts.identityserver-{Date}.txt") .CreateLogger(); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }; AntiForgeryConfig.UniqueClaimTypeIdentifier = IdentityServer3Constants.ClaimTypes.Subject; JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>(); // Adjust the configuration for anti-CSRF protection to the new unique sub claim type JwtSecurityTokenHandler.InboundClaimTypeMap.Clear(); IContainer container = AutofacConfig.ConfigureContainer(); app.UseAutofacMiddleware(container); CustomLanguageManager customLanguageManager = new CustomLanguageManager(container.Resolve <ILanguageManager>()); ValidatorOptions.LanguageManager = customLanguageManager; app.Use(async(context, next) => { try { await next(); } catch (Exception ex) { Log.Error(ex, "OWIN error."); } }); app.Map("/windows", ConfigureWindowsTokenProvider); app.Map("/identity", idsrvApp => { idsrvApp.UseAutofacMiddleware(container); IdentityServerServiceFactory factory = new IdentityServerServiceFactory(); factory.CustomGrantValidators.Add(new Registration <ICustomGrantValidator>(typeof(WindowsGrantValidator))); factory.UserService = new Registration <IUserService, UserService>(); factory.ScopeStore = new Registration <IScopeStore>(container.Resolve <IScopeStore>()); factory.ClientStore = new Registration <IClientStore>(container.Resolve <IClientStore>()); IdentityModelEventSource.ShowPII = true; IdentityModelEventSource.HeaderWritten = true; var cors = new DefaultCorsPolicyService { AllowAll = true }; factory.CorsPolicyService = new Registration <ICorsPolicyService>(cors); //var subjects = X509.LocalMachine.My.SubjectDistinguishedName; IdentityServerOptions options = new IdentityServerOptions { SiteName = "Duy Tan Security Token Service", SigningCertificate = Certificate.Get(), //X509.LocalMachine.My.SubjectDistinguishedName.Find("CN=localhost").First(),//Certificate.Get(),//X509.LocalMachine.My.SerialNumber.Find("CN =*.duytan.com OU=IT O=Duy Tan Plastics Manufacturing Corporation L=Ho Chi Minh C=VN").First(),//Certificate.Get(), Factory = factory, RequireSsl = false, EnableWelcomePage = true, AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions { EnablePostSignOutAutoRedirect = true, EnableSignOutPrompt = false, }, EventsOptions = new EventsOptions { RaiseSuccessEvents = true, RaiseErrorEvents = true, RaiseFailureEvents = true, RaiseInformationEvents = true }, LoggingOptions = new LoggingOptions { EnableWebApiDiagnostics = true, WebApiDiagnosticsIsVerbose = true, EnableHttpLogging = true, EnableKatanaLogging = true } }; if (Configs.WindowAuth) { options.AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions { EnablePostSignOutAutoRedirect = true, EnableSignOutPrompt = false, EnableLocalLogin = false, IdentityProviders = ConfigureIdentityProviders, EnableAutoCallbackForFederatedSignout = true, }; } idsrvApp.UseIdentityServer(options); }); app.UseResourceAuthorization(new AuthorizationManager()); app.UseKentorOwinCookieSaver(); /*app.UseCookieAuthentication(new CookieAuthenticationOptions * { * AuthenticationType = "Cookies", * CookieManager = new SystemWebChunkingCookieManager() * * });*/ /*object section = ConfigurationManager.GetSection("openIdConnectionOptionSection"); * * if (section != null) * { * OpenIdConnectionOption openIdConnectionOption = (section as OpenIdConnectionOptionSection).OpenIdConnectionOption; * app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions * { * Authority = openIdConnectionOption.Authority, * ClientId = openIdConnectionOption.ClientId, * Scope = openIdConnectionOption.Scopes, * ResponseType = openIdConnectionOption.ResponseType, * RedirectUri = openIdConnectionOption.RedirectUri, * SignInAsAuthenticationType = openIdConnectionOption.SignInAsAuthenticationType, * UseTokenLifetime = openIdConnectionOption.UseTokenLifetime, * Notifications = new OpenIdConnectAuthenticationNotifications * { * AuthenticationFailed = context => * { * context.HandleResponse(); * context.Response.Redirect("/Error?message=" + context.Exception.Message); * return Task.FromResult(0); * }, * MessageReceived = n => { * return Task.FromResult(0); * }, * SecurityTokenValidated = async n => * { * ClaimsIdentity nid = new ClaimsIdentity( * n.AuthenticationTicket.Identity.AuthenticationType, * ClaimTypes.GivenName, * ClaimTypes.Role); * * // get userinfo data #pragma warning disable CS0618 // Type or member is obsolete * UserInfoClient userInfoClient = new UserInfoClient( #pragma warning restore CS0618 // Type or member is obsolete * n.Options.Authority + "/connect/userinfo"); * * UserInfoResponse userInfo = await userInfoClient.GetAsync(n.ProtocolMessage.AccessToken); * userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Type, ui.Value))); * * // keep the id_token for logout * nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken)); * * // add access token for sample API * nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken)); * * // keep track of access token expiration * nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString())); * * // add some other app specific claim * nid.AddClaim(new Claim("app_specific", "some data")); * * n.AuthenticationTicket = new AuthenticationTicket( * nid, * n.AuthenticationTicket.Properties); * }, * * RedirectToIdentityProvider = n => * { * if (n.ProtocolMessage.RequestType == Microsoft.IdentityModel.Protocols.OpenIdConnectRequestType.LogoutRequest) * { * string uri = ConfigurationManager.AppSettings["Host"].ToString(); * n.ProtocolMessage.RedirectUri = $"{uri}/"; * n.ProtocolMessage.PostLogoutRedirectUri = $"{uri}/"; * Claim idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token"); * * if (idTokenHint != null) * { * n.ProtocolMessage.IdTokenHint = idTokenHint.Value; * } * } * * return Task.FromResult(0); * } * } * }); * }*/ }