2

How to secure cookies in asp.net core. Because for now i have cookies in just plain text and everyone can get the data from inspector in browser. Does some handy solution exists for it, so it can encrypt and decrypt cookie value before processing?

context.Response.Cookies.Append("name", "Tom");
3
  • @CamiloTerevinto Added Commented Jun 6, 2018 at 13:12
  • Why don't you store these informations on session? Commented Jun 6, 2018 at 13:21
  • Don't store secrets or sensitive data on the client. End of story Commented Jun 6, 2018 at 14:38

1 Answer 1

4

There are several ways to encrypt and decrypt string and simple one of them is using IDataProtector.

private IDataProtector _protector;

public AccessController(IDataProtectionProvider provider)
{
    _protector = provider.CreateProtector("MySecretKey");
}

public void ActionResult Index()
{
    var protectedName = _protector.Protect("Tom");

    HttpContext.Response.Cookies.Append("name", protectedName);
   .
   . 
   .
}

and use _protector.UnProtect(encryptedString) to decrypt string.

Sign up to request clarification or add additional context in comments.

3 Comments

Won't this will fail if you are using a server farm or if the site is moved to a different server? I.e. you won't be able to read the value of the cookie if site is relocated.
@Sha this is true. But avoidable. You just need to specify a shared key-ring: learn.microsoft.com/en-us/aspnet/core/security/…
@pimbrouwers - Yeah, I just want to avoid all that complexity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.