public ActionResult Index(string token) { try { var validationParameters = new TokenValidationParameters { IssuerSigningToken = new BinarySecretSecurityToken( TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["auth0:ClientSecret"])), ValidIssuer = ConfigurationManager.AppSettings["auth0:Domain"], ValidAudience = ConfigurationManager.AppSettings["auth0:ClientId"] }; var handler = new JwtSecurityTokenHandler(); SecurityToken securityToken; ClaimsPrincipal principal = handler.ValidateToken(token, validationParameters, out securityToken); ClaimsIdentity identity = principal.Identity as ClaimsIdentity; identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Auth0")); identity.AddClaim(new Claim(ClaimTypes.Name, identity.FindFirst(ClaimTypes.Email).Value)); var sessionToken = new SessionSecurityToken(principal, TimeSpan.FromMinutes(15)); FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionToken); return RedirectToAction("Change"); } catch (Exception ex) { return RedirectToAction("Unauthorized"); } }
public virtual void SignIn(string username) { // find user var account = this.userRepository.GetByUsername(username); if (account == null) throw new ArgumentException("Invalid username"); // gather claims var claims = (from uc in account.Claims select new Claim(uc.Type, uc.Value)).ToList(); claims.Insert(0, new Claim(ClaimTypes.Email, account.Email)); claims.Insert(0, new Claim(ClaimTypes.AuthenticationMethod, "password")); claims.Insert(0, new Claim(ClaimTypes.AuthenticationInstant, DateTime.UtcNow.ToString("s"))); claims.Insert(0, new Claim(ClaimTypes.NameIdentifier, account.Username)); claims.Insert(0, new Claim(ClaimTypes.Name, account.Username)); // create principal/identity var id = new ClaimsIdentity(claims, "Forms"); var cp = new ClaimsPrincipal(id); // claims transform cp = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager.Authenticate(String.Empty, cp); // issue cookie var sam = FederatedAuthentication.SessionAuthenticationModule; if (sam == null) throw new Exception("SessionAuthenticationModule is not configured and it needs to be."); var token = new SessionSecurityToken(cp, TimeSpan.FromHours(DefaultTokenLifetime_InHours)); sam.WriteSessionTokenToCookie(token); }
public override void AddOrUpdate(System.IdentityModel.Tokens.SessionSecurityTokenCacheKey key, System.IdentityModel.Tokens.SessionSecurityToken value, DateTime expiryTime) { string tokenId = null; var claimsIdentity = Thread.CurrentPrincipal.Identity as ClaimsIdentity; if (claimsIdentity != null && claimsIdentity.BootstrapContext != null) { var bootstrap = claimsIdentity.BootstrapContext as BootstrapContext; if (bootstrap != null && bootstrap.SecurityToken != null) { tokenId = bootstrap.SecurityToken.Id; } } var data = cache.AddOrUpdate(new bUtility.TokenCache.Types.SessionSecurity.SessionCacheEntry { EndpointId = key.EndpointId, ContextId = key?.ContextId?.ToString(), KeyGeneration = GetKeyGenerationString(key), ExpiryTime = expiryTime, SessionSecurityTokenValue = value, UserName = Thread.CurrentPrincipal.Identity.Name, SessionSecurityTokenID = tokenId }); if (data) { _internalCache.AddOrUpdate(key, value, expiryTime); } }
/// <summary> /// Validates a token and returns its claims. /// </summary> /// <param name="token">The <see cref="SessionSecurityToken"/> to validate.</param> /// <param name="endpointId">Identifier to the endpoint to which the token is scoped.</param> /// <returns>A <see cref="ReadOnlyCollection{T}"/> of <see cref="ClaimsIdentity"/> representing the identities contained in the token.</returns> /// <exception cref="ArgumentNullException">The parameter 'token' is null.</exception> /// <exception cref="ArgumentNullException">The parameter 'endpointId' is null.</exception> /// <exception cref="SecurityTokenException">token.EndpointId != endpointId.</exception> public virtual ReadOnlyCollection <ClaimsIdentity> ValidateToken(SessionSecurityToken token, string endpointId) { if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); } if (endpointId == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpointId"); } // We consider SessionTokens with String.Empty as the endpoint Id to be // globally scoped tokens. This in insecure, we are allowing this only // for compatibility with customers who have overriden SessionSecurityTokenHandler. if (!string.IsNullOrEmpty(token.EndpointId)) { if (token.EndpointId != endpointId) { string errorMessage = SR.GetString(SR.ID4291, token); this.TraceTokenValidationFailure(token, errorMessage); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(errorMessage)); } } return(this.ValidateToken(token)); }
/// <summary> /// Checks the valid time of a SecurityToken. /// </summary> /// <remarks> /// The token is invalid if the securityToken.ValidFrom > DateTime.UtcNow OR securityToken.ValidTo < DateTime.UtcNow /// </remarks> /// <param name="token">The <see cref="SessionSecurityToken"/> to validate.</param> /// <exception cref="ArgumentNullException">Thrown if 'securityToken' is null.</exception> /// <exception cref="InvalidOperationException">Thrown if 'Configuration' is null.</exception> /// <exception cref="SecurityTokenNotYetValidException">Thrown if securityToken.ValidFrom > DateTime.UtcNow.</exception> /// <exception cref="SecurityTokenExpiredException">Thrown if securityToken.ValidTo < DateTime.UtcNow.</exception> protected virtual void ValidateSession(SessionSecurityToken securityToken) { if (securityToken == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityToken"); } if (this.Configuration == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4274))); } Fx.Assert(this.Configuration != null, SR.GetString(SR.ID8027)); DateTime utcNow = DateTime.UtcNow; // apply clock skew here. DateTime maxTime = DateTimeUtil.Add(utcNow, Configuration.MaxClockSkew); DateTime minTime = DateTimeUtil.Add(utcNow, -Configuration.MaxClockSkew); if (securityToken.ValidFrom > maxTime) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenNotYetValidException(SR.GetString(SR.ID4255, securityToken.ValidTo, securityToken.ValidFrom, utcNow))); } if (securityToken.ValidTo < minTime) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenExpiredException(SR.GetString(SR.ID4255, securityToken.ValidTo, securityToken.ValidFrom, utcNow))); } }
public void Login(User user) { var claims = new List<Claim>(new[] { new Claim(ClaimTypes.NameIdentifier, user.Username), new Claim(ClaimTypes.Name, user.Name) }); if (!string.IsNullOrWhiteSpace(user.Email)) { claims.Add(new Claim(ClaimTypes.Email, user.Email)); } claims.AddRange(user.Roles.Select(role => new Claim(ClaimTypes.Role, role.Name))); var identity = new ClaimsIdentity(claims, "Forms"); var principal = new ClaimsPrincipal(identity); var sessionToken = new SessionSecurityToken(principal); var authenticationModule = FederatedAuthentication.SessionAuthenticationModule; // Persist the authentication cookie. authenticationModule.WriteSessionTokenToCookie(sessionToken); // Set the current user for the current request Thread.CurrentPrincipal = principal; }
/// <summary> /// Save user state to cookie /// </summary> /// <param name="user">User to save to cookie</param> /// <returns></returns> private static ClaimsPrincipal SaveToCookie(ClaimsIdentity user) { var claimsPrincipal = new ClaimsPrincipal(user); var sessionSecurityToken = new SessionSecurityToken(claimsPrincipal, TimeSpan.FromDays(365)); FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionSecurityToken); return claimsPrincipal; }
private void EstablishSession(ClaimsPrincipal principal) { if (HttpContext.Current != null) { var sessionToken = new SessionSecurityToken(principal); FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionToken); } }
private void CreateSession(ClaimsPrincipal transformedPrincipal) { SessionSecurityToken sessionSecurityToken = new SessionSecurityToken(transformedPrincipal, TimeSpan.FromHours(8)); sessionSecurityToken.IsPersistent = false; sessionSecurityToken.IsReferenceMode = true; FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionSecurityToken); FederatedAuthentication.SessionAuthenticationModule.SessionSecurityTokenReceived += SessionAuthenticationModule_SessionSecurityTokenReceived; }
public static void EstablishSession(ClaimsPrincipal principal) { var sessionToken = new SessionSecurityToken(principal, TimeSpan.FromHours(12)) { // IsReferenceMode = true // cache on server - caused me some problems }; FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionToken); }
private static void ApplyPrincipal(CommandResult commandResult) { if (commandResult.Principal != null) { var sessionToken = new SessionSecurityToken(commandResult.Principal); FederatedAuthentication.SessionAuthenticationModule .AuthenticateSessionSecurityToken(sessionToken, true); } }
private static ClaimsPrincipal AuthenticatePrincipalAndSerialize(ClaimsPrincipal principal) { var outputprincipal = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager .Authenticate(string.Empty, principal); var sessionToken = new SessionSecurityToken(outputprincipal, TimeSpan.FromHours(1)) { IsPersistent = true }; FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionToken); return outputprincipal; }
public static void Login( HttpContextBase httpContext, bool rememberMe) { var claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal; // Encrypts the claims principal using a 128-bit key before storing it into cache. var sessionSecurityToken = new SessionSecurityToken(claimsPrincipal); httpContext.Cache[string.Concat(CacheKeyNames.Identity, UserId)] = sessionSecurityToken; FormsAuthentication.SetAuthCookie(UserId.ToString(Format.English), rememberMe); }
public virtual void SignIn(string tenant, string username) { Tracing.Information(String.Format("[ClaimsBasedAuthenticationService.Signin] called: {0}, {1}", tenant, username)); if (!SecuritySettings.Instance.MultiTenant) { tenant = SecuritySettings.Instance.DefaultTenant; } if (String.IsNullOrWhiteSpace(tenant)) throw new ArgumentException("tenant"); if (String.IsNullOrWhiteSpace(username)) throw new ArgumentException("username"); // find user var account = this.userService.GetByUsername(tenant, username); if (account == null) throw new ArgumentException("Invalid username"); // gather claims var claims = (from uc in account.Claims select new Claim(uc.Type, uc.Value)).ToList(); if (!String.IsNullOrWhiteSpace(account.Email)) { claims.Insert(0, new Claim(ClaimTypes.Email, account.Email)); } claims.Insert(0, new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Password)); claims.Insert(0, new Claim(ClaimTypes.AuthenticationInstant, DateTime.UtcNow.ToString("s"))); claims.Insert(0, new Claim(ClaimTypes.Name, account.Username)); claims.Insert(0, new Claim(MembershipRebootConstants.ClaimTypes.Tenant, account.Tenant)); claims.Insert(0, new Claim(ClaimTypes.NameIdentifier, String.Format("{0}:{1}", account.Tenant, account.Username))); // create principal/identity var id = new ClaimsIdentity(claims, "Forms"); var cp = new ClaimsPrincipal(id); // claims transform cp = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager.Authenticate(String.Empty, cp); // issue cookie var sam = FederatedAuthentication.SessionAuthenticationModule; if (sam == null) { Tracing.Verbose("[ClaimsBasedAuthenticationService.Signin] SessionAuthenticationModule is not configured"); throw new Exception("SessionAuthenticationModule is not configured and it needs to be."); } var token = new SessionSecurityToken(cp, TimeSpan.FromHours(DefaultTokenLifetime_InHours)); sam.WriteSessionTokenToCookie(token); Tracing.Verbose(String.Format("[ClaimsBasedAuthenticationService.Signin] cookie issued: {0}", claims.GetValue(ClaimTypes.NameIdentifier))); }
public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal) { //only try this if the user is authenticated if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated) { //get hold of the session authentication module that allows us to read and read auth cookies var sam = FederatedAuthentication.SessionAuthenticationModule; SessionSecurityToken token; //try to get the session from the token - check logs if this is ever true if (sam.TryReadSessionTokenFromCookie(out token)) { Log.Info("read token from cookie - not sure this should happen"); //is there is no illuminate issued token in the cookie inject illuminate specific ones and save session if (!token.ClaimsPrincipal.HasClaim(c => c.Type == IlluminateClaimTypes.UserId)) { var nameIdentifierValue = token.ClaimsPrincipal.FindFirst(c => c.Type == ClaimTypes.NameIdentifier).Value; //inject the new claims token.ClaimsPrincipal.Identities.First().AddClaims(GetInjectedClaims(nameIdentifierValue)); //save the session to the cookie sam.WriteSessionTokenToCookie(token); } } var claimsID = (ClaimsIdentity) incomingPrincipal.Identity; //check if the claims principle has an illuminate specific token - if it doesn't add them if (!claimsID.HasClaim(c => c.Type == IlluminateClaimTypes.UserId)) { var nameIdentifierValue = claimsID.FindFirst(c => c.Type == ClaimTypes.NameIdentifier).Value; claimsID.AddClaims(GetInjectedClaims(nameIdentifierValue)); Log.Info(string.Format("injected claims for user {0}",nameIdentifierValue)); //write the session to the cookie so its available next time var securityToken = new SessionSecurityToken(incomingPrincipal); Log.Info(string.Format("created new session security token ")); try { sam.WriteSessionTokenToCookie(securityToken); } catch (Exception ex) { Log.Error(string.Format("error writing session token to cookie"),ex); } Log.Info(string.Format("created new session security token ")); } } return incomingPrincipal; }
public static void SignInSessionAuthenticationModule(this CommandResult commandResult) { if (commandResult == null) { throw new ArgumentNullException("commandResult"); } // Ignore this if we're not running inside IIS, e.g. in unit tests. if (commandResult.Principal != null && HttpContext.Current != null) { var sessionToken = new SessionSecurityToken(commandResult.Principal); FederatedAuthentication.SessionAuthenticationModule .AuthenticateSessionSecurityToken(sessionToken, true); } }
/// <summary> /// Validates a <see cref="SessionSecurityToken"/>. /// </summary> /// <param name="token">The <see cref="SessionSecurityToken"/> to validate.</param> /// <returns>A <see cref="ReadOnlyCollection{T}"/> of <see cref="ClaimsIdentity"/> representing the identities contained in the token.</returns> /// <exception cref="ArgumentNullException">The parameter 'token' is null.</exception> /// <exception cref="ArgumentException">The token is not assignable from <see cref="SessionSecurityToken"/>.</exception> public override ReadOnlyCollection <ClaimsIdentity> ValidateToken(SecurityToken token) { if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); } SessionSecurityToken sessionToken = token as SessionSecurityToken; if (sessionToken == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4292, token.GetType().ToString(), this.GetType().ToString()))); } try { if (DiagnosticUtility.ShouldTrace(TraceEventType.Verbose)) { TraceUtility.TraceEvent( TraceEventType.Verbose, TraceCode.Diagnostics, SR.GetString(SR.TraceValidateToken), new SecurityTraceRecordHelper.TokenTraceRecord(token), null, null); } this.ValidateSession(sessionToken); this.TraceTokenValidationSuccess(token); List <ClaimsIdentity> identitites = new List <ClaimsIdentity>(1); identitites.AddRange(sessionToken.ClaimsPrincipal.Identities); return(identitites.AsReadOnly()); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.TraceTokenValidationFailure(token, e.Message); throw e; } }
public virtual void SignIn(User user, bool isPersistant = false) { Tracing.Information(String.Format("[ClaimsBasedAuthenticationService.Signin] called: {0}", user.Username)); if (String.IsNullOrWhiteSpace(user.Username)) throw new ArgumentException("username"); // gather claims var claims = new List<Claim>(); foreach (UserClaim uc in user.Claims) claims.Add(new Claim(uc.Type, uc.Value)); if (!String.IsNullOrWhiteSpace(user.Email)) { claims.Insert(0, new Claim(ClaimTypes.Email, user.Email)); } claims.Insert(0, new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Password)); claims.Insert(0, new Claim(ClaimTypes.AuthenticationInstant, DateTime.UtcNow.ToString("s"))); claims.Insert(0, new Claim(ClaimTypes.Name, user.Username)); claims.Insert(0, new Claim(ClaimTypes.NameIdentifier, user.Username)); // create principal/identity var id = new ClaimsIdentity(claims, "Forms"); var cp = new ClaimsPrincipal(id); // claims transform cp = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager .Authenticate(String.Empty, cp); // issue cookie var sam = FederatedAuthentication.SessionAuthenticationModule; if (sam == null) throw new Exception("SessionAuthenticationModule is not configured and it needs to be."); var token = new SessionSecurityToken(cp, isPersistant ? FormsAuthentication.Timeout : TimeSpan.FromMinutes(SessionHelpers.GetSessionTimeoutInMinutes)) { IsPersistent = isPersistant }; sam.WriteSessionTokenToCookie(token); Tracing.Verbose(String.Format("[ClaimsBasedAuthenticationService.Signin] cookie issued: {0}", claims.GetValue(ClaimTypes.NameIdentifier))); }
public override void AddOrUpdate( SessionSecurityTokenCacheKey key, SessionSecurityToken value, DateTime expiryTime) { if (key == null) throw new ArgumentNullException("key"); inner.AddOrUpdate(key, value, expiryTime); var item = new TokenCacheItem { Key = key.ToString(), Expires = expiryTime, Token = TokenToBytes(value), }; tokenCacheRepository.AddOrUpdate(item); }
/// <summary> /// Writes the token into a byte array. /// </summary> /// <param name="sessionToken">The SessionSecurityToken to write.</param> /// <exception cref="ArgumentNullException">Thrown if 'sessiontoken' is null.</exception> /// <returns>An encoded byte array.</returns> public virtual byte[] WriteToken(SessionSecurityToken sessionToken) { if (sessionToken == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("sessionToken"); } using (MemoryStream ms = new MemoryStream()) { using (XmlWriter writer = XmlWriter.Create(ms)) { WriteToken(writer, sessionToken); writer.Flush(); } return(ms.ToArray()); } }
/// <summary> /// Attempts to add an entry to the cache or update an existing one. /// </summary> /// <param name="key">The key for the entry to be added.</param> /// <param name="value">The security token to be added to the cache.</param> /// <param name="expirationTime">The expiration time for this entry.</param> public override void AddOrUpdate(SessionSecurityTokenCacheKey key, SessionSecurityToken value, DateTime expirationTime) { if (key == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("key"); } lock (this.syncRoot) { this.Purge(); this.Remove(key); // Add the new entry to the cache and make it the MRU element CacheEntry entry = new CacheEntry(); entry.Node = this.mruList.AddFirst(key); entry.Value = value; this.items.Add(key, entry); this.mruEntry = entry; } }
/// <summary> /// Sign the user in with Claims. /// </summary> /// <param name="userData">UserData: the user data.</param> /// <param name="tokenLifetimeInMinutes">int: cookie token lifetime.</param> public void SignIn(IUserData userData, int tokenLifetimeInMinutes = 60*24) { // Create the identity & then principal. var identity = new ClaimsIdentity(userData.ToClaims(), "Forms"); var principal = new ClaimsPrincipal(identity); // Claims transform. principal = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager .Authenticate(String.Empty, principal); // Issue the cookie. var sam = FederatedAuthentication.SessionAuthenticationModule; if (sam == null) { throw new Exception("SessionAuthenticationModule is not configured and it needs to be."); } var token = new SessionSecurityToken(principal, TimeSpan.FromHours(tokenLifetimeInMinutes)); sam.WriteSessionTokenToCookie(token); }
public async Task<ActionResult> Callback() { var result = await OAuth2Client.Instance.ProcessCallbackAsync(); if (result.Error != null) { return Content(result.Error + "<br>" + result.ErrorDetails); } var sam = FederatedAuthentication.SessionAuthenticationModule; if (sam != null) { var cp = new ClaimsPrincipal(new ClaimsIdentity(result.Claims, "OAuth")); var transformer = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager; if (transformer != null) { cp = transformer.Authenticate(String.Empty, cp); } var token = new SessionSecurityToken(cp); sam.WriteSessionTokenToCookie(token); } return Redirect(result.ReturnUrl); }
public static void SignInSessionAuthenticationModule(this CommandResult commandResult) { if (commandResult == null) { throw new ArgumentNullException(nameof(commandResult)); } // Ignore this if we're not running inside IIS, e.g. in unit tests. if (commandResult.Principal != null && HttpContext.Current != null) { var sessionToken = new SessionSecurityToken(commandResult.Principal); if (FederatedAuthentication.SessionAuthenticationModule == null) { throw new InvalidOperationException( "FederatedAuthentication.SessionAuthenticationModule is null, make sure you have loaded the SessionAuthenticationModule in web.config. " + "See https://github.com/KentorIT/authservices/blob/master/doc/Configuration.md#loading-modules"); } FederatedAuthentication.SessionAuthenticationModule .AuthenticateSessionSecurityToken(sessionToken, true); } }
/// <summary> /// Returns the Session Security Token corresponding to the specified key exists in the cache. Also if it exists, marks it as MRU. /// </summary> /// <param name="key">Specifies the key for the entry to be retrieved.</param> /// <returns>Returns the Session Security Token from the cache if found, otherwise, null.</returns> public override SessionSecurityToken Get(SessionSecurityTokenCacheKey key) { if (key == null) { return(null); } // If found, make the entry most recently used SessionSecurityToken sessionToken = null; CacheEntry entry; bool found; lock (this.syncRoot) { // first check our MRU item if (this.mruEntry.Node != null && key != null && key.Equals(this.mruEntry.Node.Value)) { return(this.mruEntry.Value); } found = this.items.TryGetValue(key, out entry); if (found) { sessionToken = entry.Value; // Move the node to the head of the MRU list if it's not already there if (this.mruList.Count > 1 && !object.ReferenceEquals(this.mruList.First, entry.Node)) { this.mruList.Remove(entry.Node); this.mruList.AddFirst(entry.Node); this.mruEntry = entry; } } } return(sessionToken); }
protected override void IssueToken(ClaimsPrincipal principal, TimeSpan? tokenLifetime = null, bool? persistentCookie = null) { if (principal == null) throw new ArgumentNullException("principal"); if (tokenLifetime == null) { var handler = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers[typeof(SessionSecurityToken)] as SessionSecurityTokenHandler; if (handler == null) { Tracing.Verbose("[SamAuthenticationService.IssueToken] SessionSecurityTokenHandler is not configured"); throw new Exception("SessionSecurityTokenHandler is not configured and it needs to be."); } tokenLifetime = handler.TokenLifetime; } if (persistentCookie == null) { persistentCookie = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration.PersistentCookiesOnPassiveRedirects; } var sam = FederatedAuthentication.SessionAuthenticationModule; if (sam == null) { Tracing.Verbose("[SamAuthenticationService.IssueToken] SessionAuthenticationModule is not configured"); throw new Exception("SessionAuthenticationModule is not configured and it needs to be."); } var token = new SessionSecurityToken(principal, tokenLifetime.Value); token.IsPersistent = persistentCookie.Value; token.IsReferenceMode = sam.IsReferenceMode; sam.WriteSessionTokenToCookie(token); Tracing.Verbose("[SamAuthenticationService.IssueToken] cookie issued: {0}", principal.Claims.GetValue(ClaimTypes.NameIdentifier)); }
public async Task<ActionResult> Callback() { var result = await OAuth2Client.Instance.ProcessCallbackAsync(); if (result.Error != null) { return Content(result.Error + "<br>" + result.ErrorDetails); } var sam = FederatedAuthentication.SessionAuthenticationModule; if (sam == null) throw new Exception("SessionAuthenticationModule not registered."); var cp = new ClaimsPrincipal(new ClaimsIdentity(result.Claims, "OAuth")); var id = cp.Identities.First(); var authInstantClaim = new Claim(ClaimTypes.AuthenticationInstant, DateTime.UtcNow.ToString("s")); id.AddClaim(authInstantClaim); var idpClaim = new Claim(Constants.ClaimTypes.IdentityProvider, result.ProviderName); id.AddClaim(idpClaim); var token = new SessionSecurityToken(cp); sam.WriteSessionTokenToCookie(token); return RedirectToAction("Index"); }
public async Task<ActionResult> Callback() { var result = await OAuth2Client.Instance.ProcessCallbackAsync(); if (result.Error != null) { return Content(result.Error + "<br>" + result.ErrorDetails); } var sam = FederatedAuthentication.SessionAuthenticationModule; if (sam == null) throw new Exception("SessionAuthenticationModule not registered."); var cp = new ClaimsPrincipal(new ClaimsIdentity(result.Claims, "OAuth")); var id = cp.Identities.First(); var authInstantClaim = new Claim(ClaimTypes.AuthenticationInstant, DateTime.UtcNow.ToString("s")); id.AddClaim(authInstantClaim); var idpClaim = new Claim(Constants.ClaimTypes.IdentityProvider, result.ProviderName); id.AddClaim(idpClaim); var transformer = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager; if (transformer != null) { cp = transformer.Authenticate(String.Empty, cp); } var token = new SessionSecurityToken(cp); sam.WriteSessionTokenToCookie(token); if (!String.IsNullOrWhiteSpace(result.ReturnUrl)) { return Redirect(result.ReturnUrl); } else { return Redirect("~"); } }
/// <summary> /// Writes the token into a byte array. /// </summary> /// <param name="sessionToken">The SessionSecurityToken to write.</param> /// <exception cref="ArgumentNullException">Thrown if 'sessiontoken' is null.</exception> /// <returns>An encoded byte array.</returns> public virtual byte[] WriteToken(SessionSecurityToken sessionToken) { if (sessionToken == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("sessionToken"); } using (MemoryStream ms = new MemoryStream()) { using (XmlWriter writer = XmlWriter.Create(ms)) { WriteToken(writer, sessionToken); writer.Flush(); } return ms.ToArray(); } }
/// <summary> /// Validates a token and returns its claims. /// </summary> /// <param name="token">The <see cref="SessionSecurityToken"/> to validate.</param> /// <param name="endpointId">Identifier to the endpoint to which the token is scoped.</param> /// <returns>A <see cref="ReadOnlyCollection{T}"/> of <see cref="ClaimsIdentity"/> representing the identities contained in the token.</returns> /// <exception cref="ArgumentNullException">The parameter 'token' is null.</exception> /// <exception cref="ArgumentNullException">The parameter 'endpointId' is null.</exception> /// <exception cref="SecurityTokenException">token.EndpointId != endpointId.</exception> public virtual ReadOnlyCollection<ClaimsIdentity> ValidateToken(SessionSecurityToken token, string endpointId) { if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); } if (endpointId == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpointId"); } // We consider SessionTokens with String.Empty as the endpoint Id to be // globally scoped tokens. This in insecure, we are allowing this only // for compatibility with customers who have overriden SessionSecurityTokenHandler. if (!string.IsNullOrEmpty(token.EndpointId)) { if (token.EndpointId != endpointId) { string errorMessage = SR.GetString(SR.ID4291, token); this.TraceTokenValidationFailure(token, errorMessage); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(errorMessage)); } } return this.ValidateToken(token); }
private void CreateSession(ClaimsPrincipal transformedPrincipal) { var sessionSecurityToken = new SessionSecurityToken(transformedPrincipal, TimeSpan.FromHours(8)); FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionSecurityToken); }
public virtual byte[] WriteToken(SessionSecurityToken sessionToken) { throw new NotImplementedException(); }
public virtual ReadOnlyCollection <ClaimsIdentity> ValidateToken(SessionSecurityToken token, string endpointId) { throw new NotImplementedException(); }
void WriteSessionToken(XmlWriter writer, SessionSecurityToken sessionToken) { SessionSecurityTokenHandler ssth = GetOrCreateSessionSecurityTokenHandler(); XmlDictionaryWriter dictionaryWriter = XmlDictionaryWriter.CreateDictionaryWriter(writer); ssth.WriteToken(dictionaryWriter, sessionToken); }
/// <summary> /// Reads the SessionSecurityToken from the given reader. /// </summary> /// <param name="reader">XmlReader over the SessionSecurityToken.</param> /// <param name="tokenResolver">SecurityTokenResolver that can used to resolve SessionSecurityToken.</param> /// <returns>An instance of <see cref="SessionSecurityToken"/>.</returns> /// <exception cref="ArgumentNullException">The input argument 'reader' is null.</exception> /// <exception cref="SecurityTokenException">The 'reader' is not positioned at a SessionSecurityToken /// or the SessionSecurityToken cannot be read.</exception> public override SecurityToken ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } if (tokenResolver == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenResolver"); } byte[] encodedCookie = null; SysUniqueId contextId = null; SysUniqueId keyGeneration = null; string ns = null; string identifier = null; string instance = null; SecurityToken securityContextToken = null; SessionDictionary dictionary = SessionDictionary.Instance; XmlDictionaryReader dicReader = XmlDictionaryReader.CreateDictionaryReader(reader); if (dicReader.IsStartElement(WSSecureConversationFeb2005Constants.ElementNames.Name, WSSecureConversationFeb2005Constants.Namespace)) { ns = WSSecureConversationFeb2005Constants.Namespace; identifier = WSSecureConversationFeb2005Constants.ElementNames.Identifier; instance = WSSecureConversationFeb2005Constants.ElementNames.Instance; } else if (dicReader.IsStartElement(WSSecureConversation13Constants.ElementNames.Name, WSSecureConversation13Constants.Namespace)) { ns = WSSecureConversation13Constants.Namespace; identifier = WSSecureConversation13Constants.ElementNames.Identifier; instance = WSSecureConversation13Constants.ElementNames.Instance; } else { // // Something is wrong // throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException( SR.GetString(SR.ID4230, WSSecureConversationFeb2005Constants.ElementNames.Name, dicReader.Name))); } string id = dicReader.GetAttribute(WSUtilityConstants.Attributes.IdAttribute, WSUtilityConstants.NamespaceURI); dicReader.ReadFullStartElement(); if (!dicReader.IsStartElement(identifier, ns)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException( SR.GetString(SR.ID4230, WSSecureConversation13Constants.ElementNames.Identifier, dicReader.Name))); } contextId = dicReader.ReadElementContentAsUniqueId(); if (contextId == null || string.IsNullOrEmpty(contextId.ToString())) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4242))); } // // The token can be a renewed token, in which case we need to know the // instance id, which will be the secondary key to the context id for // cache lookups // if (dicReader.IsStartElement(instance, ns)) { keyGeneration = dicReader.ReadElementContentAsUniqueId(); } if (dicReader.IsStartElement(CookieElementName, CookieNamespace)) { // Get the token from the Cache, which is returned as an SCT SecurityToken cachedToken = null; SecurityContextKeyIdentifierClause sctClause = null; if (keyGeneration == null) { sctClause = new SecurityContextKeyIdentifierClause(contextId); } else { sctClause = new SecurityContextKeyIdentifierClause(contextId, keyGeneration); } tokenResolver.TryResolveToken(sctClause, out cachedToken); if (cachedToken != null) { securityContextToken = cachedToken; dicReader.Skip(); } else { // // CookieMode // encodedCookie = dicReader.ReadElementContentAsBase64(); if (encodedCookie == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4237))); } // // appply transforms // byte[] decodedCookie = ApplyTransforms(encodedCookie, false); using (MemoryStream ms = new MemoryStream(decodedCookie)) { BinaryFormatter formatter = new BinaryFormatter(); securityContextToken = formatter.Deserialize(ms) as SecurityToken; } SessionSecurityToken sessionToken = securityContextToken as SessionSecurityToken; if (sessionToken != null && sessionToken.ContextId != contextId) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4229, sessionToken.ContextId, contextId))); } if (sessionToken != null && sessionToken.Id != id) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4227, sessionToken.Id, id))); } } } else { // // SessionMode // // Get the token from the Cache. SecurityToken cachedToken = null; SecurityContextKeyIdentifierClause sctClause = null; if (keyGeneration == null) { sctClause = new SecurityContextKeyIdentifierClause(contextId); } else { sctClause = new SecurityContextKeyIdentifierClause(contextId, keyGeneration); } tokenResolver.TryResolveToken(sctClause, out cachedToken); if (cachedToken != null) { securityContextToken = cachedToken; } } dicReader.ReadEndElement(); if (securityContextToken == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4243))); } return(securityContextToken); }
/// <summary> /// Serializes the given token to the XmlWriter. /// </summary> /// <param name="writer">XmlWriter to which the token needs to be serialized</param> /// <param name="token">The SecurityToken to be serialized.</param> /// <exception cref="ArgumentNullException">The input argument 'writer' is null.</exception> /// <exception cref="InvalidOperationException">The input argument 'token' is either null or not of type /// SessionSecurityToken.</exception> public override void WriteToken(XmlWriter writer, SecurityToken token) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); } SessionSecurityToken sessionToken = token as SessionSecurityToken; if (sessionToken == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4046, token, TokenType))); } string ns, elementName, contextIdElementName, instance; if (sessionToken.SecureConversationVersion == WSSecureConversationFeb2005Constants.NamespaceUri) { ns = WSSecureConversationFeb2005Constants.Namespace; elementName = WSSecureConversationFeb2005Constants.ElementNames.Name; contextIdElementName = WSSecureConversationFeb2005Constants.ElementNames.Identifier; instance = WSSecureConversationFeb2005Constants.ElementNames.Instance; } else if (sessionToken.SecureConversationVersion == WSSecureConversation13Constants.NamespaceUri) { ns = WSSecureConversation13Constants.Namespace; elementName = WSSecureConversation13Constants.ElementNames.Name; contextIdElementName = WSSecureConversation13Constants.ElementNames.Identifier; instance = WSSecureConversation13Constants.ElementNames.Instance; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4050))); } XmlDictionaryWriter dicWriter; SessionDictionary dictionary = SessionDictionary.Instance; if (writer is XmlDictionaryWriter) { dicWriter = (XmlDictionaryWriter)writer; } else { dicWriter = XmlDictionaryWriter.CreateDictionaryWriter(writer); } dicWriter.WriteStartElement(elementName, ns); if (sessionToken.Id != null) { dicWriter.WriteAttributeString(WSUtilityConstants.Attributes.IdAttribute, WSUtilityConstants.NamespaceURI, sessionToken.Id); } dicWriter.WriteElementString(contextIdElementName, ns, sessionToken.ContextId.ToString()); if (sessionToken.KeyGeneration != null) { dicWriter.WriteStartElement(instance, ns); dicWriter.WriteValue(sessionToken.KeyGeneration); dicWriter.WriteEndElement(); } if (!sessionToken.IsReferenceMode) { dicWriter.WriteStartElement(CookieElementName, CookieNamespace); byte[] cookie; using (MemoryStream ms = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, token); cookie = ms.ToArray(); } cookie = ApplyTransforms(cookie, true); dicWriter.WriteBase64(cookie, 0, cookie.Length); dicWriter.WriteEndElement(); } dicWriter.WriteEndElement(); dicWriter.Flush(); }
public abstract void AddOrUpdate(SessionSecurityTokenCacheKey key, SessionSecurityToken value, DateTime expiryTime);
public void SetSessionToken(string userName, string authenticationMethod, bool isPersistent, int ttl, IEnumerable<Claim> additionalClaims = null) { var principal = CreatePrincipal(userName, authenticationMethod, additionalClaims); var sessionToken = new SessionSecurityToken(principal, TimeSpan.FromHours(ttl)) { IsPersistent = isPersistent }; FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionToken); }
/// <summary> /// Applies the principal found in the command result by a call to the /// session auth module. /// </summary> public void ApplyPrincipal() { // Ignore this if we're not running inside IIS, e.g. in unit tests. if(Principal != null && HttpContext.Current != null) { var sessionToken = new SessionSecurityToken(Principal); FederatedAuthentication.SessionAuthenticationModule .AuthenticateSessionSecurityToken(sessionToken, true); } }
static public SecurityContextSecurityToken ConvertSessionTokenToSecurityContextSecurityToken(SessionSecurityToken token) { if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); } List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(); if (token.SctAuthorizationPolicy != null) { policies.Add(token.SctAuthorizationPolicy); } if (token.ClaimsPrincipal != null && token.ClaimsPrincipal.Identities != null) { policies.Add(new AuthorizationPolicy(token.ClaimsPrincipal.Identities)); } byte[] key = null; SymmetricSecurityKey symmetricKey = token.SecurityKeys[0] as SymmetricSecurityKey; if (symmetricKey != null) { key = symmetricKey.GetSymmetricKey(); } SecurityContextSecurityToken sct = new SecurityContextSecurityToken( token.ContextId, token.Id, key, token.ValidFrom, token.ValidTo, token.KeyGeneration, token.KeyEffectiveTime, token.KeyExpirationTime, policies.AsReadOnly()); return sct; }
protected virtual void ValidateSession(SessionSecurityToken securityToken) { throw new NotImplementedException(); }