// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Security.Principal; using System.Web.Mvc; using System.Web.WebPages.Resources; namespace System.Web.Helpers.AntiXsrf { internal sealed class AntiForgeryWorker { private readonly IAntiForgeryConfig _config; private readonly IAntiForgeryTokenSerializer _serializer; private readonly ITokenStore _tokenStore; private readonly ITokenValidator _validator; internal AntiForgeryWorker(IAntiForgeryTokenSerializer serializer, IAntiForgeryConfig config, ITokenStore tokenStore, ITokenValidator validator) { _serializer = serializer; _config = config; _tokenStore = tokenStore; _validator = validator; } private void CheckSSLConfig(HttpContextBase httpContext) { if (_config.RequireSSL && !httpContext.Request.IsSecureConnection) { throw new InvalidOperationException(WebPageResources.AntiForgeryWorker_RequireSSL); } } private AntiForgeryToken DeserializeToken(string serializedToken) { return (!String.IsNullOrEmpty(serializedToken)) ? _serializer.Deserialize(serializedToken) : null; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Caller will just regenerate token in case of failure.")] private AntiForgeryToken DeserializeTokenNoThrow(string serializedToken) { try { return DeserializeToken(serializedToken); } catch { // ignore failures since we'll just generate a new token return null; } } private static IIdentity ExtractIdentity(HttpContextBase httpContext) { if (httpContext != null) { IPrincipal user = httpContext.User; if (user != null) { return user.Identity; } } return null; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Caller will just regenerate token in case of failure.")] private AntiForgeryToken GetCookieTokenNoThrow(HttpContextBase httpContext) { try { return _tokenStore.GetCookieToken(httpContext); } catch { // ignore failures since we'll just generate a new token return null; } } // [ ENTRY POINT ] // Generates an anti-XSRF token pair for the current user. The return // value is the hidden input form element that should be rendered in // the