public async Task OnValidateIdentityRejectsWhenValidateSecurityStampFails() { var user = new IdentityUser("test"); var httpContext = new Mock<HttpContext>(); var userManager = MockHelpers.MockUserManager<IdentityUser>(); var authManager = new Mock<IAuthenticationManager>(); var claimsManager = new Mock<IClaimsIdentityFactory<IdentityUser>>(); var signInManager = new Mock<SignInManager<IdentityUser>>(userManager.Object, authManager.Object, claimsManager.Object); signInManager.Setup(s => s.ValidateSecurityStamp(It.IsAny<ClaimsIdentity>(), user.Id)).ReturnsAsync(null).Verifiable(); var services = new ServiceCollection(); services.AddInstance(signInManager.Object); httpContext.Setup(c => c.ApplicationServices).Returns(services.BuildServiceProvider()); var id = new ClaimsIdentity(ClaimsIdentityOptions.DefaultAuthenticationType); id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); var ticket = new AuthenticationTicket(id, new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow }); var context = new CookieValidateIdentityContext(httpContext.Object, ticket, new CookieAuthenticationOptions()); Assert.NotNull(context.Properties); Assert.NotNull(context.Options); Assert.NotNull(context.Identity); await SecurityStampValidator.OnValidateIdentity<IdentityUser>(TimeSpan.Zero).Invoke(context); Assert.Null(context.Identity); signInManager.VerifyAll(); }
public async Task OnValidateIdentityThrowsWithEmptyServiceCollection() { var httpContext = new Mock<HttpContext>(); httpContext.Setup(c => c.ApplicationServices).Returns(new ServiceCollection().BuildServiceProvider()); var id = new ClaimsIdentity(ClaimsIdentityOptions.DefaultAuthenticationType); var ticket = new AuthenticationTicket(id, new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow }); var context = new CookieValidateIdentityContext(httpContext.Object, ticket, new CookieAuthenticationOptions()); await Assert.ThrowsAsync<Exception>(() => SecurityStampValidator.OnValidateIdentity<IdentityUser>(TimeSpan.Zero).Invoke(context)); }
private static Task<bool> VerifyClientIdAsync(ApplicationUserManager manager, ApplicationUser user, CookieValidateIdentityContext context) { string clientId = context.Identity.FindFirstValue("AspNet.Identity.ClientId"); if (!string.IsNullOrEmpty(clientId) && user.Users.Any(c => c.Id.ToString() == clientId)) { user.CurrentClientId = clientId; return Task.FromResult(true); } return Task.FromResult(false); }
public Task ValidateIdentity(CookieValidateIdentityContext context) { if (context.Identity.IsAuthenticated) { if (context.Request.Path.Value.Contains(context.Options.LoginPath.Value)) { return(Task.FromResult <object>(null)); } bool isWebPart = context.Request.Get <string>("IsWebPart") == "1"; var spContext = SPContextProvider.Get(context.Identity, isWebPart); string spHostUrlString = TokenHelper.EnsureTrailingSlash(context.Request.Query.Get(SharePointContext.SPHostUrlKey)); if (string.IsNullOrEmpty(spHostUrlString)) { spHostUrlString = ConfigurationManager.AppSettings["SPHostUrl"]; } Uri spHostUrl; if (!Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl)) { //throw new Exception(string.Format("Unable to determine {0}.", SharePointContext.SPHostUrlKey)); } //try //{ if (spHostUrl != null && !string.Equals(spContext.SPHostUrl.GetLeftPart(UriPartial.Path).TrimEnd('/'), spHostUrl.GetLeftPart(UriPartial.Path).TrimEnd('/'), StringComparison.OrdinalIgnoreCase)) { context.RejectIdentity(); } //} //catch (Exception) //{ // context.RejectIdentity(); //} string clientId = ConfigurationManager.AppSettings["ClientId"]; try { if (spContext.ClientId != (string.IsNullOrEmpty(clientId) ? Guid.Empty : new Guid(clientId))) { context.RejectIdentity(); } } catch (Exception) { context.RejectIdentity(); } } return(Task.FromResult <object>(null)); }
public async Task OnValidateIdentityNoBoomWithNullManagerTest() { var owinContext = new OwinContext(); var id = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie); var ticket = new AuthenticationTicket(id, new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow }); var context = new CookieValidateIdentityContext(owinContext, ticket, new CookieAuthenticationOptions()); await SecurityStampValidator.OnValidateIdentity <UserManager <IdentityUser>, IdentityUser>(TimeSpan.Zero, SignIn) .Invoke(context); Assert.NotNull(context.Identity); }
public async Task OnValidateIdentityThrowsWithEmptyServiceCollection() { var httpContext = new Mock <HttpContext>(); httpContext.Setup(c => c.RequestServices).Returns(new ServiceCollection().BuildServiceProvider()); var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationType); var ticket = new AuthenticationTicket(id, new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow }); var context = new CookieValidateIdentityContext(httpContext.Object, ticket, new CookieAuthenticationOptions()); var ex = await Assert.ThrowsAsync <InvalidOperationException>(() => SecurityStampValidator.ValidateIdentityAsync(context)); Assert.True(ex.Message.Contains("No service for type 'Microsoft.Framework.OptionsModel.IOptions")); }
/// <summary> /// Ensures that the culture is set correctly for the current back office user and that the user's session token is valid /// </summary> /// <param name="context"/> /// <returns/> public override async Task ValidateIdentity(CookieValidateIdentityContext context) { //ensure the thread culture is set context?.Identity?.EnsureCulture(); await EnsureValidSessionId(context); if (context?.Identity == null) { context?.OwinContext.Authentication.SignOut(context.Options.AuthenticationType); return; } await base.ValidateIdentity(context); }
public async Task OnValidateIdentity(CookieValidateIdentityContext cookieValidateIdentityContext) { DateTimeOffset currentDateUtc = DateTimeOffset.UtcNow; if (cookieValidateIdentityContext.Options?.SystemClock != null) { currentDateUtc = cookieValidateIdentityContext.Options.SystemClock.UtcNow; } DateTimeOffset? authenticationTickedIssuedDataUtc = cookieValidateIdentityContext.Properties.IssuedUtc; bool authenticationTickedIsValid = !authenticationTickedIssuedDataUtc.HasValue; if (authenticationTickedIssuedDataUtc.HasValue) { authenticationTickedIsValid = currentDateUtc.Subtract(authenticationTickedIssuedDataUtc.Value) > this.ValidationInterval; } if (authenticationTickedIsValid) { var userId = cookieValidateIdentityContext.Identity.GetUserId(); if (userId != null) { bool userIdentityIsValid = false; User user = await this.userRepository.FindByIdAsync(userId); if (user != null) { string securityStamp = cookieValidateIdentityContext.Identity.FindFirst("AspNet.Identity.SecurityStamp")?.Value; if (securityStamp == user.SecurityStamp) { var userRoles = await this.userRepository.GetRolesAsync(user); var userClaims = await this.userRepository.GetClaimsAsync(user); var claimsIdentity = await this.claimsIdentityFactory.CreateAsync(user, AuthenticationType.ApplicationCookie, userRoles, userClaims); // Add custom user claims here. cookieValidateIdentityContext.Properties.IssuedUtc = new DateTimeOffset?(); cookieValidateIdentityContext.Properties.ExpiresUtc = new DateTimeOffset?(); cookieValidateIdentityContext.OwinContext.Authentication.SignIn(cookieValidateIdentityContext.Properties, claimsIdentity); userIdentityIsValid = true; } } if (!userIdentityIsValid) { cookieValidateIdentityContext.RejectIdentity(); cookieValidateIdentityContext.OwinContext.Authentication.SignOut(cookieValidateIdentityContext.Options.AuthenticationType); } } } }
public static async Task ValidateSessionAsync(TimeSpan validateInterval, CookieValidateIdentityContext context, IGlobalSettings globalSettings) { if (context.Request.Uri.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath, globalSettings) == false) { return; } var valid = await ValidateSessionAsync(validateInterval, context.OwinContext, context.Options.CookieManager, context.Options.SystemClock, context.Properties.IssuedUtc, context.Identity, globalSettings); if (valid == false) { context.RejectIdentity(); context.OwinContext.Authentication.SignOut(context.Options.AuthenticationType); } }
private static bool shouldIgnoreRequest(CookieValidateIdentityContext context) { string[] reservedPath = { "/__browserLink", "/img", "/fonts", "/Scripts", "/Content", "/Uploads", "/Images" }; return(reservedPath.Any(path => context.OwinContext.Request.Path.Value.StartsWith(path, StringComparison.OrdinalIgnoreCase)) || BundleTable.Bundles.Select(bundle => bundle.Path.TrimStart('~')).Any(bundlePath => context.OwinContext.Request.Path.Value.StartsWith(bundlePath, StringComparison.OrdinalIgnoreCase))); }
public static async Task UpdateAccessToken(CookieValidateIdentityContext context) { if (context.Identity == null || !context.Identity.IsAuthenticated) { return; } var expiresAt = context.Identity.FindFirst(ClaimTypes.ExpiresAt); if (expiresAt != null) { DateTime expiryDate; if (!DateTime.TryParseExact(expiresAt.Value, "u", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out expiryDate)) { // If the expiry date can't be parsed then sign the user out. RejectIdentity(context); return; } if (expiryDate < SystemTime.UtcNow) { // If the access token has expired, try and get a new one. var refreshTokenClaim = context.Identity.FindFirst(OidcConstants.AuthorizeResponse.RefreshToken); if (refreshTokenClaim != null) { var oauthClient = DependencyResolver.Current.GetService <IOAuthClient>(); var response = await oauthClient.GetRefreshTokenAsync(refreshTokenClaim.Value); if (response.IsError) { // If the refresh token doesn't work (e.g. it is expired) then sign the user out. RejectIdentity(context); return; } // Create a new cookie from the token response by signing out and in. var identity = response.GenerateUserIdentity(context.Options.AuthenticationType); var auth = context.OwinContext.Authentication; auth.SignOut(context.Options.AuthenticationType); auth.SignIn(context.Properties, identity); context.ReplaceIdentity(identity); } } } }
private async Task UpdateAccessToken(CookieValidateIdentityContext context) { if (context.Identity == null || !context.Identity.IsAuthenticated) { return; } var expiresAt = context.Identity.FindFirst(ClaimTypes.ExpiresAt); if (expiresAt != null) { DateTime expiryDate; if (!DateTime.TryParseExact(expiresAt.Value, "u", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out expiryDate)) { // If the expiry date can't be parsed then sign the user out. RejectIdentity(context); return; } if (expiryDate < SystemTime.UtcNow) { // If the access token has expired, try and get a new one. var refreshTokenClaim = context.Identity.FindFirst(OidcConstants.AuthorizeResponse.RefreshToken); if (refreshTokenClaim != null) { var oauthClient = DependencyResolver.Current.GetService<IOAuthClient>(); var response = await oauthClient.GetRefreshTokenAsync(refreshTokenClaim.Value); if (response.IsError) { // If the refresh token doesn't work (e.g. it is expired) then sign the user out. RejectIdentity(context); return; } // Create a new cookie from the token response by signing out and in. var identity = response.GenerateUserIdentity(context.Options.AuthenticationType); var auth = context.OwinContext.Authentication; auth.SignOut(context.Options.AuthenticationType); auth.SignIn(context.Properties, identity); context.ReplaceIdentity(identity); } } } }
public static async Task TransformClaims(CookieValidateIdentityContext context) { if (context.Identity == null || !context.Identity.IsAuthenticated) { return; } var accessTokenClaim = context.Identity.FindFirst(OidcConstants.AuthorizeResponse.AccessToken); if (accessTokenClaim == null) { RejectIdentity(context); return; } var userInfoClient = DependencyResolver.Current.GetService <IUserInfoClient>(); var userInfo = await userInfoClient.GetUserInfoAsync(accessTokenClaim.Value); if (userInfo.IsError) { RejectIdentity(context); return; } var claims = new List <Claim>(); userInfo.Claims.ToList().ForEach(ui => claims.Add(new Claim(ui.Item1, ui.Item2))); claims.Add(accessTokenClaim); claims.Add(context.Identity.FindFirst(OidcConstants.AuthorizeResponse.RefreshToken)); claims.Add(context.Identity.FindFirst(ClaimTypes.ExpiresAt)); var nameId = context.Identity.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier); if (nameId != null) { claims.Add(nameId); } var id = new ClaimsIdentity(context.Options.AuthenticationType); id.AddClaims(claims); context.ReplaceIdentity(id); }
public async Task OnValidateIdentityTestSuccess(bool isPersistent) { var user = new IdentityUser("test"); var userManager = MockHelpers.MockUserManager <IdentityUser>(); var claimsManager = new Mock <IClaimsIdentityFactory <IdentityUser> >(); var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.Zero }; var options = new Mock <IOptions <IdentityOptions> >(); options.Setup(a => a.Options).Returns(identityOptions); var httpContext = new Mock <HttpContext>(); var contextAccessor = new Mock <IContextAccessor <HttpContext> >(); contextAccessor.Setup(a => a.Value).Returns(httpContext.Object); var signInManager = new Mock <SignInManager <IdentityUser> >(userManager.Object, contextAccessor.Object, claimsManager.Object, options.Object); signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny <ClaimsIdentity>(), user.Id, CancellationToken.None)).ReturnsAsync(user).Verifiable(); signInManager.Setup(s => s.SignInAsync(user, isPersistent, null, CancellationToken.None)).Returns(Task.FromResult(0)).Verifiable(); var services = new ServiceCollection(); services.AddInstance(options.Object); services.AddInstance(signInManager.Object); services.AddInstance <ISecurityStampValidator>(new SecurityStampValidator <IdentityUser>()); httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider()); var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationType); id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); var ticket = new AuthenticationTicket(id, new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow, IsPersistent = isPersistent }); var context = new CookieValidateIdentityContext(httpContext.Object, ticket, new CookieAuthenticationOptions()); Assert.NotNull(context.Properties); Assert.NotNull(context.Options); Assert.NotNull(context.Identity); await SecurityStampValidator.ValidateIdentityAsync(context); Assert.NotNull(context.Identity); signInManager.VerifyAll(); }
public async Task OnValidateIdentityDoesNotRejectsWhenNotExpired() { var user = new IdentityUser("test"); var httpContext = new Mock <HttpContext>(); var userManager = MockHelpers.MockUserManager <IdentityUser>(); var claimsManager = new Mock <IClaimsIdentityFactory <IdentityUser> >(); var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.FromDays(1) }; var options = new Mock <IOptions <IdentityOptions> >(); options.Setup(a => a.Options).Returns(identityOptions); var contextAccessor = new Mock <IContextAccessor <HttpContext> >(); contextAccessor.Setup(a => a.Value).Returns(httpContext.Object); var signInManager = new Mock <SignInManager <IdentityUser> >(userManager.Object, contextAccessor.Object, claimsManager.Object, options.Object); signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny <ClaimsIdentity>(), user.Id, CancellationToken.None)).Throws(new Exception("Shouldn't be called")); signInManager.Setup(s => s.SignInAsync(user, false, null, CancellationToken.None)).Throws(new Exception("Shouldn't be called")); var services = new ServiceCollection(); services.AddInstance(options.Object); services.AddInstance(signInManager.Object); services.AddInstance <ISecurityStampValidator>(new SecurityStampValidator <IdentityUser>()); httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider()); var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationType); id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); var ticket = new AuthenticationTicket(id, new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow }); var context = new CookieValidateIdentityContext(httpContext.Object, ticket, new CookieAuthenticationOptions()); Assert.NotNull(context.Properties); Assert.NotNull(context.Options); Assert.NotNull(context.Identity); await SecurityStampValidator.ValidateIdentityAsync(context); Assert.NotNull(context.Identity); }
private static Task MyCustomValidateIdentity(CookieValidateIdentityContext context) { var expireUtc = context.Properties.ExpiresUtc; var claimType = "myExpireUtc"; var identity = context.Identity; if (identity.HasClaim(c => c.Type == claimType)) { var existingClaim = identity.FindFirst(claimType); identity.RemoveClaim(existingClaim); } if (expireUtc != null) { var newClaim = new Claim(claimType, expireUtc.Value.UtcTicks.ToString()); context.Identity.AddClaim(newClaim); } return(Task.FromResult(0)); }
private static void CheckAccessToken(CookieValidateIdentityContext context) { var expiresAt = context.Identity.FindFirst(ClaimTypes.ExpiresAt); if (expiresAt != null) { DateTime expiryDate; if (!DateTime.TryParseExact(expiresAt.Value, "u", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out expiryDate)) { // If the expiry date can't be parsed then sign the user out. RejectIdentity(context); return; } if (expiryDate < SystemTime.UtcNow) { RejectIdentity(context); return; } } }
/// <summary> /// Not Called on Login /// </summary> /// <param name="context"></param> /// <returns></returns> public static Task ApplicationValidateIdentity(CookieValidateIdentityContext context) { // https://stackoverflow.com/questions/23090706/how-to-know-when-owin-cookie-will-expire // https://stackoverflow.com/questions/41397898/owin-cookieauthentication-onvalidateidentity-doesnt-call-regenerateidentitycall var identity = context.Identity; if (identity.HasClaim(c => c.Type == "expires")) { var existingClaim = identity.FindFirst("expires"); identity.RemoveClaim(existingClaim); } if (context.Properties.ExpiresUtc == null) { return(Task.FromResult(0)); } context.Identity.AddClaim(new Claim("expires", context.Properties.ExpiresUtc.ToString())); return(Task.FromResult(0)); }
public async Task ValidateIdentity(CookieValidateIdentityContext validateIdentityContext) { var claimsIdentity = validateIdentityContext.Identity; if (claimsIdentity.IsAuthenticated) { var userId = claimsIdentity.GetUserId <long>(); var identity = _userRepository.Find(userId); var isValid = identity != null; if (isValid) { validateIdentityContext.ReplaceIdentity(claimsIdentity); } else { validateIdentityContext.RejectIdentity(); } } }
/// <summary> /// Rejects the identity if the stamp changes, and otherwise will sign in a new /// ClaimsIdentity /// </summary> /// <returns></returns> public virtual async Task ValidateAsync(CookieValidateIdentityContext context, ClaimsIdentity identity, CancellationToken cancellationToken = default(CancellationToken)) { var manager = context.HttpContext.RequestServices.GetRequiredService <SignInManager <TUser> >(); var userId = identity.GetUserId(); var user = await manager.ValidateSecurityStampAsync(identity, userId, cancellationToken); if (user != null) { var isPersistent = false; if (context.Properties != null) { isPersistent = context.Properties.IsPersistent; } await manager.SignInAsync(user, isPersistent, authenticationMethod : null, cancellationToken : cancellationToken); } else { context.RejectIdentity(); manager.SignOut(); } }
public async Task OnValidateRejectsUnknownUserIdentityTest() { var owinContext = new OwinContext(); await CreateManager(owinContext); var manager = owinContext.GetUserManager <UserManager <IdentityUser> >(); var user = new IdentityUser("test"); UnitTestHelper.IsSuccess(await manager.CreateAsync(user)); var id = await SignIn(manager, user); UnitTestHelper.IsSuccess(await manager.DeleteAsync(user)); var ticket = new AuthenticationTicket(id, new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow }); var context = new CookieValidateIdentityContext(owinContext, ticket, new CookieAuthenticationOptions()); await SecurityStampValidator.OnValidateIdentity <UserManager <IdentityUser>, IdentityUser>(TimeSpan.Zero, SignIn) .Invoke(context); Assert.Null(context.Identity); }
private static void CheckAccessToken(CookieValidateIdentityContext context) { var expiresAt = context.Identity.FindFirst(ClaimTypes.ExpiresAt); if (expiresAt != null) { DateTime expiryDate; if (!DateTime.TryParseExact(expiresAt.Value, "u", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out expiryDate)) { // If the expiry date can't be parsed then sign the user out. RejectIdentity(context); return; } if (expiryDate < SystemTime.UtcNow) { RejectIdentity(context); return; } } }
public async Task OnValidateIdentityRejectsWhenValidateSecurityStampFails() { var user = new IdentityUser("test"); var httpContext = new Mock <HttpContext>(); var userManager = MockHelpers.MockUserManager <IdentityUser>(); var authManager = new Mock <IAuthenticationManager>(); var claimsManager = new Mock <IClaimsIdentityFactory <IdentityUser> >(); var identityOptions = new IdentityOptions(); var options = new Mock <IOptionsAccessor <IdentityOptions> >(); options.Setup(a => a.Options).Returns(identityOptions); var signInManager = new Mock <SignInManager <IdentityUser> >(userManager.Object, authManager.Object, claimsManager.Object, options.Object); signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny <ClaimsIdentity>(), user.Id, CancellationToken.None)).ReturnsAsync(null).Verifiable(); var services = new ServiceCollection(); services.AddInstance(signInManager.Object); httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider()); var id = new ClaimsIdentity(ClaimsIdentityOptions.DefaultAuthenticationType); id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); var ticket = new AuthenticationTicket(id, new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow }); var context = new CookieValidateIdentityContext(httpContext.Object, ticket, new CookieAuthenticationOptions()); Assert.NotNull(context.Properties); Assert.NotNull(context.Options); Assert.NotNull(context.Identity); await SecurityStampValidator.OnValidateIdentity <IdentityUser>(TimeSpan.Zero).Invoke(context); Assert.Null(context.Identity); signInManager.VerifyAll(); }
public override Task ValidateIdentity(CookieValidateIdentityContext context) { if (context.Identity.IsAuthenticated) { var shortHandUrl = context.Request.Path.ToString() .Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries) .ToList() .FirstOrDefault(); if (shortHandUrl != null && (shortHandUrl.Equals("auth", StringComparison.OrdinalIgnoreCase) || shortHandUrl.StartsWith("signin") || context.Request.Path.Value.Contains(context.Options.LoginPath.Value))) { return(Task.FromResult <object>(null)); } var shortHandUrlClaim = context.Identity.FindFirst(SPAddinClaimTypes.ShortHandUrl).Value; if (!shortHandUrlClaim.Equals(shortHandUrl, StringComparison.OrdinalIgnoreCase)) { context.RejectIdentity(); } } return(Task.FromResult <object>(null)); }
private static void RejectIdentity(CookieValidateIdentityContext context) { context.RejectIdentity(); context.OwinContext.Authentication.SignOut(context.Options.AuthenticationType); }
private async Task OnValidateIdentityImpl(CookieValidateIdentityContext context) { await UpdateAccessToken(context); await TransformClaims(context); }
private async Task TransformClaims(CookieValidateIdentityContext context) { if (context.Identity == null || !context.Identity.IsAuthenticated) { return; } var accessTokenClaim = context.Identity.FindFirst(OidcConstants.AuthorizeResponse.AccessToken); if (accessTokenClaim == null) { RejectIdentity(context); return; } var userInfoClient = DependencyResolver.Current.GetService<IUserInfoClient>(); var userInfo = await userInfoClient.GetUserInfoAsync(accessTokenClaim.Value); if (userInfo.IsError || userInfo.IsHttpError) { RejectIdentity(context); return; } var claims = new List<Claim>(); userInfo.Claims.ToList().ForEach(ui => claims.Add(new Claim(ui.Item1, ui.Item2))); claims.Add(accessTokenClaim); claims.Add(context.Identity.FindFirst(OidcConstants.AuthorizeResponse.RefreshToken)); claims.Add(context.Identity.FindFirst(ClaimTypes.ExpiresAt)); var nameId = context.Identity.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier); if (nameId != null) { claims.Add(nameId); } var id = new ClaimsIdentity(context.Options.AuthenticationType); id.AddClaims(claims); context.ReplaceIdentity(id); }
private static void RejectIdentity(CookieValidateIdentityContext context) { context.RejectIdentity(); context.OwinContext.Authentication.SignOut(context.Options.AuthenticationType); }
private static async Task<bool> VerifySecurityStampAsync(ApplicationUserManager manager, ApplicationUser user, CookieValidateIdentityContext context) { string stamp = context.Identity.FindFirstValue("AspNet.Identity.SecurityStamp"); return (stamp == await manager.GetSecurityStampAsync(context.Identity.GetUserId())); }
public override Task ValidateIdentity(CookieValidateIdentityContext context) { return(base.ValidateIdentity(context)); }
private static async Task ValidateAccessToken(CookieValidateIdentityContext ctx, string tokenEndpoint, string clientId, string clientSecret) { var claimsIdentity = ctx?.Identity; if (claimsIdentity == null) { return; } DateTimeOffset expiresAt; DateTimeOffset.TryParse(claimsIdentity.FindFirst("expires_at")?.Value, out expiresAt); try { //Check for expired token if (DateTimeOffset.UtcNow.AddMinutes(5) >= expiresAt) { Trace.WriteLine($"Token expiring, expiresAt: {expiresAt}, now: {DateTimeOffset.UtcNow}"); string refreshToken = claimsIdentity.FindFirst("refresh_token")?.Value; if (refreshToken == null) { Trace.WriteLine("No refresh token, rejecting identity"); ctx.RejectIdentity(); return; } var tokenResponse = await StsTokenHelper.RefreshToken(_client, tokenEndpoint, clientId, clientSecret, refreshToken); if (tokenResponse.IsError) { Trace.WriteLine("RefreshToken resulted in error, rejecting identity"); ctx.RejectIdentity(); return; } claimsIdentity.AddOrUpdateClaim("access_token", tokenResponse.AccessToken); claimsIdentity.AddOrUpdateClaim("expires_at", tokenResponse.ExpiresUtc().ToString()); claimsIdentity.AddOrUpdateClaim("refresh_token", tokenResponse.RefreshToken); //ctx.ReplaceIdentity(claimsIdentity); // kill old cookie ctx.OwinContext.Authentication.SignOut(ctx.Options.AuthenticationType); // sign in again var authenticationProperties = new AuthenticationProperties { IsPersistent = ctx.Properties.IsPersistent }; ctx.OwinContext.Authentication.SignIn(authenticationProperties, claimsIdentity); } } catch (Exception ex) { Trace.WriteLine($"Exception occurred, rejecting identity\r\n{ex.Message}\r\n{ex.StackTrace}"); ctx.RejectIdentity(); } }
public Task ValidateIdentity(CookieValidateIdentityContext context) { return(Task.FromResult(0)); //throw new NotImplementedException(); }
private static async Task OnValidateIdentity(CookieValidateIdentityContext context) { CheckAccessToken(context); await IdentityValidationHelper.TransformClaims(context); }
private async Task OnValidateIdentityImpl(CookieValidateIdentityContext context) { await UpdateAccessToken(context); await TransformClaims(context); }
private static async Task <bool> VerifySecurityStampAsync(ApplicationUserManager manager, ApplicationUser user, CookieValidateIdentityContext context) { string stamp = context.Identity.FindFirstValue("AspNet.Identity.SecurityStamp"); return(stamp == await manager.GetSecurityStampAsync(context.Identity.GetUserId())); }
/// <summary> /// Implements the interface method by invoking the related delegate method /// </summary> /// <param name="context"></param> /// <returns></returns> public virtual Task ValidateIdentity(CookieValidateIdentityContext context) { return OnValidateIdentity.Invoke(context); }
public Task ValidateIdentity(CookieValidateIdentityContext context) { return TaskAsyncHelper.Empty; }
private static async Task ProcessIdentity(TimeSpan validateInterval, CookieValidateIdentityContext context) { if (context.Request.Path.HasValue && (context.Request.Path.Value.EndsWith(".css") || context.Request.Path.Value.EndsWith(".js") || context.Request.Path.Value.EndsWith(".map") || context.Request.Path.Value.EndsWith(".woff") || context.Request.Path.Value.EndsWith(".woff2") || context.Request.Path.Value.EndsWith(".png") || context.Request.Path.Value.EndsWith(".gif") || context.Request.Path.Value.EndsWith(".jpg") || context.Request.Path.Value.EndsWith(".jpeg") ) ) { return; } try { var currentUtc = DateTimeOffset.UtcNow; if (context.Options?.SystemClock != null) { currentUtc = context.Options.SystemClock.UtcNow; } var issuedUtc = context.Properties.IssuedUtc; // Only validate if enough time has elapsed var validate = (issuedUtc == null); if (issuedUtc != null) { var timeElapsed = currentUtc.Subtract(issuedUtc.Value); validate = timeElapsed > validateInterval; } if (validate) { var manager = context.OwinContext.GetUserManager <UserManager>(); var userId = context.Identity.GetUserId(); if (manager != null && !string.IsNullOrWhiteSpace(userId)) { var user = await manager.FindByIdAsync(userId); var reject = true; // Refresh the identity if the stamp matches, otherwise reject if (user != null && await VerifySecurityStampAsync(manager, user, context) //&& await VerifyClientIdAsync(user, context) ) { reject = false; // Regenerate fresh claims if possible and resign in var identity = await user.GenerateUserIdentityAsync(manager, context.Identity.GetIsPersistent()); if (identity != null) { context.OwinContext.Authentication.SignIn(identity); var newResponseGrant = context.OwinContext.Authentication.AuthenticationResponseGrant; if (newResponseGrant != null) { newResponseGrant.Properties.IsPersistent = context.Identity.GetIsPersistent(); } } } if (reject) { if (user != null) { int clientId; if (int.TryParse(context.Identity.FindFirstValue("AspNet.Identity.ClientId"), out clientId)) { manager.SignOutClientById(user, clientId); } } context.RejectIdentity(); context.OwinContext.Authentication.SignOut(context.Options.AuthenticationType); } } } } catch (Exception e) { LogManager.GetLogger(typeof(ApplicationCookieIdentityValidator)).Error("Error in validate cookie.", e); throw; } }
private static async Task OnValidateIdentity(CookieValidateIdentityContext context) { CheckAccessToken(context); await IdentityValidationHelper.TransformClaims(context); }
public Task ValidateIdentity(CookieValidateIdentityContext context) { return(TaskAsyncHelper.Empty); }
private static async Task <bool> VerifySecurityStampAsync(ApplicationUserManager manager, CookieValidateIdentityContext context) { var stamp = context.Identity.FindFirstValue("AspNet.Identity.SecurityStamp"); var stampUser = await manager.GetSecurityStampAsync(context.Identity.GetUserId <int>()); //arrumar return(true); }
private static Task <bool> VerifyClientIdAsync(ApplicationUserManager manager, ApplicationUser user, CookieValidateIdentityContext context) { string clientId = context.Identity.FindFirstValue("AspNet.Identity.ClientId"); if (!string.IsNullOrEmpty(clientId) && user.Clients.Any(c => c.Id.ToString() == clientId)) { user.CurrentClientId = clientId; return(Task.FromResult(true)); } return(Task.FromResult(false)); }
private static async Task <bool> VerifySecurityStampAsync <TManager, TUser>(TManager manager, TUser user, CookieValidateIdentityContext context) where TManager : UserManager where TUser : IdentityUser { var stamp = context.Identity.FindFirstValue(Constants.DefaultSecurityStampClaimType); return(stamp == await manager.GetSecurityStampAsync(user.User.UserName)); }