1

FormsAuthentication has an encrypt and decrypt method to push and pull the Authentication Ticket. Roles has a lot of the same methods, but it does not tell you what type of encryption is being used, or how to decrypt it. Can anyone point me in the right direction? I need to be able to mock up a Role Cookie for a test.

EDIT 1:

Here is an example of the problem that I'm still having.

SetLoggedInUserInHttpContext(User, Roles.GetRolesForUser(User.UserID.ToString()));

RQUserMembership member = new RQUserMembership();
QUserMembership mem = member.GetByUserAndPass(User.Username, User.Password);

FormsAuthentication.SetAuthCookie(mem.UserId.ToString(), true);
QGlobals.expireLoginProxyID();
RQLoginAttempt.LogSuccessfulAttempt(User.Username);

Here is the setting of the user

        public static bool SetLoggedInUserInHttpContext(QUser User, string[] roles = null) {
        if (HttpContext.Current != null) {
            if (roles == null) {
                roles = Roles.GetRolesForUser(User.UserID.ToString());
            } 

            GenericIdentity genericIdentity = new GenericIdentity(User.UserID.ToString());
            RolePrincipal genericUser = new RolePrincipal(genericIdentity); //rolesToSet
            HttpContext.Current.User = genericUser;
            return (User.UserID == QGlobals.GetLoggedInUserID());
        } else {
            return false;
        }
    }

My attempt to get the byte[]:

        HttpContext blah = HttpContext.Current;
        string blah2 = HttpContext.Current.Request.Cookies[".ASPXROLES"].Value;
        byte[] bytes = new byte[blah2.Length * sizeof(char)];
        System.Buffer.BlockCopy(blah2.ToCharArray(), 0, bytes, 0, bytes.Length);
        byte[] blah3 = MachineKey.Unprotect(bytes);
        var str = System.Text.Encoding.Default.GetString(blah3);

I'm now getting an error on blah3 = MachineKey.Unprotect(bytes);

Error occurred during a cryptographic operation.

   at System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.HomogenizeErrors(Func`2 func, Byte[] input)
   at System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.Unprotect(Byte[] protectedData)
   at System.Web.Security.MachineKey.Unprotect(ICryptoServiceProvider cryptoServiceProvider, Byte[] protectedData, String[] purposes)
   at System.Web.Security.MachineKey.Unprotect(Byte[] protectedData, String[] purposes)
   at Quorra.Repositories.RQUser.GetUserHomePageStats(Int32 UserID, Int32 HourInterval) in e:\Code\quorra\Quorra.Domain\Repositories\RQUser.cs:line 133
   at Quorra.Admin.Controllers.HomeController.Home(Nullable`1 refreshBasketCount) in e:\Code\quorra\Quorra.Admin\Controllers\HomeController.cs:line 31
   at lambda_method(Closure , ControllerBase , Object[] )
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass48.<InvokeActionMethodFilterAsynchronouslyRecursive>b__41()

Any direction would be appreciated.

Edit 2:

To clarify I need to be able to set up a role cookie for a user so that Roles.IsUserInRole(); works. Right now if I pass the userId it works, because it goes to the role provider and runs that method, but to check the logged on user, it just tests the cookie. I don't actually need to be able to decrypt it, if I can encrypt it, that will be enough.

tereško
  • 58,060
  • 25
  • 98
  • 150
Recursor
  • 542
  • 5
  • 18
  • Can you clarify what you mean by "mock up a role cookie for a test?" The MachineKey.Unprotect API intentionally cannot be used to decrypt .ASPXAUTH or .ASPXROLES cookies. – Levi Sep 09 '14 at 05:18
  • I added some clarification, let me know if you need anything else. – Recursor Sep 09 '14 at 13:29

1 Answers1

2

The encryption used for Forms Authentication is based on the <machineKey> element under <system.web>. Effectively you reconfigure the <machineKey> element to control the encryption.

See here for further information.

Martin Costello
  • 9,672
  • 5
  • 60
  • 72
  • I'm still getting an error. It's has to do with Roles, I know that's related to Forms Authentication, but I'm not sure how closely. Thank you for your help. – Recursor Sep 08 '14 at 20:43
  • If you added the `` element as suggested but tried to decrypt a value encrypted before you added it then you won't be able to decrypt the previous value due to the key mismatch. This scenario would also cause the 'Error occurred during a cryptographic operation.' message. – Martin Costello Sep 08 '14 at 21:37
  • All of the keys match, and each time I'm trying a new one, and it won't work. – Recursor Sep 09 '14 at 13:28