SharePoint 2010 introduced Claims Based Authentication. One of the consequences of this is the fact that in order to use Forms Based Authentication (FBA) you need to configure your Web Application to use Claims instead of Classic Authentication. One of the many changes that you notice while working with claims are different login names: while in SharePoint 2007 you used something like myprovider:myuser, SharePoint 2010 makes the claims-soup of it: i:0#.f|myprovider|myuser. And while this is something you can take into account for newly created solutions, it can get confusing when upgrading SharePoint 2007 solutions to SharePoint 2010, especially if all you need is the user name. So is String.Replace the only way to get it out or is there a better way?
It turns out that retrieving the user name from its claims representation is pretty straight forward and can be done using the following code snippet:
Script:
string
userName =
null
;
SPClaimProviderManager
mgr =
SPClaimProviderManager
.Local;
if
(mgr !=
null
)
{
userName = mgr.DecodeClaim(
SPContext
.Current.Web.CurrentUser.LoginName).Value;
}
Claims back and forth
string
userName =
null
;
SPClaimProviderManager
mgr =
SPClaimProviderManager
.Local;
if
(mgr !=
null
)
{
SPClaim
claim =
new
SPClaim
(
SPClaimTypes
.UserLogonName,
"myuser"
,
"http://www.w3.org/2001/XMLSchema#string"
,
SPOriginalIssuers
.Format(
SPOriginalIssuerType
.Forms,
"myprovider"
));
userName = mgr.EncodeClaim(claim);
}
In some scenario’s you might want to do the exact opposite: you might be starting off with a login name and will need to turn it over into the claims-based name. Just like in the previous scenario this can be easily done using the SPClaimProviderManager:
First we retrieve a reference to the Claims Provider Manager configured with the current Web Application. Then, using the DecodeClaim(string) method, we convert the string into SPClaim and retrieve its value, which contains the login name of the current user.
So, assuming you were logged in with the myuser account and the value of the SPContext.Current.Web.CurrentUser.LoginName property was something similar to i:0#.f|myprovider|myuser, calling the code snippet above would return myuser.
In some scenario’s you might want to do the exact opposite: you might be starting off with a login name and will need to turn it over into the claims-based name. Just like in the previous scenario this can be easily done using the SPClaimProviderManager.
No comments:
Post a Comment