private ClaimsIdentity BuildIdentity(CasAuthenticationOptions options, string username, XElement successNode) { var identity = new ClaimsIdentity(options.AuthenticationType, options.NameClaimType, ClaimTypes.Role); identity.AddClaim(new Claim(ClaimTypes.Name, username, "http://www.w3.org/2001/XMLSchema#string", options.AuthenticationType)); var attributesNode = successNode.Element(_ns + "attributes"); if (attributesNode != null) { foreach (var element in attributesNode.Elements()) { identity.AddClaim(new Claim(element.Name.LocalName, element.Value)); } } string identityValue = username; if (options.NameIdentifierAttribute != null && attributesNode != null) { var identityAttribute = attributesNode.Elements().FirstOrDefault(x => x.Name.LocalName == options.NameIdentifierAttribute); if (identityAttribute == null) throw new ApplicationException(string.Format("Identity attribute [{0}] not found for user: {1}", options.NameIdentifierAttribute, username)); identityValue = identityAttribute.Value; } identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, identityValue, "http://www.w3.org/2001/XMLSchema#string", options.AuthenticationType)); return identity; }
public CasRedirectToAuthorizationEndpointContext(HttpContext context, CasAuthenticationOptions options, AuthenticationProperties properties, string redirectUri) : base(context, options) { RedirectUri = redirectUri; Properties = properties; }
// For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context, user manager and signin manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider // Configure the sign in cookie app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the user logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. //app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); // Enables the application to remember the second login verification factor such as phone or email. // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. // This is similar to the RememberMe option when you log in. //app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); CasAuthenticationOptions casOptions = new CasAuthenticationOptions() { CasServerUrlBase = "https://cas.iu.edu/cas", }; app.UseCasAuthentication(casOptions); // 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 async Task ReplyPathWillAuthenticateValidTicketAndState() { var options = new CasAuthenticationOptions { CasServerUrlBase = "https://cas-dev.tamu.edu/cas", BackchannelHttpHandler = new TestHttpMessageHandler { Sender = req => { if (req.RequestUri.AbsoluteUri.StartsWith("https://cas-dev.tamu.edu/cas/serviceValidate?service=")) { var res = new HttpResponseMessage(HttpStatusCode.OK); var text = @"<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'> <cas:authenticationSuccess> <cas:user>testuser</cas:user> <cas:attributes> <cas:tamuEduPersonNetID>testuser</cas:tamuEduPersonNetID> <cas:tamuEduPersonUIN>111001111</cas:tamuEduPersonUIN> <cas:uid>5c62dae8b85c9dfa1417a43ceffc5926</cas:uid> </cas:attributes> </cas:authenticationSuccess> </cas:serviceResponse> "; res.Content = new StringContent(text, Encoding.UTF8, "text/html"); return(Task.FromResult(res)); } return(null); } } }; var server = CreateServer(options); var properties = new AuthenticationProperties(); var correlationKey = ".AspNet.Correlation.CAS"; var correlationValue = "TestCorrelationId"; properties.Dictionary.Add(correlationKey, correlationValue); var state = options.StateDataFormat.Protect(properties); var transaction = await SendAsync(server, "https://example.com/signin-cas?&state=" + Uri.EscapeDataString(state) + "&ticket=12345", correlationKey + "=" + correlationValue); var authCookie = transaction.AuthenticationCookieValue; transaction = await SendAsync(server, "https://example.com/me", authCookie); transaction.Response.StatusCode.ShouldBe(HttpStatusCode.OK); transaction.FindClaimValue(ClaimTypes.Name).ShouldBe("testuser"); transaction.FindClaimValue(ClaimTypes.NameIdentifier).ShouldBe("testuser"); transaction.FindClaimValue("tamuEduPersonNetID").ShouldBe("testuser"); transaction.FindClaimValue("tamuEduPersonUIN").ShouldBe("111001111"); transaction.FindClaimValue("uid").ShouldBe("5c62dae8b85c9dfa1417a43ceffc5926"); }
public CasAuthenticationMiddlewareTest() { // Arrange var principalName = Guid.NewGuid().ToString(); principal = new CasPrincipal(new Assertion(principalName), "CAS"); ticketValidator = Mock.Of <IServiceTicketValidator>(); options = new CasAuthenticationOptions { ServiceTicketValidator = ticketValidator, CasServerUrlBase = "http://example.com/cas" }; server = new TestServer(new WebHostBuilder() .ConfigureServices(services => { services.AddAuthentication(options => options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme); services.Configure <CookieAuthenticationOptions>(options => { options.AutomaticAuthenticate = true; options.AutomaticChallenge = true; options.LoginPath = new PathString("/login"); options.LogoutPath = new PathString("/logout"); }); }) .Configure(app => { app.UseCookieAuthentication(); app.UseCasAuthentication(options); app.Use(async(context, next) => { var request = context.Request; if (request.Path.StartsWithSegments(new PathString("/login"))) { await context.Authentication.ChallengeAsync(options.AuthenticationScheme, new AuthenticationProperties { RedirectUri = "/" }); } else if (request.Path.StartsWithSegments(new PathString("/logout"))) { await context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); } await next.Invoke(); }); app.Run(async context => { var user = context.User; // Deny anonymous request beyond this point. if (user == null || !user.Identities.Any(identity => identity.IsAuthenticated)) { await context.Authentication.ChallengeAsync(options.AuthenticationScheme); return; } // Display authenticated user id await context.Response.WriteAsync((user.Identity as ClaimsIdentity)?.FindFirst(ClaimTypes.NameIdentifier)?.Value); }); })); client = server.CreateClient(); }
/// <summary> /// Authenticate users using Cas /// </summary> /// <param name="app">The <see cref="IAppBuilder"/> passed to the configuration method</param> /// <param name="options">Middleware configuration options</param> /// <returns>The updated <see cref="IAppBuilder"/></returns> public static IAppBuilder UseCasAuthentication(this IAppBuilder app, CasAuthenticationOptions options) { if (app == null) throw new ArgumentNullException("app"); if (options == null) throw new ArgumentNullException("options"); app.Use(typeof(CasAuthenticationMiddleware), app, options); return app; }
public async Task ReplyPathWithoutStateQueryStringWillBeRejected() { var options = new CasAuthenticationOptions() { CasServerUrlBase = "https://cas-dev.tamu.edu/cas" }; var server = CreateServer(options); var transaction = await SendAsync(server, "https://example.com/signin-cas?code=TestCode"); transaction.Response.StatusCode.ShouldBe(HttpStatusCode.InternalServerError); }
public async Task ReplyPathWithoutStateQueryStringWillBeRejected() { var options = new CasAuthenticationOptions() { CasServerUrlBase = "https://cas-dev.tamu.edu/cas" }; var server = CreateServer(options); var transaction = await SendAsync(server, "https://example.com/signin-cas?code=TestCode"); transaction.Response.StatusCode.ShouldBe(HttpStatusCode.InternalServerError); }
public CasAuthenticationMiddlewareTest() { // Arrange var principalName = Guid.NewGuid().ToString(); principal = new CasPrincipal(new Assertion(principalName), "CAS"); ticketValidator = Mock.Of <IServiceTicketValidator>(); options = new CasAuthenticationOptions { ServiceTicketValidator = ticketValidator, CasServerUrlBase = "http://example.com/cas" }; server = TestServer.Create(app => { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions { LoginPath = new PathString("/login"), LogoutPath = new PathString("/logout") }); app.UseCasAuthentication(options); app.Use((context, next) => { var request = context.Request; if (request.Path.StartsWithSegments(new PathString("/login"))) { context.Authentication.Challenge(new AuthenticationProperties() { RedirectUri = "/" }, options.AuthenticationType); } else if (request.Path.StartsWithSegments(new PathString("/logout"))) { context.Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); } return(next.Invoke()); }); app.Run(async context => { var user = context.Authentication.User; // Deny anonymous request beyond this point. if (user == null || !user.Identities.Any(identity => identity.IsAuthenticated)) { context.Authentication.Challenge(options.AuthenticationType); return; } // Display authenticated principal name await context.Response.WriteAsync(user.GetPrincipalName()); }); }); client = server.HttpClient; }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context, user manager and signin manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider // Configure the sign in cookie app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the user logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); CasAuthenticationOptions casOptions = new CasAuthenticationOptions(); casOptions.CasServerUrlBase = "https://cas.csuchico.edu/cas"; casOptions.Caption = "Chico State Portal"; casOptions.AuthenticationType = "ChicoState"; app.UseCasAuthentication(casOptions); // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); // Enables the application to remember the second login verification factor such as phone or email. // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. // This is similar to the RememberMe option when you log in. app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); app.UseFacebookAuthentication( appId: "1461716180788223", appSecret: "430841e54fff127215c88158be1278de"); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "", // ClientSecret = "" //}); }
private TestServer CreateServer(Action <CasAuthenticationOptions> configureOptions) { var options = new CasAuthenticationOptions(); configureOptions?.Invoke(options); return(TestServer.Create(app => { app.SetDataProtectionProvider(new FakeDataProtectionProvider(new AesDataProtector("test"))); app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions { LoginPath = CookieAuthenticationDefaults.LoginPath, LogoutPath = CookieAuthenticationDefaults.LogoutPath }); app.UseCasAuthentication(options); app.Use(async(context, _) => { var request = context.Request; if (request.Path == CookieAuthenticationDefaults.LoginPath) { context.Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, CasDefaults.AuthenticationType); return; } if (request.Path == CookieAuthenticationDefaults.LogoutPath) { context.Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); return; } var user = context.Authentication.User; // Deny anonymous request beyond this point. if (user?.Identities.Any(identity => identity.IsAuthenticated) != true) { // This is what [Authorize] calls // The cookie middleware will intercept this 401 and redirect to LoginPath context.Authentication.Challenge(); return; } // Display authenticated principal name await context.Response.WriteAsync(user.GetPrincipalName()).ConfigureAwait(false); }); })); }
public async Task ChallengeWillTriggerApplyRedirectEvent() { var options = new CasAuthenticationOptions { CasServerUrlBase = "https://cas-dev.tamu.edu/cas", Provider = new CasAuthenticationProvider { OnApplyRedirect = context => context.Response.Redirect(context.RedirectUri + "&custom=test") } }; var server = CreateServer(options); var transaction = await SendAsync(server, "https://example.com/challenge"); transaction.Response.StatusCode.ShouldBe(HttpStatusCode.Redirect); var query = transaction.Response.Headers.Location.Query; query.ShouldContain("custom=test"); }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context and user manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider // Configure the sign in cookie app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); 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(); CasAuthenticationOptions casOptions = new CasAuthenticationOptions(); casOptions.CasServerUrlBase = "http://<url of my CAS server/"; casOptions.Caption = "University of Cleverville Single Sign-On"; casOptions.AuthenticationType = "UoC_SSO"; app.UseCasAuthentication(casOptions); }
public async Task ChallengeWillTriggerApplyRedirectEvent() { var options = new CasAuthenticationOptions { CasServerUrlBase = "https://cas-dev.tamu.edu/cas", Provider = new CasAuthenticationProvider { OnApplyRedirect = context => context.Response.Redirect(context.RedirectUri + "&custom=test") } }; var server = CreateServer(options); var transaction = await SendAsync(server, "https://example.com/challenge"); transaction.Response.StatusCode.ShouldBe(HttpStatusCode.Redirect); var query = transaction.Response.Headers.Location.Query; query.ShouldContain("custom=test"); }
private static TestServer CreateServer(CasAuthenticationOptions options, Func <IOwinContext, Task> testpath = null) { return(TestServer.Create(app => { app.Properties["host.AppName"] = "Microsoft.Owin.Security.Tests"; app.SetDataProtectionProvider(new DummyDataProtectorProvider()); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = CookieAuthenticationType, }); options.SignInAsAuthenticationType = CookieAuthenticationType; app.UseCasAuthentication(options); app.Use(async(context, next) => { IOwinRequest req = context.Request; IOwinResponse res = context.Response; if (req.Path == new PathString("/challenge")) { context.Authentication.Challenge("CAS"); res.StatusCode = 401; } else if (req.Path == new PathString("/me")) { Describe(res, new AuthenticateResult(req.User.Identity, new AuthenticationProperties(), new AuthenticationDescription())); } else if (testpath != null) { await testpath(context); } else { await next(); } }); })); }
public CasCreatingTicketContext( HttpContext context, CasAuthenticationOptions options) : base(context, options) { }
public BaseCasContext(HttpContext context, CasAuthenticationOptions options) : base(context) { Options = options; }
private static TestServer CreateServer(CasAuthenticationOptions options, Func<IOwinContext, Task> testpath = null) { return TestServer.Create(app => { app.Properties["host.AppName"] = "Microsoft.Owin.Security.Tests"; app.SetDataProtectionProvider(new DummyDataProtectorProvider()); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = CookieAuthenticationType, }); options.SignInAsAuthenticationType = CookieAuthenticationType; app.UseCasAuthentication(options); app.Use(async (context, next) => { IOwinRequest req = context.Request; IOwinResponse res = context.Response; if (req.Path == new PathString("/challenge")) { context.Authentication.Challenge("CAS"); res.StatusCode = 401; } else if (req.Path == new PathString("/me")) { Describe(res, new AuthenticateResult(req.User.Identity, new AuthenticationProperties(), new AuthenticationDescription())); } else if (testpath != null) { await testpath(context); } else { await next(); } }); }); }
public Cas2ServiceValidateTicketValidator(CasAuthenticationOptions options) { _options = options; }
public async Task ReplyPathWillAuthenticateValidTicketAndState() { var options = new CasAuthenticationOptions { CasServerUrlBase = "https://cas-dev.tamu.edu/cas", BackchannelHttpHandler = new TestHttpMessageHandler { Sender = req => { if (req.RequestUri.AbsoluteUri.StartsWith("https://cas-dev.tamu.edu/cas/serviceValidate?service=")) { var res = new HttpResponseMessage(HttpStatusCode.OK); var text = @"<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'> <cas:authenticationSuccess> <cas:user>testuser</cas:user> <cas:attributes> <cas:tamuEduPersonNetID>testuser</cas:tamuEduPersonNetID> <cas:tamuEduPersonUIN>111001111</cas:tamuEduPersonUIN> <cas:uid>5c62dae8b85c9dfa1417a43ceffc5926</cas:uid> </cas:attributes> </cas:authenticationSuccess> </cas:serviceResponse> "; res.Content = new StringContent(text, Encoding.UTF8, "text/html"); return Task.FromResult(res); } return null; } } }; var server = CreateServer(options); var properties = new AuthenticationProperties(); var correlationKey = ".AspNet.Correlation.CAS"; var correlationValue = "TestCorrelationId"; properties.Dictionary.Add(correlationKey, correlationValue); var state = options.StateDataFormat.Protect(properties); var transaction = await SendAsync(server, "https://example.com/signin-cas?&state=" + Uri.EscapeDataString(state) + "&ticket=12345", correlationKey + "=" + correlationValue); var authCookie = transaction.AuthenticationCookieValue; transaction = await SendAsync(server, "https://example.com/me", authCookie); transaction.Response.StatusCode.ShouldBe(HttpStatusCode.OK); transaction.FindClaimValue(ClaimTypes.Name).ShouldBe("testuser"); transaction.FindClaimValue(ClaimTypes.NameIdentifier).ShouldBe("testuser"); transaction.FindClaimValue("tamuEduPersonNetID").ShouldBe("testuser"); transaction.FindClaimValue("tamuEduPersonUIN").ShouldBe("111001111"); transaction.FindClaimValue("uid").ShouldBe("5c62dae8b85c9dfa1417a43ceffc5926"); }