Reputation: 9580
I've just watched the Introduction to Identity and Access Control in .NET 4.5 video on Pluralsight. I am trying to convert an old webforms app (not MVC and not OWIN) from this...
Dim authTicket As New FormsAuthenticationTicket(1, "Bob", DateTime.UtcNow.ToLocalTime(), DateTime.UtcNow.ToLocalTime.AddMinutes(60), False, "Master")
Dim authCookie As New HttpCookie("MyApp", FormsAuthentication.Encrypt(authTicket))
...to a ClaimsIdentity
and claims-based approach. Although ClaimsIdentity
and its Claims are covered in the video, there is little mention of how to plug it all together and persist a user across pages (the stuff that's been done automatically before now).
For example, is this a valid alternative to the above for setting up the user's claims?
Dim fd As New FormsIdentity(New FormsAuthenticationTicket("MyApp", True, 60))
fd.AddClaims(New List(Of Claim) From {
New Claim(ClaimTypes.Name, "Bob"),
New Claim(ClaimTypes.Role, "Master")
})
Dim p As New ClaimsPrincipal(fd)
If so, how is ClaimsPrincipal
then stored/persisted/retrieved on subsequent pages?
Currently I'm not using OWIN, but can introduce it if it will benefit this scenario.
Upvotes: 3
Views: 4442
Reputation: 1759
AFAIK A ClaimsPrincipal
is always converted to some kind of SecurityToken when "serialized". If it is sent by an STS this is a SAML or JWT security token. If is is remembered during a session then it is a SessionSecurityToken
. Each of these tokens has a corresponding SecurityTokenHandler
class.
In classical ASP.NET/MVC, You have two http modules : WSFederationAuthenticationModule
and SessionAuthenticationModule
. The latter makes sure the ClaimsPrincipal
is stored across a session. By default, WIF uses a SessionSecurityTokenHandler
and stores the ClaimsPrincipal
in a bunch of cookies.
So your question becomes easier once you know that the road to serializaing a ClaimsPrincipal
goes over a SecurityToken
. You first convert it to a SecurityToken
and then use a handler to "convert it to a string".
For you it boils down to instantiating the correct SecurityTokenHandler
derivate. To deserialize it, you just call ValidateToken
(which is a great method name to deserialize a token). This gives you a list of claims, which can easily be converted in a ClaimsIdentity
and a ClaimsPrincipal
.
To serialize it, you might have to pass over a SecurityTokenDescriptor
(where you put your claims in) to convert your ClaimsPrincipal
into a SecurityToken
, then the SecurityTokenHandler
can convert this into a "string".
Upvotes: 2