public override async Task<AuthenticateInfo> GetAuthenticateInfoAsync(string authenticationScheme) { if (authenticationScheme == null) { throw new ArgumentNullException(nameof(authenticationScheme)); } var handler = HttpAuthenticationFeature.Handler; var context = new AuthenticateContext(authenticationScheme); if (handler != null) { await handler.AuthenticateAsync(context); } if (!context.Accepted) { throw new InvalidOperationException($"No authentication handler is configured to authenticate for the scheme: {context.AuthenticationScheme}"); } return new AuthenticateInfo { Principal = context.Principal, Properties = new AuthenticationProperties(context.Properties), Description = new AuthenticationDescription(context.Description) }; }
public Task AuthenticateAsync(AuthenticateContext context) { context.Authenticated( ClaimsPrincipalBuilder.DefaultAuthenticated, new Dictionary<string, string>(), new Dictionary<string, object>()); return TaskCache.CompletedTask; }
public void AuthenticateContext_NotAuthenticated() { // Arrange var context = new AuthenticateContext("test"); // Act context.NotAuthenticated(); // Assert Assert.True(context.Accepted); Assert.Equal("test", context.AuthenticationScheme); Assert.Null(context.Description); Assert.Null(context.Error); Assert.Null(context.Principal); Assert.Null(context.Properties); }
public void AuthenticateContext_NotAuthenticated_SetsUnusedPropertiesToDefault_Failed() { // Arrange var context = new AuthenticateContext("test"); context.Failed(new Exception()); context.NotAuthenticated(); // Assert Assert.True(context.Accepted); Assert.Equal("test", context.AuthenticationScheme); Assert.Null(context.Description); Assert.Null(context.Error); Assert.Null(context.Principal); Assert.Null(context.Properties); }
// Remove once callers have been switched to GetAuthenticateInfoAsync public override async Task AuthenticateAsync(AuthenticateContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var handler = HttpAuthenticationFeature.Handler; if (handler != null) { await handler.AuthenticateAsync(context); } if (!context.Accepted) { throw new InvalidOperationException($"No authentication handler is configured to authenticate for the scheme: {context.AuthenticationScheme}"); } }
public void AuthenticateContext_Failed() { // Arrange var context = new AuthenticateContext("test"); var exception = new Exception(); // Act context.Failed(exception); // Assert Assert.True(context.Accepted); Assert.Equal("test", context.AuthenticationScheme); Assert.Null(context.Description); Assert.Same(exception, context.Error); Assert.Null(context.Principal); Assert.Null(context.Properties); }
public async Task AuthenticateAsync(AuthenticateContext context) { if (PriorHandler != null) { await PriorHandler.AuthenticateAsync(context); if (_transform != null && context?.Principal != null) { var transformationContext = new ClaimsTransformationContext(_httpContext) { Principal = context.Principal }; context.Authenticated( await _transform.TransformAsync(transformationContext), context.Properties, context.Description); } } }
public void AuthenticateContext_Authenticated() { // Arrange var context = new AuthenticateContext("test"); var principal = new ClaimsPrincipal(); var properties = new Dictionary <string, string>(); var description = new Dictionary <string, object>(); // Act context.Authenticated(principal, properties, description); // Assert Assert.True(context.Accepted); Assert.Equal("test", context.AuthenticationScheme); Assert.Same(description, context.Description); Assert.Null(context.Error); Assert.Same(principal, context.Principal); Assert.Same(properties, context.Properties); }
public void AuthenticateContext_Authenticated() { // Arrange var context = new AuthenticateContext("test"); var principal = new ClaimsPrincipal(); var properties = new Dictionary<string, string>(); var description = new Dictionary<string, object>(); // Act context.Authenticated(principal, properties, description); // Assert Assert.True(context.Accepted); Assert.Equal("test", context.AuthenticationScheme); Assert.Same(description, context.Description); Assert.Null(context.Error); Assert.Same(principal, context.Principal); Assert.Same(properties, context.Properties); }
public void AuthenticateContext_Failed_SetsUnusedPropertiesToDefault() { // Arrange var context = new AuthenticateContext("test"); var exception = new Exception(); context.Authenticated(new ClaimsPrincipal(), new Dictionary<string, string>(), new Dictionary<string, object>()); // Act context.Failed(exception); // Assert Assert.True(context.Accepted); Assert.Equal("test", context.AuthenticationScheme); Assert.Null(context.Description); Assert.Same(exception, context.Error); Assert.Null(context.Principal); Assert.Null(context.Properties); }
public void AuthenticateContext_Failed_SetsUnusedPropertiesToDefault() { // Arrange var context = new AuthenticateContext("test"); var exception = new Exception(); context.Authenticated(new ClaimsPrincipal(), new Dictionary <string, string>(), new Dictionary <string, object>()); // Act context.Failed(exception); // Assert Assert.True(context.Accepted); Assert.Equal("test", context.AuthenticationScheme); Assert.Null(context.Description); Assert.Same(exception, context.Error); Assert.Null(context.Principal); Assert.Null(context.Properties); }
public Task AuthenticateAsync(AuthenticateContext context) { if (ShouldHandleScheme(context.AuthenticationScheme)) { if (User != null) { context.Authenticated(User, properties: null, description: Options.AuthenticationDescriptions.FirstOrDefault(descrip => string.Equals(User.Identity.AuthenticationType, descrip.AuthenticationScheme, StringComparison.Ordinal))?.Items); } else { context.NotAuthenticated(); } } if (PriorHandler != null) { return PriorHandler.AuthenticateAsync(context); } return Task.FromResult(0); }
public async Task<string> Get(string cookie, CancellationToken token) { // get the TokenCache stored per-user from within OpenIdConnectOptions.Events.OnAuthorizationCodeReceived var authenticateContext = new AuthenticateContext(CookieAuthenticationDefaults.AuthenticationScheme); await this.HttpContext.Authentication.AuthenticateAsync(authenticateContext); string tokenBase64; if (authenticateContext.Properties.TryGetValue(Keys.TokenCache, out tokenBase64)) { byte[] tokenBlob = Convert.FromBase64String(tokenBase64); // decode the resumption cookie from the url var resume = UrlToken.Decode<ResumptionCookie>(cookie); var continuation = resume.GetMessage(); using (var scope = DialogModule.BeginLifetimeScope(Container.Instance, continuation)) { var botData = scope.Resolve<IBotData>(); await botData.LoadAsync(token); var data = botData.UserData; var tenantID = this.User.FindFirst(Keys.TenantID); var objectIdentifier = this.User.FindFirst(Keys.ObjectID); data.SetValue(Keys.ObjectID, objectIdentifier.Value); data.SetValue(Keys.TenantID, tenantID.Value); data.SetValue(Keys.TokenCache, tokenBlob); await botData.FlushAsync(token); } return "You're now logged-in - continue talking to the bot!"; } else { throw new InvalidOperationException(); } }
// Will remove once callees have been updated public abstract Task AuthenticateAsync(AuthenticateContext context);
public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory) { loggerfactory.AddConsole(LogLevel.Information); // Simple error page app.Use(async (context, next) => { try { await next(); } catch (Exception ex) { if (!context.Response.HasStarted) { context.Response.Clear(); context.Response.StatusCode = 500; await context.Response.WriteAsync(ex.ToString()); } else { throw; } } }); app.UseCookieAuthentication(new CookieAuthenticationOptions()); var clientId = Configuration["oidc:clientid"]; var clientSecret = Configuration["oidc:clientsecret"]; var authority = Configuration["oidc:authority"]; var resource = "https://graph.windows.net"; app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = clientId, ClientSecret = clientSecret, // for code flow Authority = authority, ResponseType = OpenIdConnectResponseTypes.CodeIdToken, // GetClaimsFromUserInfoEndpoint = true, Events = new OpenIdConnectEvents() { OnAuthorizationCodeReceived = async context => { var request = context.HttpContext.Request; var currentUri = UriHelper.Encode(request.Scheme, request.Host, request.PathBase, request.Path); var credential = new ClientCredential(clientId, clientSecret); var authContext = new AuthenticationContext(authority, new AuthPropertiesTokenCache(context.Properties)); var result = await authContext.AcquireTokenByAuthorizationCodeAsync( context.ProtocolMessage.Code, new Uri(currentUri), credential, resource); context.HandleCodeRedemption(result.AccessToken, result.IdToken); } } }); app.Run(async context => { if (context.Request.Path.Equals("/signout")) { await context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); context.Response.ContentType = "text/html"; await context.Response.WriteAsync($"<html><body>Signing out {context.User.Identity.Name}<br>{Environment.NewLine}"); await context.Response.WriteAsync("<a href=\"/\">Sign In</a>"); await context.Response.WriteAsync($"</body></html>"); return; } if (!context.User.Identities.Any(identity => identity.IsAuthenticated)) { await context.Authentication.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties { RedirectUri = "/" }); return; } context.Response.ContentType = "text/html"; await context.Response.WriteAsync($"<html><body>Hello Authenticated User {context.User.Identity.Name}<br>{Environment.NewLine}"); await context.Response.WriteAsync("Claims:<br>" + Environment.NewLine); foreach (var claim in context.User.Claims) { await context.Response.WriteAsync($"{claim.Type}: {claim.Value}<br>{Environment.NewLine}"); } await context.Response.WriteAsync("Tokens:<br>" + Environment.NewLine); try { // Retrieve the auth session with the cached tokens var authenticateContext = new AuthenticateContext(CookieAuthenticationDefaults.AuthenticationScheme); await context.Authentication.AuthenticateAsync(authenticateContext); var authProperties = new AuthenticationProperties(authenticateContext.Properties); var tokenCache = new AuthPropertiesTokenCache(authProperties); // Use ADAL to get the right token var authContext = new AuthenticationContext(authority, tokenCache); var credential = new ClientCredential(clientId, clientSecret); string userObjectID = context.User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; var result = authContext.AcquireTokenSilent(resource, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); // Update the cookie with the modified tokens if (tokenCache.HasCacheChanged) { await context.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, authenticateContext.Principal, authProperties); } await context.Response.WriteAsync($"access_token: {result.AccessToken}<br>{Environment.NewLine}"); } catch (Exception ex) { await context.Response.WriteAsync($"AquireToken error: {ex.Message}<br>{Environment.NewLine}"); } await context.Response.WriteAsync("<a href=\"/signout\">Sign Out</a>"); await context.Response.WriteAsync($"</body></html>"); }); }
private static void Describe(HttpResponse res, AuthenticateContext result) { res.StatusCode = 200; res.ContentType = "text/xml"; var xml = new XElement("xml"); if (result != null && result.Principal != null) { xml.Add(result.Principal.Claims.Select(claim => new XElement("claim", new XAttribute("type", claim.Type), new XAttribute("value", claim.Value)))); } if (result != null && result.Properties != null) { xml.Add(result.Properties.Select(extra => new XElement("extra", new XAttribute("type", extra.Key), new XAttribute("value", extra.Value)))); } var xmlBytes = Encoding.UTF8.GetBytes(xml.ToString()); res.Body.Write(xmlBytes, 0, xmlBytes.Length); }
private static TestServer CreateServer(CookieAuthenticationOptions options, Func<HttpContext, Task> testpath = null, Uri baseAddress = null, ClaimsTransformationOptions claimsTransform = null) { var builder = new WebHostBuilder() .Configure(app => { app.UseCookieAuthentication(options); // app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookie2" }); if (claimsTransform != null) { app.UseClaimsTransformation(claimsTransform); } app.Use(async (context, next) => { var req = context.Request; var res = context.Response; PathString remainder; if (req.Path == new PathString("/normal")) { res.StatusCode = 200; } else if (req.Path == new PathString("/protected")) { res.StatusCode = 401; } else if (req.Path == new PathString("/forbid")) // Simulate forbidden { await context.Authentication.ForbidAsync(CookieAuthenticationDefaults.AuthenticationScheme); } else if (req.Path == new PathString("/challenge")) { await context.Authentication.ChallengeAsync(CookieAuthenticationDefaults.AuthenticationScheme); } else if (req.Path == new PathString("/signout")) { await context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); } else if (req.Path == new PathString("/unauthorized")) { await context.Authentication.ChallengeAsync(CookieAuthenticationDefaults.AuthenticationScheme, new AuthenticationProperties(), ChallengeBehavior.Unauthorized); } else if (req.Path == new PathString("/protected/CustomRedirect")) { await context.Authentication.ChallengeAsync(new AuthenticationProperties() { RedirectUri = "/CustomRedirect" }); } else if (req.Path == new PathString("/me")) { var authContext = new AuthenticateContext(CookieAuthenticationDefaults.AuthenticationScheme); authContext.Authenticated(context.User, properties: null, description: null); Describe(res, authContext); } else if (req.Path.StartsWithSegments(new PathString("/me"), out remainder)) { var authContext = new AuthenticateContext(remainder.Value.Substring(1)); await context.Authentication.AuthenticateAsync(authContext); Describe(res, authContext); } else if (req.Path == new PathString("/testpath") && testpath != null) { await testpath(context); } else { await next(); } }); }) .ConfigureServices(services => services.AddAuthentication()); var server = new TestServer(builder); server.BaseAddress = baseAddress; return server; }
public async Task CanSpecifyAndShareDataProtector() { var dp = new NoOpDataProtector(); var builder1 = new WebHostBuilder() .Configure(app => { app.UseCookieAuthentication(new CookieAuthenticationOptions { TicketDataFormat = new TicketDataFormat(dp), CookieName = "Cookie" }); app.Use((context, next) => context.Authentication.SignInAsync("Cookies", new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))), new AuthenticationProperties())); }) .ConfigureServices(services => services.AddAuthentication()); var server1 = new TestServer(builder1); var transaction = await SendAsync(server1, "http://example.com/stuff"); Assert.NotNull(transaction.SetCookie); var builder2 = new WebHostBuilder() .Configure(app => { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookies", CookieName = "Cookie", TicketDataFormat = new TicketDataFormat(dp) }); app.Use(async (context, next) => { var authContext = new AuthenticateContext("Cookies"); await context.Authentication.AuthenticateAsync(authContext); Describe(context.Response, authContext); }); }) .ConfigureServices(services => services.AddAuthentication()); var server2 = new TestServer(builder2); var transaction2 = await SendAsync(server2, "http://example.com/stuff", transaction.CookieNameValue); Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name)); }
private static TestServer CreateResourceServer(Action<OAuthIntrospectionOptions> configuration) { var server = CreateAuthorizationServer(); var builder = new WebHostBuilder(); builder.UseEnvironment("Testing"); builder.ConfigureServices(services => { services.AddAuthentication(); services.AddDistributedMemoryCache(); }); builder.Configure(app => { app.UseOAuthIntrospection(options => { options.AutomaticAuthenticate = true; options.AutomaticChallenge = true; options.Authority = server.BaseAddress.AbsoluteUri; options.HttpClient = server.CreateClient(); // Run the configuration delegate // registered by the unit tests. configuration?.Invoke(options); }); app.Map("/ticket", map => map.Run(async context => { var ticket = new AuthenticateContext(OAuthIntrospectionDefaults.AuthenticationScheme); await context.Authentication.AuthenticateAsync(ticket); if (!ticket.Accepted || ticket.Principal == null || ticket.Properties == null) { await context.Authentication.ChallengeAsync(); return; } context.Response.ContentType = "application/json"; // Return the authentication ticket as a JSON object. await context.Response.WriteAsync(JsonConvert.SerializeObject(new { Claims = from claim in ticket.Principal.Claims select new { claim.Type, claim.Value }, Properties = from property in ticket.Properties select new { Name = property.Key, property.Value } })); })); app.Run(context => { if (!context.User.Identities.Any(identity => identity.IsAuthenticated)) { return context.Authentication.ChallengeAsync(); } return context.Response.WriteAsync(context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value); }); }); return new TestServer(builder); }
private static TestServer CreateServer(Action<IServiceCollection> configureServices = null, Func<HttpContext, Task> testpath = null, Uri baseAddress = null) { var builder = new WebHostBuilder() .Configure(app => { app.UseIdentity(); app.Use(async (context, next) => { var req = context.Request; var res = context.Response; var userManager = context.RequestServices.GetRequiredService<UserManager<TestUser>>(); var signInManager = context.RequestServices.GetRequiredService<SignInManager<TestUser>>(); PathString remainder; if (req.Path == new PathString("/normal")) { res.StatusCode = 200; } else if (req.Path == new PathString("/createMe")) { var result = await userManager.CreateAsync(new TestUser("hao"), TestPassword); res.StatusCode = result.Succeeded ? 200 : 500; } else if (req.Path == new PathString("/createSimple")) { var result = await userManager.CreateAsync(new TestUser("simple"), "aaaaaa"); res.StatusCode = result.Succeeded ? 200 : 500; } else if (req.Path == new PathString("/protected")) { res.StatusCode = 401; } else if (req.Path.StartsWithSegments(new PathString("/pwdLogin"), out remainder)) { var isPersistent = bool.Parse(remainder.Value.Substring(1)); var result = await signInManager.PasswordSignInAsync("hao", TestPassword, isPersistent, false); res.StatusCode = result.Succeeded ? 200 : 500; } else if (req.Path == new PathString("/twofactorRememeber")) { var user = await userManager.FindByNameAsync("hao"); await signInManager.RememberTwoFactorClientAsync(user); res.StatusCode = 200; } else if (req.Path == new PathString("/isTwoFactorRememebered")) { var user = await userManager.FindByNameAsync("hao"); var result = await signInManager.IsTwoFactorClientRememberedAsync(user); res.StatusCode = result ? 200 : 500; } else if (req.Path == new PathString("/twofactorSignIn")) { } else if (req.Path == new PathString("/me")) { var auth = new AuthenticateContext("Application"); auth.Authenticated(context.User, new AuthenticationProperties().Items, new AuthenticationDescription().Items); Describe(res, auth); } else if (req.Path.StartsWithSegments(new PathString("/me"), out remainder)) { var auth = new AuthenticateContext(remainder.Value.Substring(1)); await context.Authentication.AuthenticateAsync(auth); Describe(res, auth); } else if (req.Path == new PathString("/testpath") && testpath != null) { await testpath(context); } else { await next(); } }); }) .ConfigureServices(services => { services.AddIdentity<TestUser, TestRole>(); services.AddSingleton<IUserStore<TestUser>, InMemoryStore<TestUser, TestRole>>(); services.AddSingleton<IRoleStore<TestRole>, InMemoryStore<TestUser, TestRole>>(); if (configureServices != null) { configureServices(services); } }); var server = new TestServer(builder); server.BaseAddress = baseAddress; return server; }
private void BeforeAccessNotificationWithContext(TokenCacheNotificationArgs args) { // Retrieve the auth session with the cached tokens var authenticateContext = new AuthenticateContext(_signInScheme); _httpContext.Authentication.AuthenticateAsync(authenticateContext).Wait(); _authProperties = new AuthenticationProperties(authenticateContext.Properties); _principal = authenticateContext.Principal; BeforeAccessNotificationWithProperties(args); }
public void Authenticate(AuthenticateContext context) { context.NotAuthenticated(); }
public Task AuthenticateAsync(AuthenticateContext context) { context.Authenticated(new ClaimsPrincipal(), _props.Items, new Dictionary<string, object>()); return Task.FromResult(0); }
private static TestServer CreateServer(JwtBearerOptions options, Func<HttpContext, bool> handler = null) { var builder = new WebHostBuilder() .Configure(app => { if (options != null) { app.UseJwtBearerAuthentication(options); } app.Use(async (context, next) => { if (context.Request.Path == new PathString("/checkforerrors")) { var authContext = new AuthenticateContext(Http.Authentication.AuthenticationManager.AutomaticScheme); await context.Authentication.AuthenticateAsync(authContext); if (authContext.Error != null) { throw new Exception("Failed to authenticate", authContext.Error); } return; } else if (context.Request.Path == new PathString("/oauth")) { if (context.User == null || context.User.Identity == null || !context.User.Identity.IsAuthenticated) { context.Response.StatusCode = 401; return; } var identifier = context.User.FindFirst(ClaimTypes.NameIdentifier); if (identifier == null) { context.Response.StatusCode = 500; return; } await context.Response.WriteAsync(identifier.Value); } else if (context.Request.Path == new PathString("/unauthorized")) { // Simulate Authorization failure var result = await context.Authentication.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme); await context.Authentication.ChallengeAsync(JwtBearerDefaults.AuthenticationScheme); } else if (context.Request.Path == new PathString("/signIn")) { await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignInAsync(JwtBearerDefaults.AuthenticationScheme, new ClaimsPrincipal())); } else if (context.Request.Path == new PathString("/signOut")) { await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignOutAsync(JwtBearerDefaults.AuthenticationScheme)); } else { await next(); } }); }) .ConfigureServices(services => services.AddAuthentication()); return new TestServer(builder); }
public Task AuthenticateAsync(AuthenticateContext context) { return TaskCache.CompletedTask; }
private static TestServer CreateResourceServer(Action<OAuthValidationOptions> configuration = null) { var builder = new WebHostBuilder(); var format = new Mock<ISecureDataFormat<AuthenticationTicket>>(MockBehavior.Strict); format.Setup(mock => mock.Unprotect(It.Is<string>(token => token == "invalid-token"))) .Returns(value: null); format.Setup(mock => mock.Unprotect(It.Is<string>(token => token == "valid-token"))) .Returns(delegate { var identity = new ClaimsIdentity(OAuthValidationDefaults.AuthenticationScheme); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "Fabrikam")); var properties = new AuthenticationProperties(); return new AuthenticationTicket(new ClaimsPrincipal(identity), properties, OAuthValidationDefaults.AuthenticationScheme); }); format.Setup(mock => mock.Unprotect(It.Is<string>(token => token == "valid-token-with-scopes"))) .Returns(delegate { var identity = new ClaimsIdentity(OAuthValidationDefaults.AuthenticationScheme); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "Fabrikam")); var properties = new AuthenticationProperties(); properties.Items[OAuthValidationConstants.Properties.Scopes] = "C54A8F5E-0387-43F4-BA43-FD4B50DC190D 5C57E3BD-9EFB-4224-9AB8-C8C5E009FFD7"; return new AuthenticationTicket(new ClaimsPrincipal(identity), properties, OAuthValidationDefaults.AuthenticationScheme); }); format.Setup(mock => mock.Unprotect(It.Is<string>(token => token == "valid-token-with-single-audience"))) .Returns(delegate { var identity = new ClaimsIdentity(OAuthValidationDefaults.AuthenticationScheme); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "Fabrikam")); var properties = new AuthenticationProperties(new Dictionary<string, string> { [OAuthValidationConstants.Properties.Audiences] = "http://www.google.com/" }); return new AuthenticationTicket(new ClaimsPrincipal(identity), properties, OAuthValidationDefaults.AuthenticationScheme); }); format.Setup(mock => mock.Unprotect(It.Is<string>(token => token == "valid-token-with-multiple-audiences"))) .Returns(delegate { var identity = new ClaimsIdentity(OAuthValidationDefaults.AuthenticationScheme); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "Fabrikam")); var properties = new AuthenticationProperties(new Dictionary<string, string> { [OAuthValidationConstants.Properties.Audiences] = "http://www.google.com/ http://www.fabrikam.com/" }); return new AuthenticationTicket(new ClaimsPrincipal(identity), properties, OAuthValidationDefaults.AuthenticationScheme); }); format.Setup(mock => mock.Unprotect(It.Is<string>(token => token == "expired-token"))) .Returns(delegate { var identity = new ClaimsIdentity(OAuthValidationDefaults.AuthenticationScheme); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "Fabrikam")); var properties = new AuthenticationProperties(); properties.ExpiresUtc = DateTimeOffset.UtcNow - TimeSpan.FromDays(1); return new AuthenticationTicket(new ClaimsPrincipal(identity), properties, OAuthValidationDefaults.AuthenticationScheme); }); builder.UseEnvironment("Testing"); builder.ConfigureLogging(options => options.AddDebug()); builder.ConfigureServices(services => { services.AddAuthentication(); }); builder.Configure(app => { app.UseOAuthValidation(options => { options.AutomaticAuthenticate = true; options.AutomaticChallenge = true; options.AccessTokenFormat = format.Object; // Run the configuration delegate // registered by the unit tests. configuration?.Invoke(options); }); app.Map("/ticket", map => map.Run(async context => { var ticket = new AuthenticateContext(OAuthValidationDefaults.AuthenticationScheme); await context.Authentication.AuthenticateAsync(ticket); if (!ticket.Accepted || ticket.Principal == null || ticket.Properties == null) { await context.Authentication.ChallengeAsync(); return; } context.Response.ContentType = "application/json"; // Return the authentication ticket as a JSON object. await context.Response.WriteAsync(JsonConvert.SerializeObject(new { Claims = from claim in ticket.Principal.Claims select new { claim.Type, claim.Value }, Properties = from property in ticket.Properties select new { Name = property.Key, property.Value } })); })); app.Run(context => { if (!context.User.Identities.Any(identity => identity.IsAuthenticated)) { return context.Authentication.ChallengeAsync(); } var identifier = context.User.FindFirst(ClaimTypes.NameIdentifier).Value; return context.Response.WriteAsync(identifier); }); }); return new TestServer(builder); }
public Task AuthenticateAsync(AuthenticateContext context) { context.NotAuthenticated(); return Task.FromResult(0); }
private static TestServer CreateServer(GoogleOptions options, Func<HttpContext, Task> testpath = null) { var builder = new WebHostBuilder() .Configure(app => { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = TestExtensions.CookieAuthenticationScheme, AutomaticAuthenticate = true }); app.UseGoogleAuthentication(options); app.UseClaimsTransformation(context => { var id = new ClaimsIdentity("xform"); id.AddClaim(new Claim("xform", "yup")); context.Principal.AddIdentity(id); return Task.FromResult(context.Principal); }); app.Use(async (context, next) => { var req = context.Request; var res = context.Response; if (req.Path == new PathString("/challenge")) { await context.Authentication.ChallengeAsync("Google"); } else if (req.Path == new PathString("/tokens")) { var authContext = new AuthenticateContext(TestExtensions.CookieAuthenticationScheme); await context.Authentication.AuthenticateAsync(authContext); var tokens = new AuthenticationProperties(authContext.Properties).GetTokens(); res.Describe(tokens); } else if (req.Path == new PathString("/me")) { res.Describe(context.User); } else if (req.Path == new PathString("/unauthorized")) { // Simulate Authorization failure var result = await context.Authentication.AuthenticateAsync("Google"); await context.Authentication.ChallengeAsync("Google"); } else if (req.Path == new PathString("/unauthorizedAuto")) { var result = await context.Authentication.AuthenticateAsync("Google"); await context.Authentication.ChallengeAsync(); } else if (req.Path == new PathString("/401")) { res.StatusCode = 401; } else if (req.Path == new PathString("/signIn")) { await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignInAsync("Google", new ClaimsPrincipal())); } else if (req.Path == new PathString("/signOut")) { await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignOutAsync("Google")); } else if (req.Path == new PathString("/forbid")) { await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.ForbidAsync("Google")); } else if (testpath != null) { await testpath(context); } else { await next(); } }); }) .ConfigureServices(services => { services.AddAuthentication(authOptions => authOptions.SignInScheme = TestExtensions.CookieAuthenticationScheme); }); return new TestServer(builder); }
public async Task AuthenticateWillFail() { var server = CreateServer(new GoogleOptions { ClientId = "Test Id", ClientSecret = "Test Secret" }, async context => { var req = context.Request; var res = context.Response; if (req.Path == new PathString("/auth")) { var auth = new AuthenticateContext("Google"); await context.Authentication.AuthenticateAsync(auth); Assert.NotNull(auth.Error); } }); var transaction = await server.SendAsync("https://example.com/auth"); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); }
public Task AuthenticateAsync(AuthenticateContext context) { throw new NotImplementedException(); }
public static async Task<string> GetTokenAsync(this AuthenticationManager manager, string signInScheme, string tokenName) { if (manager == null) { throw new ArgumentNullException(nameof(manager)); } if (signInScheme == null) { throw new ArgumentNullException(nameof(signInScheme)); } if (tokenName == null) { throw new ArgumentNullException(nameof(tokenName)); } var authContext = new AuthenticateContext(signInScheme); await manager.AuthenticateAsync(authContext); return new AuthenticationProperties(authContext.Properties).GetTokenValue(tokenName); }
private static void Describe(HttpResponse res, AuthenticateContext result) { res.StatusCode = 200; res.ContentType = "text/xml"; var xml = new XElement("xml"); if (result != null && result.Principal != null) { xml.Add(result.Principal.Claims.Select(claim => new XElement("claim", new XAttribute("type", claim.Type), new XAttribute("value", claim.Value)))); } if (result != null && result.Properties != null) { xml.Add(result.Properties.Select(extra => new XElement("extra", new XAttribute("type", extra.Key), new XAttribute("value", extra.Value)))); } using (var memory = new MemoryStream()) { using (var writer = XmlWriter.Create(memory, new XmlWriterSettings { Encoding = Encoding.UTF8 })) { xml.WriteTo(writer); } res.Body.Write(memory.ToArray(), 0, memory.ToArray().Length); } }