Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get the OWIN cookie and decrypt it to get claims from it in BeginRequest?

I am implementing the new ASP.NET Identity 2.0 Framework in an existing website uses CA's Identity Minder which primarily uses Request.ServerVariables to power all the controls.

What I am trying to do is populate the Request Headers with the same variables that CA does on every request in the BeginRequest event with an HTTP Handler, but using the new Identity Provider.

I know that in the BeginRequest event I have access to read cookies from the client, and I know that I can check if the OWIN cookie is there (named .AspNet.ApplicationCookie) but I don't know how I can decrypt the cookie to get the claims out of it.

I have also tried doing this to read the claims:

Dim identity = CType(Thread.CurrentPrincipal, ClaimsPrincipal)
Dim claim = identity.Claims.SingleOrDefault(Function(c) c.Type = ClaimTypes.Name)

When I do this, however, I get nothing for the value so I am assuming that the Thread.CurrentPrincipal isn't populated this early in the request pipeline.

This code does work, however

Dim application As HttpApplication = DirectCast(sender, HttpApplication)
Dim cookie = application.Context.Request.Cookies(".AspNet.ApplicationCookie")
If cookie Is Nothing Then
    HttpContext.Current.Request.Headers.Add("SM_SERVERSESSIONID", "NOT Logged in")
Else
    HttpContext.Current.Request.Headers.Add("SM_SERVERSESSIONID", "Logged in")
End If

So considering that I DO have access to the cookie, I was wondering if there was any way that I could decrypt it so I can read the claims that I have set inside of it.

Here is how I am setting my claims on the login page:

Dim claims = New List(Of Claim)()
claims.Add(New Claim(ClaimTypes.Name, user.UserName))
claims.Add(New Claim(ClaimTypes.Email, user.Email))
Dim id = New ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie)
authenticationManager.SignIn(id)
like image 201
vipergtsrz Avatar asked Jul 30 '14 17:07

vipergtsrz


1 Answers

You don't need to decrypt the cookie by yourself. You just need to check if user is authorised and get existed claims.

Please, try something like this:

var claimsIdentity = User.Identity as ClaimsIdentity;
if (claimsIdentity != null)
{
    Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier);
    if (providerKeyClaim != null)
    {
        var name = claimsIdentity.FindFirstValue(ClaimTypes.Name);
        var email = claimsIdentity.FindFirstValue(ClaimTypes.Email);
    }
}
like image 133
Yuriy A. Avatar answered Nov 12 '22 04:11

Yuriy A.