// Notification raised after ADAL accessed the cache. // If the HasStateChanged flag is set, ADAL changed the content of the cache void AfterAccessNotification(TokenCacheNotificationArgs args) { // if state changed if (this.HasStateChanged) { if (Cache == null) { Cache = new UserTokenCache { webUserUniqueId = userId }; } Cache.cacheBits = MachineKey.Protect(this.Serialize(), "ADALCache"); Cache.LastWrite = DateTime.Now; // update the DB and the lastwrite db.Entry(Cache).State = Cache.UserTokenCacheId == 0 ? EntityState.Added : EntityState.Modified; db.SaveChanges(); this.HasStateChanged = false; } }
/// <summary> /// Extension method to convert a HttpRequestBase to a HttpRequestData. /// </summary> /// <param name="requestBase">The request object used to populate the <c>HttpRequestData</c>.</param> /// <param name="ignoreCookies">Ignore cookies when extracting data. /// This is useful for the stub idp that might see the relay state /// and the requester's cookie, but shouldn't try to decrypt it.</param> /// <returns>The <c>HttpRequestData</c> object that has been populated by the request.</returns> public static HttpRequestData ToHttpRequestData( this HttpRequestBase requestBase, bool ignoreCookies) { if (requestBase == null) { throw new ArgumentNullException(nameof(requestBase)); } var cookies = ignoreCookies ? Enumerable.Empty <KeyValuePair <string, string> >() : GetCookies(requestBase); return(new HttpRequestData( requestBase.HttpMethod, requestBase.Url, requestBase.ApplicationPath, requestBase.Form.Cast <string>().Select((de, i) => new KeyValuePair <string, string[]>(de, ((string)requestBase.Form[i]).Split(','))), cookies, v => MachineKey.Unprotect(v, ProtectionPurpose))); }
// Se genera una notificación después de que ADAL acceda a la caché. // Si se establece la marca HasStateChanged, ADAL cambia el contenido de la caché void AfterAccessNotification(TokenCacheNotificationArgs args) { // si ha cambiado el estado if (this.HasStateChanged) { if (Cache == null) { Cache = new UserTokenCache { webUserUniqueId = userId }; } Cache.cacheBits = MachineKey.Protect(this.Serialize(), "ADALCache"); Cache.LastWrite = DateTime.Now; // actualice la base de datos y la última escritura db.Entry(Cache).State = Cache.UserTokenCacheId == 0 ? EntityState.Added : EntityState.Modified; db.SaveChanges(); this.HasStateChanged = false; } }
public void HttpRequestBaseExtensions_ToHttpRequestData() { var url = new Uri("http://example.com:42/ApplicationPath/Path?RelayState=SomeState"); string appPath = "/ApplicationPath"; var request = Substitute.For <HttpRequestBase>(); request.HttpMethod.Returns("GET"); request.Url.Returns(url); request.Form.Returns(new NameValueCollection { { "Key", "Value" } }); request.ApplicationPath.Returns(appPath); var cookieValue = HttpRequestData.ConvertBinaryData( MachineKey.Protect( new StoredRequestState(null, new Uri("urn:someUri"), null, null).Serialize(), HttpRequestBaseExtensions.ProtectionPurpose)); request.Cookies.Returns(new HttpCookieCollection()); request.Cookies.Add(new HttpCookie("Kentor.SomeState", cookieValue)); var actual = request.ToHttpRequestData(); var expected = new HttpRequestData( "GET", url, appPath, new KeyValuePair <string, string[]>[] { new KeyValuePair <string, string[]>("Key", new string[] { "Value" }) }, Enumerable.Empty <KeyValuePair <string, string> >(), null, ClaimsPrincipal.Current); actual.ShouldBeEquivalentTo(expected, opt => opt.Excluding(s => s.StoredRequestState)); actual.StoredRequestState.ReturnUrl.AbsoluteUri.Should().Be("urn:someUri"); }
private void ValidatePostRequest() { if (RequestHelper.IsPostBack()) { bool isValidPostRequest; try { var cookieValue = CookieHelper.GetValue(INSTALL_CHECK_COOKIE_NAME); var value = MachineKey.Unprotect(Convert.FromBase64String(cookieValue), INSTALL_CHECK_PURPOSE); isValidPostRequest = INSTALL_CHECK_PAYLOAD.Equals(Encoding.UTF8.GetString(value), StringComparison.InvariantCulture); } catch (Exception ex) { throw new SecurityException(INSTALL_CHECK_EXCEPTION_MESSAGE, ex); } if (!isValidPostRequest) { throw new SecurityException(INSTALL_CHECK_EXCEPTION_MESSAGE); } } }
// Notification raised before ADAL accesses the cache. // This is your chance to update the in-memory copy from the DB, if the in-memory version is stale void BeforeAccessNotification(TokenCacheNotificationArgs args) { if (userToken == null) { // first time access userToken = cache.Get(userId) as UserToken; } else { // retrieve last write from the DB var cached = cache.Get(userId) as UserToken; // if the in-memory copy is older than the persistent copy if (cached == null || cached.LastWrite > userToken.LastWrite) { // read from from storage, update in-memory copy userToken = cache.Get(userId) as UserToken; } } Deserialize((userToken == null) ? null : MachineKey.Unprotect(userToken.CacheBits, "ADALCache")); }
public ActionResult ResetPassword(string t) { int userId; try { using (var ms = new MemoryStream(MachineKey.Unprotect(Convert.FromBase64String(t), "ResetPassword"))) using (var br = new BinaryReader(ms)) { var dt = DateTime.FromBinary(br.ReadInt64()); if (dt < DateTime.UtcNow) { return(Error(Texts.Validation.InvalidResetToken)); } userId = br.ReadInt32(); } } catch (Exception) { return(Error(Texts.Validation.InvalidResetToken)); } using (var connection = SqlConnections.NewFor <UserRow>()) { var user = connection.TryById <UserRow>(userId); if (user == null) { return(Error(Texts.Validation.InvalidResetToken)); } } //if (UseAdminLTELoginBox) // return View(MVC.Views.Membership.Account.ResetPassword.AccountResetPassword_AdminLTE, new ResetPasswordModel { Token = t }); //else return(View(MVC.Views.Membership.Account.ResetPassword.AccountResetPassword, new ResetPasswordModel { Token = t })); }
/// <summary> /// Apply cookies of the CommandResult to the response. /// </summary> /// <param name="commandResult">Commandresult</param> /// <param name="response">Response</param> /// <param name="emitSameSiteNone">Include a SameSite=None attribute on any cookies set</param> public static void ApplyCookies(this CommandResult commandResult, HttpResponseBase response, bool emitSameSiteNone) { if (commandResult == null) { throw new ArgumentNullException(nameof(commandResult)); } if (response == null) { throw new ArgumentNullException(nameof(response)); } if (!string.IsNullOrEmpty(commandResult.SetCookieName)) { var protectedData = HttpRequestData.ConvertBinaryData( MachineKey.Protect( commandResult.GetSerializedRequestState(), HttpRequestBaseExtensions.ProtectionPurpose)); response.SetCookie(new HttpCookie( commandResult.SetCookieName, protectedData) { HttpOnly = true, Secure = commandResult.SetCookieSecureFlag, SameSite = emitSameSiteNone ? SameSiteMode.None : (SameSiteMode)(-1) }); } if (!string.IsNullOrEmpty(commandResult.ClearCookieName)) { response.SetCookie(new HttpCookie(commandResult.ClearCookieName) { Expires = new DateTime(1970, 01, 01), Secure = commandResult.SetCookieSecureFlag }); } }
private string UnEncodePassword(string encodedPassword) { string password = encodedPassword; switch (PasswordFormat) { case MembershipPasswordFormat.Clear: break; case MembershipPasswordFormat.Encrypted: password = Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password))); break; case MembershipPasswordFormat.Hashed: password = Encoding.Unicode.GetString(MachineKey.Decode(encodedPassword, MachineKeyProtection.Validation)); break; default: throw new ProviderException("Unsupported password format."); } return(password); }
private string EncodePassword(string password) { string encodedPassword = password; switch (PasswordFormat) { case MembershipPasswordFormat.Clear: break; case MembershipPasswordFormat.Encrypted: encodedPassword = Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password))); break; case MembershipPasswordFormat.Hashed: encodedPassword = MachineKey.Encode(Encoding.Unicode.GetBytes(password), MachineKeyProtection.Validation); break; default: throw new ProviderException("Unsupported password format."); } return(encodedPassword); }
// Notification raised after ADAL accessed the cache. // If the HasStateChanged flag is set, ADAL changed the content of the cache void AfterAccessNotification(TokenCacheNotificationArgs args) { // if state changed if (this.HasStateChanged) { Cache = new UserTokenCacheItem { cacheBits = MachineKey.Protect(this.Serialize(), "ADALCache"), LastWrite = DateTime.Now }; try { var cache = Redis.Connection.GetDatabase(); var cacheItemJson = JsonConvert.SerializeObject(Cache); cache.StringSet(userId, cacheItemJson, TimeSpan.FromDays(1)); // could we use token expiry somehow? } catch (Exception ex) { Trace.WriteLine("Exception in RedisTokenCache.AfterAccessNotification: " + ex.Message); } this.HasStateChanged = false; } }
/// <summary> /// Action responsible for leaving a game /// </summary> /// <param name="id">The game id to leave</param> /// <param name="playerType">The type of player leaving</param> /// <returns>The view for game listing screen</returns> public ActionResult Index(Int32 id, Entities.Enums.GamePlayerType playerType, Boolean windowUnload = false) { Entities.User user = new Entities.User { UserId = Authentication.Security.CurrentUserId, DisplayName = Authentication.Security.CurrentUserName }; if (windowUnload) { String jobId = BackgroundJob.Schedule(() => _leaveGame.Execute(id, user.UserId, user.DisplayName, playerType), TimeSpan.FromSeconds(20)); String key = String.Format("LeaveGame_{0}_JobId", id); Session.Add(key, MachineKey.Protect(Encoding.ASCII.GetBytes(jobId), Session.SessionID)); } else { _leaveGame.Execute(id, user, playerType); } return(Redirect("/GameListing")); }
public static string ProtectData(string providerName, string providerUserId) { using (MemoryStream ms = new MemoryStream()) using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write(providerName); bw.Write(providerUserId); bw.Flush(); byte[] serializedWithPadding = new byte[ms.Length + _padding.Length]; Buffer.BlockCopy(_padding, 0, serializedWithPadding, 0, _padding.Length); Buffer.BlockCopy( ms.GetBuffer(), 0, serializedWithPadding, _padding.Length, (int)ms.Length ); #pragma warning disable 0618 // Encode is [Obsolete] in 4.5 return(MachineKey.Encode(serializedWithPadding, MachineKeyProtection.All)); #pragma warning restore 0618 } }
public static IdsContext ReadFrom(string data) { try { if (string.IsNullOrEmpty(data)) { return(new IdsContext()); } var unEncData = Encoding.UTF8.GetString(MachineKey.Unprotect(Convert.FromBase64String(data))); return(JsonConvert.DeserializeObject <IdsContext>(unEncData)); } catch (ArgumentException ex) { LogManager.GetCurrentClassLogger().Info(ex, ex.Message); return(new IdsContext()); } catch (Exception ex) { LogManager.GetCurrentClassLogger().Error(ex, ex.Message); return(new IdsContext()); } }
public static string Encrypt(string unencrypted) { if (string.IsNullOrEmpty(unencrypted)) { return(string.Empty); } try { var encryptedBytes = MachineKey.Protect(Encoder.GetBytes(unencrypted)); if (encryptedBytes != null && encryptedBytes.Length > 0) { return(HttpServerUtility.UrlTokenEncode(encryptedBytes)); } } catch (Exception) { return(string.Empty); } return(string.Empty); }
public List <FlashMessageModel> Retrieve() { // Attempt to retrieve cookie. If the cookie is non existent, return an empty message list. var context = new HttpContextWrapper(HttpContext.Current); var cookie = context.Request.Cookies[CookieName]; if (cookie == null) { return(new List <FlashMessageModel>()); } var data = cookie.Value; // Clear the cookie by setting it to expired. cookie.Value = null; cookie.Expires = DateTime.Now.AddDays(-1); context.Response.SetCookie(cookie); // Decode and deserialize the data. var serializedMessages = MachineKey.Decode(data, MachineKeyProtection.All); return(FlashMessage.Deserialize(serializedMessages)); }
public ActionResult Index(Entities.Models.Game.CreateGame model) { if (ModelState.IsValid) { model.Game.GameCreator_UserId = Authentication.Security.CurrentUserId; model.Game.GameDeckIDs.Add(1); _insertGame.Execute(model.Game); string key = string.Format("Game_{0}_Passphrase", model.Game.GameID); if (!string.IsNullOrWhiteSpace(model.Game.Passphrase)) { Session.Add(key, MachineKey.Protect(Encoding.ASCII.GetBytes(model.Game.Passphrase), Session.SessionID)); } return(Redirect(Url.RouteUrl("Game_NoAction", new { id = model.Game.GameID }))); } else { return(View("~/Views/CreateGame/CreateGame.cshtml", model)); } }
/// <summary> /// Deserializes and loads persisted state information from an <see cref="T:System.Web.HttpRequest" /> object when a <see cref="T:System.Web.UI.Page" /> object initializes its control hierarchy. /// </summary> public override void Load() { string viewState = Page.Request.Form["__CVIEWSTATE"]; byte[] bytes = Convert.FromBase64String(viewState); // decrypt viewstate if (Page.Request.Form["__CVIEWSTATEENC"] == "1") { bytes = MachineKey.Unprotect(bytes); } // uncompress viewstate if (Page.Request.Form["__CVIEWSTATESIZE"] != "0") { using (MemoryStream output = new MemoryStream()) { using (MemoryStream input = new MemoryStream()) { input.Write(bytes, 0, bytes.Length); input.Position = 0; using (GZipStream gzip = new GZipStream(input, CompressionMode.Decompress, true)) { gzip.CopyTo(output); } } bytes = output.ToArray(); } } // deserialize the data back into ViewState and ControlState. Pair pair = (Pair) new LosFormatter().Deserialize(Convert.ToBase64String(bytes)); ViewState = pair.First; ControlState = pair.Second; }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { var authHeader = context.Request.Headers.Authorization; if (authHeader != null && String.Equals(authHeader.Scheme, "Bearer", StringComparison.InvariantCultureIgnoreCase) && authHeader.Parameter != null) { try { var tokenEncrypted = Base64UrlEncoder.DecodeBytes(authHeader.Parameter); var tokenDecrypted = MachineKey.Unprotect(tokenEncrypted); var tokenString = Encoding.Unicode.GetString(tokenDecrypted); var tokenValidationParams = new TokenValidationParameters { IssuerSigningToken = new BinarySecretSecurityToken(Convert.FromBase64String(JsonWebTokenFactory.SymmetricKey)), ValidAudience = JsonWebTokenFactory.Audience, ValidIssuer = JsonWebTokenFactory.TokenIssuerName }; var handler = new JwtSecurityTokenHandler(); SecurityToken token; IPrincipal principal = handler.ValidateToken(tokenString, tokenValidationParams, out token); context.Principal = principal; } catch (SecurityTokenExpiredException) { context.ErrorResult = new ApiErrorResult(ApiErrorCode.ExpiredToken); } catch (Exception) { context.ErrorResult = new ApiErrorResult(ApiErrorCode.InvalidToken); } } return(Task.FromResult(default(object))); }
public void HttpRequestBaseExtensions_ToHttpRequestData() { var url = new Uri("http://example.com:42/ApplicationPath/Path?RelayState=SomeState"); string appPath = "/ApplicationPath"; var request = Substitute.For <HttpRequestBase>(); request.HttpMethod.Returns("GET"); request.Url.Returns(url); request.Form.Returns(new NameValueCollection { { "Key", "Value" } }); request.ApplicationPath.Returns(appPath); var cookieValue = HttpRequestData.EscapeBase64CookieValue(Convert.ToBase64String( MachineKey.Protect(Encoding.UTF8.GetBytes("CookieValue"), "Kentor.AuthServices"))); request.Cookies.Returns(new HttpCookieCollection()); request.Cookies.Add(new HttpCookie("Kentor.SomeState", cookieValue)); var subject = request.ToHttpRequestData(); var expected = new HttpRequestData( "GET", url, appPath, new KeyValuePair <string, string[]>[] { new KeyValuePair <string, string[]>("Key", new string[] { "Value" }) }, Enumerable.Empty <KeyValuePair <string, string> >(), null); subject.ShouldBeEquivalentTo(expected, opt => opt.Excluding(s => s.CookieData)); subject.CookieData.Should().Be("CookieValue"); }
/// <summary> /// Apply cookies of the CommandResult to the response. /// </summary> /// <param name="commandResult">Commandresult</param> /// <param name="response">Response</param> public static void ApplyCookies(this CommandResult commandResult, HttpResponseBase response) { if (commandResult == null) { throw new ArgumentNullException(nameof(commandResult)); } if (response == null) { throw new ArgumentNullException(nameof(response)); } if (!string.IsNullOrEmpty(commandResult.SetCookieName)) { var protectedData = HttpRequestData.EscapeBase64CookieValue( Convert.ToBase64String( MachineKey.Protect( Encoding.UTF8.GetBytes(commandResult.SetCookieData), "Kentor.AuthServices"))); response.SetCookie(new HttpCookie( commandResult.SetCookieName, protectedData) { HttpOnly = true }); } if (!string.IsNullOrEmpty(commandResult.ClearCookieName)) { response.SetCookie(new HttpCookie(commandResult.ClearCookieName) { Expires = new DateTime(1970, 01, 01) }); } }
/// <summary> /// Recovery the Master Password from File /// </summary> /// <returns></returns> public string Open() { byte[] fileData; using (FileStream file = File.OpenRead(this.GetPath())) { fileData = new byte[file.Length]; file.Read(fileData, 0, fileData.Length); } byte[] result; if (Constants.USE_MACHINE_KEY_ENCRYPTION) { result = MachineKey.Unprotect(fileData); result = CryptoHelper.DecryptWithHardCodedKey(result); } else { result = CryptoHelper.DecryptWithHardCodedKey(fileData); } return(Encoding.ASCII.GetString(result)); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Request.Cookies["UserName"] != null && Request.Cookies["Password"] != null) { UserName.Text = Encoding.UTF8.GetString(MachineKey.Unprotect(Convert.FromBase64String(Request.Cookies["UserName"].Value), "UserName")); Password.Attributes.Add("value", Encoding.UTF8.GetString(MachineKey.Unprotect(Convert.FromBase64String(Request.Cookies["Password"].Value), "Password"))); chkRememberMe.Checked = true; } Session["dt"] = null; Session["sort"] = null; Session["SortExpression"] = null; } try { //Add refresh header to refresh the page 60 seconds before session timeout Response.AddHeader("Refresh", Convert.ToString((Session.Timeout * 60) - 60)); } catch (Exception) { throw; } }
private static AntiForgeryData DecryptForm(string value, string salt) { AntiForgeryData token = new AntiForgeryData(); try { ObjectStateFormatter formatter = new ObjectStateFormatter(); byte[] decode = MachineKey.Unprotect(Encoding.UTF8.GetBytes(value), "Authentication token"); // var decode = MachineKey.Decode(value, MachineKeyProtection.All); if (decode == null) { throw new ArgumentException("Unable to decrypt."); } Triplet triplet = (Triplet)formatter.Deserialize(Encoding.UTF8.GetString(decode)); return(Decrypt(value, formatter, triplet, salt, token)); } catch (Exception) { throw new HttpAntiForgeryException(); } }
public ActionResult Login(Credential credential) { try { credential = _iFCredential.Login(credential); bool isLogin = credential.CredentialId > 0; if (isLogin) { string encryptedUsername = Convert.ToBase64String(MachineKey.Protect(Encoding.UTF8.GetBytes(credential.Username))); string encryptedId = Convert.ToBase64String(MachineKey.Protect(Encoding.UTF8.GetBytes(credential.CredentialId.ToString()))); HttpCookie credentialCookies = new HttpCookie("Credential"); credentialCookies["Username"] = encryptedUsername; credentialCookies["CredentialId"] = encryptedId; credentialCookies.Expires = DateTime.Now.AddHours(24); Response.Cookies.Add(credentialCookies); return(Redirect("~/Home")); } return(View()); } catch (Exception exception) { return(Json("Error on logging in")); } }
public static DraftUser AuthenticateRequest(HttpRequestMessage request, int?userId = null) { DraftUser toRet = null; CookieHeaderValue cookie = request.Headers.GetCookies("DraftUser").FirstOrDefault(); if (cookie == null || String.IsNullOrWhiteSpace(cookie["DraftUser"].Value)) { throw new DraftAuthenticationException("No session"); } try { String base64Encoded = DraftAuthentication.UnescapeToken(cookie["DraftUser"].Value); byte[] bytes = Convert.FromBase64String(base64Encoded); byte[] decryptedBytes = MachineKey.Unprotect(bytes); String final = Encoding.Unicode.GetString(decryptedBytes); toRet = new JavaScriptSerializer().Deserialize <DraftUser>(final); } catch (Exception ex) { throw new DraftAuthenticationException("Authentication Failed", ex); } if (toRet.Expires < DateTime.UtcNow) { throw new DraftAuthenticationException(toRet.Username, toRet.Expires, "Authentication Expired"); } if (userId.HasValue && toRet.ID != userId.Value) { throw new DraftAuthenticationException("Unauthorized User"); } return(toRet); }
public static DraftUser AuthenticateCredentials(String username, String password, HttpResponseBase response) { if (String.IsNullOrWhiteSpace(username) || String.IsNullOrWhiteSpace(password)) { throw new DraftAuthenticationException("Invalid credentials"); } DraftUser user = DraftObj.GetUser(username, password); if (user == null) { throw new DraftAuthenticationException("Invalid username or password"); } if (response != null) { String rawString = new JavaScriptSerializer().Serialize(user); byte[] rawBytes = Encoding.Unicode.GetBytes(rawString); byte[] encryptedBytes = MachineKey.Protect(rawBytes); response.Cookies["DraftUser"].Value = DraftAuthentication.EscapeToken(Convert.ToBase64String(encryptedBytes)); response.Cookies["DraftUser"].Expires = DateTime.Now.AddDays(1); } return(user); }
// Initializes the cache against a local file. // If the file is already present, it loads its content in the ADAL cache public NativeTokenCache(string filePath = @"\TokenCache.dat") { var pathBase = ConfigurationManagerHelper.GetValueOnKey("stardust.nativeTokenCachePath"); if (pathBase.ContainsCharacters()) { CacheFilePath = pathBase + filePath; } else { CacheFilePath = AppDomain.CurrentDomain.BaseDirectory + "App_Data" + filePath; } this.AfterAccess = AfterAccessNotification; this.BeforeAccess = BeforeAccessNotification; lock (FileLock) { try { this.Deserialize(File.Exists(CacheFilePath) ? MachineKey.Unprotect(File.ReadAllBytes(CacheFilePath)) : null); } catch (CryptographicException ex) { ex.Log(); if (!File.Exists(CacheFilePath)) { throw; } File.Delete(CacheFilePath); this.Deserialize(File.Exists(CacheFilePath) ? MachineKey.Unprotect(File.ReadAllBytes(CacheFilePath)) : null); } } }
private SessionStateStoreData Deserialize(HttpContext context, string serializedItems, int timeout) { try { var encryptedBytes = Convert.FromBase64String(serializedItems); var decryptedBytes = MachineKey.Unprotect(encryptedBytes, "Session Data"); SessionStateItemCollection sessionItems = new SessionStateItemCollection(); if (decryptedBytes != null) { MemoryStream ms = new MemoryStream(decryptedBytes); if (ms.Length > 0) { BinaryReader reader = new BinaryReader(ms); sessionItems = SessionStateItemCollection.Deserialize(reader); } } return(new SessionStateStoreData(sessionItems, SessionStateUtility.GetSessionStaticObjects(context), timeout)); } catch { return(null); } }
public override byte[] Encode(byte[] value) { return(MachineKey.Protect(value, Purpose)); }