Programmatically convert claim to classical authentication

Introduction:

I had a requirement where i am suppose to use sharepoint 2010 site with claim base authentication.
And need to insert sharepoint user in sql DB.
DB should get user name as “Domain\UserName”

Issue:

Claim based sharepoint site provide user name with prefix of “i:0#.f|infoyen\avinash” or “i:0#.w|infoyen\avinash” etc..
Where as i only need to insert “infoyen\avinash” into DB.

Solution:

We have 2 ways to split this.
1. Use SPClaimProviderManager
2 split string based on “|” operator

I have used both into my function which make sure that we get only “Domain\UserName”
See below code:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
 
public static string GetDecodedLoginName(string SPLoginName)
{
    string currentUserName = string.Empty;
 
    try
    {
        if (!String.IsNullOrEmpty(SPLoginName))
        {
            // Decode login name using SPClaimProviderManager
            if (SPClaimProviderManager.IsEncodedClaim(SPLoginName))
            {
                SPClaimProviderManager mgr = SPClaimProviderManager.Local;
                try
                {
                    if (mgr != null)
                        currentUserName = mgr.DecodeClaim(SPLoginName).Value;
                }
                catch (Exception ex)
                {
                    // log your message here
                }
            }
            // If any problem occur while decoding using SPClaimProviderManager
            // Then try decoding with .Net string split function
            if (String.IsNullOrEmpty(currentUserName))
            {
                if (SPLoginName.Contains("|"))
                {
                    string[] splitUserName = SPLoginName.Split(new char[] { '|' }, 2);
 
                    if (splitUserName.Length > 0)
                        currentUserName = splitUserName[1];
                    else
                        currentUserName = SPLoginName;
                }
                else
                {
                    currentUserName = SPLoginName;
                }
            }
        }
    }
    catch (Exception ex)
    {
                    // log your message here
    }
 
    if(String.IsNullOrEmpty(currentUserName))
        currentUserName = SPLoginName;
 
    return currentUserName;
}

Hope it helps!
Thanks!

calendarDecember 5, 2012 · cardInfoyen · commentsNo Comments
tagTags: ,  · Posted in: SharePoint, SharePoint 2010

Leave a Reply

Spam Protection: , required

myworldmaps infoyen