public void OnAuthorization(AuthorizationFilterContext context) { var user = context.HttpContext.User; if (user.Identity.IsAuthenticated == false) { String action = context.RouteData.Values["action"].ToString(); String controller = context.RouteData.Values["controller"].ToString(); ITempDataProvider provider = (ITempDataProvider)context.HttpContext.RequestServices.GetService(typeof(ITempDataProvider)); var TempData = provider.LoadTempData(context.HttpContext); TempData["action"] = action; TempData["controller"] = controller; provider.SaveTempData(context.HttpContext, TempData); context.Result = this.GetRedirectToRoute("Identity", "Login"); } else { if (user.IsInRole("Directora") == false) { context.Result = this.GetRedirectToRoute("Identity", "AccesoDenegado"); } } }
public HomeController(ITempDataProvider cookie, IAntiforgery antiForgery, IHttpContextAccessor httpContextAccessor, IServiceProvider serviceProvider, IClusterClient grainClient, ILoggerFactory loggerFactory) : base() { // this.cookie = cookie; this.antiForgery = antiForgery; this.serviceProvider = serviceProvider; this.grainClient = grainClient; this.loggerFactory = loggerFactory; // Create session id in an client-unreadable cookie IDictionary <string, object> cookieData; try { cookieData = cookie.LoadTempData(httpContextAccessor.HttpContext); } catch (CryptographicException) { // Server key changed? cookieData = new Dictionary <string, object>(); } if (cookieData.TryGetValue("session", out object id) && (id is Guid)) { this.sessionId = (Guid)id; } else { // generate a new session id cookieData["session"] = this.sessionId = Guid.NewGuid(); cookie.SaveTempData(httpContextAccessor.HttpContext, cookieData); } }
public void OnAuthorization(AuthorizationFilterContext context) { var user = context.HttpContext.User; string controller = context.RouteData.Values["controller"].ToString(); string action = context.RouteData.Values["action"].ToString(); if (user == null) { ITempDataProvider provider = (ITempDataProvider)context.HttpContext.RequestServices.GetService(typeof(ITempDataProvider)); var TempData = provider.LoadTempData(context.HttpContext); TempData["CONTROLLER"] = controller; TempData["ACTION"] = action; provider.SaveTempData(context.HttpContext, TempData); context.Result = GetRoute("Login", "Manage"); } else { int contador = 0; foreach (var role in rolesPermitidos) { if (role == user.FindFirst(ClaimTypes.Role).Value) { contador++; } ; } if (contador == 0) { context.Result = GetRoute("SinPermisos", "Manage"); } } }
public void OnAuthorization(AuthorizationFilterContext context) { var user = context.HttpContext.User; if (!user.Identity.IsAuthenticated) { ITempDataProvider provider = context.HttpContext.RequestServices.GetService(typeof(ITempDataProvider)) as ITempDataProvider; var TempData = provider.LoadTempData(context.HttpContext); String action = context.RouteData.Values["action"].ToString(); String controller = context.RouteData.Values["controller"].ToString(); if (action == "Perfil") { TempData["action"] = "TodosProductos"; TempData["controller"] = "Productos"; } else { TempData["action"] = action; TempData["controller"] = controller; } provider.SaveTempData(context.HttpContext, TempData); context.Result = this.GetRoute("Login", "Identity"); } }
/// <summary> /// 加载数据 /// </summary> /// <param name="controllerContext"></param> /// <param name="tempDataProvider"></param> public void Load(ControllerContext controllerContext, ITempDataProvider tempDataProvider) { IDictionary <string, object> dictionary = tempDataProvider.LoadTempData(controllerContext); this._data = ((dictionary != null) ? new Dictionary <string, object>(dictionary, StringComparer.OrdinalIgnoreCase) : new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase)); this._initialKeys = new HashSet <string>(this._data.Keys, StringComparer.OrdinalIgnoreCase); this._retainedKeys.Clear(); }
public void Load(ControllerContext controllerContext, ITempDataProvider tempDataProvider) { IDictionary <string, object> providerDictionary = tempDataProvider.LoadTempData(controllerContext); _data = (providerDictionary != null) ? new Dictionary <string, object>(providerDictionary, StringComparer.OrdinalIgnoreCase) : new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase); _initialKeys = new HashSet <string>(_data.Keys); _modifiedKeys.Clear(); }
internal void AddErrors(ModelStateDictionary modelState) { IDictionary <string, object> tempData = dataProvider.LoadTempData(accessor.HttpContext); if (tempData.ContainsKey(Constants.tempDataErrorDictionaryName)) { List <ValidationError> errors = JsonConvert.DeserializeObject <List <ValidationError> >(tempData[Constants.tempDataErrorDictionaryName].ToString()); errors.ForEach(error => { modelState.AddModelError(error.PropertyName, error.Message); }); } }
public ActionsController(ITempDataProvider cookie, IHttpContextAccessor httpContextAccessor) : base() { var data = cookie.LoadTempData(httpContextAccessor.HttpContext); if (data.TryGetValue("session", out object id) && (id is Guid)) { this.sessionId = (Guid)id; } else { // generate a new session id data["session"] = this.sessionId = Guid.NewGuid(); cookie.SaveTempData(httpContextAccessor.HttpContext, data); } }
public void OnAuthorization(AuthorizationFilterContext context) { var user = context.HttpContext.User; if (!user.Identity.IsAuthenticated) { ITempDataProvider provider = context.HttpContext.RequestServices.GetService(typeof(ITempDataProvider)) as ITempDataProvider; var TempData = provider.LoadTempData(context.HttpContext); String action = context.RouteData.Values["action"].ToString(); string controller = context.RouteData.Values["controller"].ToString(); TempData["action"] = action; TempData["controller"] = controller; provider.SaveTempData(context.HttpContext, TempData); context.Result = this.GetRedirectToRoute("Usuario", "Login"); } }
public ActionsController(IClusterClient grainClient, ITempDataProvider cookie, IHttpContextAccessor httpContextAccessor, IHostingEnvironment env) : base() { this.grainClient = grainClient; this.env = env; var data = cookie.LoadTempData(httpContextAccessor.HttpContext); if (data.TryGetValue("session", out object id) && (id is Guid)) { this.sessionId = (Guid)id; } else { // generate a new session id data["session"] = this.sessionId = Guid.NewGuid(); cookie.SaveTempData(httpContextAccessor.HttpContext, data); } }
public ActionsHub(IClusterClient grainClient, ITempDataProvider cookie, IHttpContextAccessor httpContextAccessor, ILogger <ActionsHub> logger) { this.grainClient = grainClient; this.logger = logger; var data = cookie.LoadTempData(httpContextAccessor.HttpContext); if (data.TryGetValue("session", out object id) && (id is Guid)) { this.sessionId = (Guid)id; } else { // generate a new session id data["session"] = this.sessionId = Guid.NewGuid(); cookie.SaveTempData(httpContextAccessor.HttpContext, data); } }
public void OnAuthorization(AuthorizationFilterContext context) { var user = context.HttpContext.User; if (!user.Identity.IsAuthenticated) { String action = context.RouteData.Values["action"].ToString(); String controller = context.RouteData.Values["controller"].ToString(); ITempDataProvider provider = (ITempDataProvider)context.HttpContext.RequestServices.GetService(typeof(ITempDataProvider)); var TempData = provider.LoadTempData(context.HttpContext); TempData["action"] = action; TempData["controller"] = controller; provider.SaveTempData(context.HttpContext, TempData); RouteValueDictionary route = new RouteValueDictionary(new { controller = "Calculator", action = "Unauthorize" }); context.Result = new RedirectToRouteResult(route); } }
public static void GuardarAcctionController(AuthorizationFilterContext context) { //RECUPERAR LA DIRECCION A DONDE QUEREMOS IR String action = context.RouteData.Values["action"].ToString(); String controller = context.RouteData.Values["controller"].ToString(); //RECUPERAR TEMPDATA PROVIDER ITempDataProvider provider = (ITempDataProvider) context.HttpContext.RequestServices.GetService(typeof(ITempDataProvider)); //RECUPERAR EL TEMPDATA var TempData = provider.LoadTempData(context.HttpContext); //GUARDAMOS LOS DATOS ACTION Y CONTROLLER TempData["action"] = action; TempData["controller"] = controller; //GUARDAR TEMPDATA PARA PODER LLEGAR AL CONTROLLER provider.SaveTempData(context.HttpContext, TempData); }
public void OnAuthorization(AuthorizationFilterContext context) { var user = context.HttpContext.User; if (user.Identity.IsAuthenticated == false) { //DEBEMOS RECUPERAR LA INFORMACION DE DONDE HA //PULSADO EL USUARIO String action = context.RouteData.Values["action"].ToString(); String controller = context.RouteData.Values["controller"].ToString(); //NECESITAMOS RECUPERAR EL PROVEEDOR DE TEMPDATA //AL NO SER UNA CLASE CONTROLLER, NO ES NATIVO //PARA ENCONTRARLO, DEBEMOS RECUPERAR LA CLASE QUE HEMOS //PUESTO EN LAS DEPENDENCIAS DE LA APP (STARTUP) //RESOLVER DEPENDENCIAS DE UN SERVICIO DEL CONTENEDOR IoC ITempDataProvider provider = (ITempDataProvider) context.HttpContext.RequestServices .GetService(typeof(ITempDataProvider)); //RECUPERAMOS EL TEMPDATA DEL PROVIDER var TempData = provider.LoadTempData(context.HttpContext); //GUARDAMOS LOS DATOS TempData["action"] = action; TempData["controller"] = controller; //DEBEMOS SALVAR TEMPDATA PARA QUE LLEGUE AL CONTROLLER provider.SaveTempData(context.HttpContext, TempData); //LOGIN context.Result = this.GetRedirectToRoute("Identity", "Login"); } else { //SOLO QUEREMOS QUE EL PRESI ENTRE if (user.IsInRole("PRESIDENTE") == false && user.IsInRole("ANALISTA") == false && user.IsInRole("DIRECTOR") == false) { context.Result = this.GetRedirectToRoute("Identity", "AccesoDenegado"); } } }
public HomeController(ITempDataProvider cookie, IAntiforgery antiForgery, IHttpContextAccessor httpContextAccessor, IServiceProvider serviceProvider, ILoggerFactory loggerFactory) : base() { // this.cookie = cookie; this.antiForgery = antiForgery; this.serviceProvider = serviceProvider; this.loggerFactory = loggerFactory; // Create session id in an client-unreadable cookie var data = cookie.LoadTempData(httpContextAccessor.HttpContext); if (data.TryGetValue("session", out object id) && (id is Guid)) { this.sessionId = (Guid)id; } else { // generate a new session id data["session"] = this.sessionId = Guid.NewGuid(); cookie.SaveTempData(httpContextAccessor.HttpContext, data); } }
public IActionResult RegisterCallback([FromBody] CredentialsModel model) { // 1. Let JSONtext be the result of running UTF-8 decode on the value of response.clientDataJSON var jsonText = Encoding.UTF8.GetString(Base64Url.Decode(model.Response.ClientDataJson)); // 2. Let C, the client data claimed as collected during the credential creation, be the result of running an implementation-specific JSON parser on JSONtext var c = JsonConvert.DeserializeObject <ClientData>(jsonText); // 3. Verify that the value of C.type is webauthn.create if (c.Type != "webauthn.create") { throw new Exception("Incorrect client data type"); } // 4. Verify that the value of C.challenge matches the challenge that was sent to the authenticator in the create() call. var data = tempData.LoadTempData(HttpContext); var challenge = (string)data["challenge"]; if (!Base64Url.Decode(c.Challenge).SequenceEqual(Convert.FromBase64String(challenge))) { throw new Exception("Incorrect challenge"); } // 5. Verify that the value of C.origin matches the Relying Party's origin. if (c.Origin != "http://localhost:5000") { throw new Exception("Incorrect origin"); } // 6. Verify that the value of C.tokenBinding.status matches the state of Token Binding for the TLS connection over which the assertion was obtained. // If Token Binding was used on that TLS connection, also verify that C.tokenBinding.id matches the base64url encoding of the Token Binding ID for the connection. // TODO: Token binding (once out of draft) // 7. Compute the hash of response.clientDataJSON using SHA-256. var hasher = new SHA256Managed(); var hashedClientDataJson = hasher.ComputeHash(Base64Url.Decode(model.Response.ClientDataJson)); // Why??? // 8. Perform CBOR decoding on the attestationObject field of the AuthenticatorAttestationResponse structure // to obtain the attestation statement format fmt, the authenticator data authData, and the attestation statement attStmt. CBORObject cbor; using (var stream = new MemoryStream(Base64Url.Decode(model.Response.AttestationObject))) cbor = CBORObject.Read(stream); var authData = cbor["authData"].GetByteString(); var fmt = cbor["fmt"].AsString(); var span = authData.AsSpan(); var rpIdHash = span.Slice(0, 32); span = span.Slice(32); var flags = new BitArray(span.Slice(0, 1).ToArray()); span = span.Slice(1); var userPresent = flags[0]; // (UP) // Bit 1 reserved for future use (RFU1) var userVerified = flags[2]; // (UV) // Bits 3-5 reserved for future use (RFU2) var attestedCredentialData = flags[6]; // (AT) "Indicates whether the authenticator added attested credential data" var extensionDataIncluded = flags[7]; // (ED) // Signature counter (4 bytes, big-endian unint32) var counterBuf = span.Slice(0, 4); span = span.Slice(4); var counter = BitConverter.ToUInt32(counterBuf); // https://www.w3.org/TR/webauthn/#signature-counter // Attested Credential Data // cred data - AAGUID (16 bytes) var aaguid = span.Slice(0, 16); span = span.Slice(16); // cred data - L (2 bytes, big-endian uint16) var credIdLenBuf = span.Slice(0, 2); span = span.Slice(2); credIdLenBuf.Reverse(); var credentialIdLength = BitConverter.ToUInt16(credIdLenBuf); // cred data - Credential ID (L bytes) var credentialId = span.Slice(0, credentialIdLength); span = span.Slice(credentialIdLength); // 9. Verify that the RP ID hash in authData is indeed the SHA-256 hash of the RP ID expected by the RP. var computedRpIdHash = hasher.ComputeHash(Encoding.UTF8.GetBytes(RelyingPartyId)); if (!rpIdHash.SequenceEqual(computedRpIdHash)) { throw new Exception("Incorrect RP ID"); } // 10. If user verification is required for this registration, verify that the User Verified bit of the flags in authData is set. // TODO: Handle user verificaton required // 11. If user verification is not required for this registration, verify that the User Present bit of the flags in authData is set. if (userPresent == false) { throw new Exception("User not present"); } // 12. Verify that the values of the client extension outputs in clientExtensionResults // TODO: Handle extension results // 13. Determine the attestation statement format by performing a USASCII case-sensitive match on fmt against the set of supported WebAuthn Attestation Statement Format Identifier values // TODO: Handle accepted fmt values // 14. Verify that attStmt is a correct attestation statement, conveying a valid attestation signature, by using the attestation statement format fmt’s verification procedure given attStmt, authData and the hash of the serialized client data computed in step 7. // TODO: Handle fmt specific attestation statement // 15. If validation is successful, obtain a list of acceptable trust anchors (attestation root certificates or ECDAA-Issuer public keys) for that attestation type and attestation statement format fmt, from a trusted source or from policy. // For example, the FIDO Metadata Service [FIDOMetadataService] provides one way to obtain such information, using the aaguid in the attestedCredentialData in authData. // 16. Assess the attestation trustworthiness using the outputs of the verification procedure in step 14 // TODO: Use of FIDO metadata service // 17. Check that the credentialId is not yet registered to any other user & var parsedCredentialId = Convert.ToBase64String(credentialId.ToArray()); if (Users.Any(x => x.CredentialId == parsedCredentialId)) { throw new Exception("Duplicate credential ID"); } // 18. If the attestation statement attStmt verified successfully and is found to be trustworthy, then register the new credential var coseStruct = CBORObject.DecodeFromBytes(span.ToArray()); var key = JsonConvert.DeserializeObject <CredentialPublicKey>(coseStruct.ToJSONString()); Users.Add(new User { Username = (string)data["username"], CredentialId = parsedCredentialId, PublicKey = key }); return(Ok()); }
public Task Invoke(HttpContext context) { var cookieData = _cookieProvider.LoadTempData(context); bool hasWaitRoomId = cookieData.ContainsKey("_waitroom"); object proxyUserId; bool hasUserId = cookieData.TryGetValue("_proxyUserId", out proxyUserId); // Any connection with a session ID is allowed if (cookieData.ContainsKey("_proxySession")) { if (hasUserId) { _telemetry.Context.User.Id = cookieData["_proxyUserId"].ToString(); } return(_next(context)); } // Get or create a user ID for tracking context if (!hasUserId) { string trackingCookieSessionId = context.Request.Cookies[_trackingCookie]; proxyUserId = String.IsNullOrEmpty(trackingCookieSessionId) ? Guid.NewGuid().ToString() : trackingCookieSessionId; cookieData.Add("_proxyUserId", proxyUserId); } _telemetry.Context.User.Id = proxyUserId.ToString(); _telemetry.Context.Session.Id = proxyUserId.ToString(); if (!_tracker.TryAcquireSession()) { // This is a new user connecting during an active session block if (_waitRoomEnabled) { if (!hasWaitRoomId) { string waitRoomId = Guid.NewGuid().ToString(); cookieData.Add("_waitroom", waitRoomId); _cookieProvider.SaveTempData(context, cookieData); // _logger.LogWarning("User {id} in wait room", proxyUserId); _telemetry.Context.Operation.ParentId = waitRoomId; _telemetry.TrackEvent("waitroom start", new Dictionary <string, string> { { "waitroom_id", waitRoomId } }); } else { // TODO: Check for context.Session.GetInt("_retries"); Increment this and then do something different in the response - could do some templating here // Track page refresh in telemetry string waitRoomId = cookieData["_waitroom"].ToString(); _telemetry.Context.Operation.ParentId = waitRoomId; } context.Response.ContentLength = _html.Length; context.Response.ContentType = "text/html"; context.Response.StatusCode = _htmlResponseCode; return(context.Response.Body.WriteAsync(_html).AsTask()); } else { _logger.LogWarning("User {id} exceeded quota (waitroom disabled)", proxyUserId); return(_next(context)); } } // Clear waitroom data from the proxy cookie if (hasWaitRoomId) { string waitRoomId = cookieData["_waitroom"].ToString(); _telemetry.Context.Operation.ParentId = waitRoomId; _telemetry.TrackEvent("waitroom end", new Dictionary <string, string> { { "waitroom_id", waitRoomId } }); cookieData.Remove("_waitroom"); _cookieProvider.SaveTempData(context, cookieData); } cookieData.Add("_proxySession", "true"); _cookieProvider.SaveTempData(context, cookieData); return(_next(context)); }
public AppStateService(IHttpContextAccessor httpContextAccessor, ITempDataProvider tempDataProvider, UserManager <EntsogUser> userManager, CompanyRepository companyRepository) { _httpContextAccessor = httpContextAccessor; _tempDataProvider = tempDataProvider; _data = _tempDataProvider.LoadTempData(_httpContextAccessor.HttpContext); }