Sharepoint 2013 - FBA and 2FA with custom login page - authentication

I'm a complete noob in Sharepoint. I've just started learning sharepoint 2 weeks ago coz my boss assigned me to a sharepoint project. I have to implement 2FA and FBA in an existing claims based intranet web application. I though it would be a simple task to do just by researching but I haven't found a clear guide or answer for my question.
Here are a few of my tasks:
1) Add forms based authentication to the site and use custom login page.
2) Authentication
Check user's name and password with AD upon login.
If valid, have to request OTP code from the 3rd party provider for
2FA.
User is authenticated after passing both.
Configurations and custom login page were not much trouble and it didn't take long to get them done. But I'm stuck at the 2FA part.
1) How to customize the authentication process? I don't remember where did I get the below code but I really hoped that I would be able to do something with it. So, can I do something with it or I'm going the wrong path? I'd really appreciate any help and thanks a lot in advance.
protected void btnLogin_Click(object sender, EventArgs e)
{
bool status = SPClaimsUtility.AuthenticateFormsUser(
Context.Request.UrlReferrer,
txtUsername.Value.ToString(),
txtPassword.Value.ToString());
if (!status) // if auth failed
{
lblInvalid.InnerText = "Wrong Username or Password";
lblInvalid.Visible = true;
}
else //if success
{
//What do I do here to change the user back to not authenticated?
}
}

After you properly log in set federated authentication cookie domain.
HttpCookie httpCookie = current.Response.Cookies["FedAuth"];
httpCookie.Domain = "." + ConfigurationManager.AppSettings["yourdomain"];
Sign out method is more complicated, long time ago i based my solution on this post
And sign out method (sorry for variable names but i'm decompiling my old dll) based on sharepoint SignOut page and fix from the post:
public static void SignOut(SPSite site, SPWeb web, IClaimsPrincipal principal)
{
HttpContext current = HttpContext.Current;
if (current.Session != null)
{
current.Session.Clear();
}
string value = string.Empty;
if (current.Request.Browser["supportsEmptyStringInCookieValue"] == "false")
{
value = "NoCookie";
}
HttpCookie httpCookie = current.Request.Cookies["WSS_KeepSessionAuthenticated"];
bool flag = false;
for (int i = 0; i < current.Request.Cookies.Count; i++)
{
HttpCookie httpCookie2 = current.Request.Cookies.Get(i);
if (httpCookie2.Name == "FedAuth" && !flag)
{
flag = true;
httpCookie2.Domain = WebConfigurationManager.AppSettings["yourdomain"];
}
}
if (httpCookie != null)
{
httpCookie.Value = value;
current.Response.Cookies.Remove("WSS_KeepSessionAuthenticated");
current.Response.Cookies.Add(httpCookie);
}
HttpCookie httpCookie3 = current.Request.Cookies["MSOWebPartPage_AnonymousAccessCookie"];
if (httpCookie3 != null)
{
httpCookie3.Value = value;
httpCookie3.Expires = new DateTime(1970, 1, 1);
current.Response.Cookies.Remove("MSOWebPartPage_AnonymousAccessCookie");
current.Response.Cookies.Add(httpCookie3);
}
SPIisSettings iisSettingsWithFallback = site.WebApplication.GetIisSettingsWithFallback(site.Zone);
if (iisSettingsWithFallback.UseClaimsAuthentication)
{
string iPUrl = Authentication.GetIPUrl(principal);
if (iPUrl != string.Empty)
{
string str = HttpUtility.UrlEncode(SPContext.Current.Site.RootWeb.Url);
string url = iPUrl + "?wa=wsignout1.0&wreply=" + str;
FederatedAuthentication.SessionAuthenticationModule.SignOut();
if (current.Session != null)
{
current.Session.Abandon();
}
current.Response.Redirect(url);
}
else
{
FederatedAuthentication.SessionAuthenticationModule.SignOut();
int num = 0;
foreach (SPAuthenticationProvider current2 in iisSettingsWithFallback.ClaimsAuthenticationProviders)
{
num++;
}
if (num != 1 || !iisSettingsWithFallback.UseWindowsIntegratedAuthentication)
{
if (current.Session != null)
{
current.Session.Abandon();
}
SPUtility.Redirect(web.ServerRelativeUrl, 0, current);
return;
}
}
}
if (AuthenticationMode.Forms == SPSecurity.AuthenticationMode)
{
FormsAuthentication.SignOut();
if (current.Session != null)
{
current.Session.Abandon();
}
SPUtility.Redirect(web.ServerRelativeUrl, 0, current);
}
else if (AuthenticationMode.Windows != SPSecurity.AuthenticationMode)
{
throw new SPException();
}
}
private static string GetIPUrl(IClaimsPrincipal principal)
{
string result;
if (principal == null)
{
result = string.Empty;
}
else
{
string text = string.Empty;
try
{
string text2 = principal.Identity.Name.Split(new char[] {'|'})[1];
if (SPSecurityTokenServiceManager.Local.TrustedLoginProviders[text2] != null)
{
text = SPSecurityTokenServiceManager.Local.TrustedLoginProviders[text2].ProviderUri.AbsoluteUri;
}
}
catch (Exception ex)
{
// log
}
result = text;
}
return result;
}
Further reading:
Writing A Custom Forms Login Page for SharePoint 2010
Custom Single Sign-On Scenario in SharePoint 2010

Normal aspx page
<html>
<head>One Head</head>
<body>
<form runat="server">
<table>
<tr>
<td>User Name:</td>
<td>
<asp:TextBox ID="txtUserName" runat="server" /></td>
</tr>
<tr>
<td>Password:</td>
<td>
<asp:TextBox ID="txtPassword" TextMode="Password" runat="server" /></td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnButton" Text="Button" OnClick="btnButton_Click" runat="server" />
</td>
</tr>
</table>
</form>
</body>
</html>
You may have trouble in adding Microsoft.SharePoint.identityModel, here is the location I got
C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint.IdentityModel\v4.0_15.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.IdentityModel.dll
List of Includes
using System;
using Microsoft.SharePoint;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using Microsoft.SharePoint.IdentityModel;
using System.IdentityModel.Tokens;
Button click code
protected void btnButton_Click(object sender, EventArgs e)
{
string domn = "mydomain";
string membershipProviderName = "membership";
string roleProviderName = "rolemanager";
string cookieeee = string.Format("{0}\\{1}", domn, txtUserName.Text);
bool isAuthenticated = Authenticate(domn, txtUserName.Text, txtPassword.Text);
if (isAuthenticated)
{
SecurityToken token = SPSecurityContext.SecurityTokenForFormsAuthentication(new Uri(SPContext.Current.Web.Url),
membershipProviderName, roleProviderName, txtUserName.Text, txtPassword.Text,
SPFormsAuthenticationOption.PersistentSignInRequest);
SPFederationAuthenticationModule.Current.SetPrincipalAndWriteSessionToken(token);
Response.Redirect("/");
}
}
[DirectoryServicesPermission(System.Security.Permissions.SecurityAction.LinkDemand, Unrestricted = true)]
public static bool Authenticate(string domainName, string userAlias, string userPassword)
{
try
{
PrincipalContext context = new PrincipalContext(ContextType.Domain, domainName);
return context.ValidateCredentials(userAlias, userPassword, ContextOptions.Negotiate));
}
catch
{
throw;
}
}
Note: Make sure you have all FBA configurations set in web config files. This is only custom authentication this will not work if role and membership are not set properly in the central admin and web config on services and webapplication.

Related

Authorization with windows authentication in ASP.NET Core 3.1

As I understand there is a way to retrieve group where user belong.
For example Admins, Users etc.
After doing that I want to transform this into claims. I cannot find how I can retrieve a user's groups.
Currently I am using my local user and not (Domain Active Directory).
Is there any solutions for that issue?
Is it a good approach or it is better to retrieve permissions for each user from the database and then operate with them?
you need to know is that AD is working on windows host only.
read Microsoft docs before you start project
add startup configuration , create login page
services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Login";
});
.....
app.UseAuthentication();
app.UseAuthorization();
third your needs:
your AD domain : yourdomain.com
your ldap url example: LDAP://DC.yourdomain.com
some knowledge about ldap query string
application.json config:
"ldap": {
"path": "LDAP://DC.yourdomain.com",
"domain": "yourdomain.com",
"personFilter": "(SAMAccountName={username})",
"groupFilter": "(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))",
//"property": "cn,displayName,mail,givenName,sn,o,title,company,department,telephoneNumber,description,userPrincipalName",
"property": "cn,displayName,mail,givenName,sn,o,title,company,department"
//"property": "cn,member,memberof,sAMAccountName,primaryGroupToken"
}
and you can use this method to check username and password
public Dictionary<string, string> UserInfo { get; private set; }
public bool IsAuthenticated(string username, string password)
{
bool result = false;
string domainAndUsername = Configuration["ldap:domain"] + #"\" + username;
DirectoryEntry entry = new DirectoryEntry(Configuration["ldap:path"], domainAndUsername, password);
try
{
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = Configuration["ldap:personFilter"].Replace("{username}", username);
var propList = Configuration["ldap:property"].Split(',');
search.PropertiesToLoad.AddRange(propList);
SearchResult searchResult = search.FindOne();
if (null == searchResult)
{
return false;
}
foreach (var propName in propList)
{
UserInfo.Add(propName, GetProperty(searchResult.Properties, propName));
}
DirectoryEntry obUser = new DirectoryEntry(searchResult.Path);
object obGroups = obUser.Invoke("Groups");
var groupList = new List<string>();
foreach (object ob in (IEnumerable)obGroups)
{
DirectoryEntry obGpEntry = new DirectoryEntry(ob);
groupList.Add(obGpEntry.Name);
}
UserInfo.Add("group", string.Join(",", groupList));
result = true;
}
catch (Exception ex)
{
throw new SysAuthException("Invalid Authentication", ex);
}
return result;
}
when login success you can check all user info from userInfo property
sample code for login page (add claim and login state to net core pipeline):
try
{
if (Authentication.IsAuthenticated(UserData.Username, UserData.Password))
{
var claims = new List<Claim>() {
new Claim(ClaimTypes.Name, UserData.Username)
};
foreach (var item in Authentication.UserInfo)
{
claims.Add(new Claim(item.Key, item.Value));
}
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties()
{
IsPersistent = UserData.RememberLogin
});
if (!string.IsNullOrEmpty(UserData.ReturnUrl))
return LocalRedirect(UserData.ReturnUrl);
return Redirect("/");
}
}
catch (SysAuthException ex)
{
Error = ex.InnerException.Message;
}
if you need to protect your page add #attribute [Authorize] in top of your page also you can check other claim for example roles or group with this attribute
sample code show current user info
<div>
<table class="table table-bordered table-striped">
<caption>Current User Info</caption>
#foreach (var claim in User.Claims)
{
<tr><td>#claim.Type</td><td>#claim.Value</td></tr>
}
</table>
</div>

open id log in with google and spring mvc

I'm trying to developing a spring mvc project with open id and google log in.
I'm using java configuration. And the xml configuration is
<openid-login user-service-ref="openIdUserService" >
<attribute-exchange >
<openid-attribute name="email" type="http://schema.openid.net/contact/email" required="true" />
<openid-attribute name="firstName" type="http://axschema.org/namePerson/first" required="true" />
<openid-attribute name="lastName" type="http://axschema.org/namePerson/last" required="true" />
</attribute-exchange>
but couldn't figure out what is the corresponding code in java configuration.
Any suggestion and some code example for that.
I'm using spring security too.
Here is the provider:
public class OpenIdUserDetailsService implements UserDetailsService, AuthenticationUserDetailsService {
#Autowired
private CustomerRepository userRepository;
private static final List DEFAULT_AUTHORITIES = AuthorityUtils.createAuthorityList("ROLE_USER");
#Override
public UserDetails loadUserByUsername(String id) throws UsernameNotFoundException {
Customer user = userRepository.findByOpenIdIdentifier(id);
if (user == null) {
throw new UsernameNotFoundException(id);
}
OpenIdUser openIdUser = new OpenIdUser(user.getOpenIdIdentifier(), DEFAULT_AUTHORITIES);
openIdUser.setName(user.getFirstname());
return openIdUser;
}
#Override
public UserDetails loadUserDetails(OpenIDAuthenticationToken token) {
String id = token.getIdentityUrl();
Customer user = userRepository.findByOpenIdIdentifier(id);
if (user != null) {
OpenIdUser openIdUser = new OpenIdUser(user.getOpenIdIdentifier(), DEFAULT_AUTHORITIES);
openIdUser.setName(user.getFirstname());
return openIdUser;
}
String firstName = null;
String lastName = null;
String fullName = null;
List attributes = token.getAttributes();
for (OpenIDAttribute attribute : attributes) {
String name = attribute.getName();
if (name.equals("firstname")) {
firstName = attribute.getValues().get(0);
} else if (name.equals("lastname")) {
lastName = attribute.getValues().get(0);
} else if (name.equals("fullname")) {
fullName = attribute.getValues().get(0);
}
}
if (fullName == null) {
StringBuilder fullNameBldr = new StringBuilder();
if (firstName != null) {
fullNameBldr.append(firstName);
}
if (lastName != null) {
fullNameBldr.append(" ").append(lastName);
}
fullName = fullNameBldr.toString();
}
OpenIdUser openIdUser = new OpenIdUser(id, DEFAULT_AUTHORITIES);
openIdUser.setName(fullName);
openIdUser.setNewUser(true);
Customer u = new Customer();
u.setOpenIdIdentifier(openIdUser.getUsername());
u.setFirstname(openIdUser.getName());
userRepository.save(u);
return openIdUser;
}
}
Thanks for all help.
OpenIDLoginConfigurer builder will build OpenIDAuthenticationFilter and register filter in spring security filter chain.
OpenIDLoginConfigurer takes attributeExchange parameters to build OpenIDAuthenticationFilter.These are the callback parameters after authenticate with openid provider.
To authenticate with open id through spring security,requested url will be "/j_spring_openid_security_check" OpenIDAuthenticationFilter will process this request,by hitting to openid provider for authentication.Once authentication is done, openid user will be mapped with local user.
Here is simple example application that works openId login with spring security.

Credentials prompted while rendering a remote ReportViewer control in MVC4

I am creating one web app (mvc 4) to authorize customers (using membership provider) to view the reports(SSRS 2008) for which they are registered but they don't have any kind of access to our report server.
Based on the link How do I render a remote ReportViewer aspx page in MVC4?, I have implemented Elsimer's latest answer and it works well in downloading as a pdf file.
But when I try to render as html using the same code mentioned in the above link it is asking for the windows credentials to access the report server.
So I am giving a general credential which has all access to all the reports in the reportserver through the code. but it is still asking for the credentials for the report server when they try to view as html in the client side browser. Report is getting rendered but the images and graphs are not rendering without credentials.
Please advise, I have tried many things to solve this. but no luck.
My controller and credential class code as follows:
[Route("report/MonthlySummary")]
[ValidateAntiForgeryToken]
public ActionResult MonthlySummary(MonthlyReportParameters model)
{
if (ModelState.IsValid)
{
try
{
var actionType = model.ActionType;
if (actionType == "View Report")
{
return ExportMonthlyReportToHtml(model);
}
else if (actionType == "Download pdf report")
{
return ExportMonthlyReportToPdf(model);
}
}
catch (Exception ex)
{
//Logging errors
}
}
return null;
}
private ActionResult ExportMonthlyReportToHtml(MonthlyReportParameters monthlyParams)
{
ReportViewer reportViewer = BuildMonthlyReport(monthlyParams);
reportViewer.ServerReport.Refresh();
byte[] streamBytes = null;
string mimeType = "";
string encoding = "";
string filenameExtension = "";
string[] streamids = null;
Warning[] warnings = null;
//To view the report in html format
streamBytes = reportViewer.ServerReport.Render("HTML4.0", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);
var htmlReport = File(streamBytes, "text/html");
return htmlReport;
}
private static ReportViewer BuildMonthlyReport(MonthlyReportParameters model)
{
ReportViewer reportViewer = new Microsoft.Reporting.WebForms.ReportViewer();
try
{
var rptParameters = new List<ReportParameter>
{
//Building parameters
};
reportViewer.ProcessingMode = ProcessingMode.Remote;
reportViewer.ServerReport.ReportPath = "/reportFolder/reportName";
var reportServerUrl = ConfigurationManager.AppSettings["ReportServerUrl"];
if(!string.IsNullOrEmpty(reportServerUrl))
{
reportViewer.ServerReport.ReportServerUrl = new Uri(reportServerUrl);
}
reportViewer.ServerReport.ReportServerCredentials = new ReportServerCredentials();
reportViewer.ServerReport.SetParameters(rptParameters);
}
catch (Exception ex)
{
var errorMessage = ex.Message;
//TODO: handle errors;
}
return reportViewer;
}
public sealed class ReportServerCredentials : IReportServerCredentials
{
public bool GetFormsCredentials(out Cookie authCookie, out string userName, out string password, out string authority)
{
authCookie = null;
userName = null;
password = null;
authority = null;
return false;
}
public WindowsIdentity ImpersonationUser
{
get
{
return null;
}
}
public ICredentials NetworkCredentials
{
get
{
string userName = ConfigurationManager.AppSettings["ReportUserName"];
if ((string.IsNullOrEmpty(userName)))
{
throw new Exception("Missing user name from web.config file");
}
string password = ConfigurationManager.AppSettings["ReportPassword"];
if ((string.IsNullOrEmpty(password)))
{
throw new Exception("Missing password from web.config file");
}
string domain = ConfigurationManager.AppSettings["DomainName"];
if ((string.IsNullOrEmpty(domain)))
{
throw new Exception("Missing domain from web.config file");
}
return new NetworkCredential(userName, password, domain);
}
}
}
Thanks in advance,

How to programmatically set the task outcome (task response) of a Nintex Flexi Task?

Is there any way of set a Nintex Flexi task completion through Sharepoint's web services? We have tried updating the "WorkflowOutcome", "ApproverComments" and "Status" fields without success (actually the comments and status are successfully updated, however I can find no way of updating the WorkflowOutcome system field).
I can't use the Nintex Web service (ProcessTaskResponse) because it needs the task's assigned user's credentials (login, password, domain).
The Asp.net page doesn't have that information, it has only the Sharepoint Administrator credentials.
One way is to delegate the task to the admin first, and then call ProcessTaskResponse, but it isn't efficient and is prone to errors.
In my tests so far, any update (UpdateListItems) to the WorkflowOutcome field automatically set the Status field to "Completed" and the PercentComplete field to "1" (100%), ending the task (and continuing the flow), but with the wrong answer: always "Reject", no matter what I try to set it to.
Did you try this code: (try-cacth block with redirection does the trick)
\\set to actual outcome id here, for ex. from OutComePanel control
taskItem[Nintex.Workflow.Common.NWSharePointObjects.FieldDecision] = 0;
taskItem[Nintex.Workflow.Common.NWSharePointObjects.FieldComments] = " Some Comments";
taskItem.Update();
try
{
Nintex.Workflow.Utility.RedirectOrCloseDialog(HttpContext.Current, Web.Url);
}
catch
{
}
?
Here are my code to change outcome of nintex flexi task. My problem is permission. I had passed admin token to site. It's solve the problem.
var siteUrl = "...";
using (var tempSite = new SPSite(siteUrl))
{
var sysToken = tempSite.SystemAccount.UserToken;
using (var site = new SPSite(siteUrl, sysToken))
{
var web = site.OpenWeb();
...
var cancelled = "Cancelled";
task.Web.AllowUnsafeUpdates = true;
Hashtable ht = new Hashtable();
ht[SPBuiltInFieldId.TaskStatus] = SPResource.GetString(new CultureInfo((int)task.Web.Language, false), Strings.WorkflowStatusCompleted, new object[0]);
ht["Completed"] = true;
ht["PercentComplete"] = 1;
ht["Status"] = "Completed";
ht["WorkflowOutcome"] = cancelled;
ht["Decision"] = CommonHelper.GetFlexiTaskOutcomeId(task, cancelled);
ht["ApproverComments"] = "cancelled";
CommonHelper.AlterTask((task as SPListItem), ht, true, 5, 100);
task.Web.AllowUnsafeUpdates = false;
}
}
}
}
}
}
public static string GetFlexiTaskOutcomeId(Microsoft.SharePoint.Workflow.SPWorkflowTask task, string outcome)
{
if (task["MultiOutcomeTaskInfo"] == null)
{
return string.Empty;
}
string xmlOutcome = HttpUtility.HtmlDecode(task["MultiOutcomeTaskInfo"].ToString());
if (string.IsNullOrEmpty(xmlOutcome))
{
return string.Empty;
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlOutcome);
var node = doc.SelectSingleNode(string.Format("/MultiOutcomeResponseInfo/AvailableOutcomes/ConfiguredOutcome[#Name='{0}']", outcome));
return node.Attributes["Id"].Value;
}
public static bool AlterTask(SPListItem task, Hashtable htData, bool fSynchronous, int attempts, int milisecondsTimeout)
{
if ((int)task[SPBuiltInFieldId.WorkflowVersion] != 1)
{
SPList parentList = task.ParentList.ParentWeb.Lists[new Guid(task[SPBuiltInFieldId.WorkflowListId].ToString())];
SPListItem parentItem = parentList.Items.GetItemById((int)task[SPBuiltInFieldId.WorkflowItemId]);
for (int i = 0; i < attempts; i++)
{
SPWorkflow workflow = parentItem.Workflows[new Guid(task[SPBuiltInFieldId.WorkflowInstanceID].ToString())];
if (!workflow.IsLocked)
{
task[SPBuiltInFieldId.WorkflowVersion] = 1;
task.SystemUpdate();
break;
}
if (i != attempts - 1)
{
Thread.Sleep(milisecondsTimeout);
}
}
}
var result = SPWorkflowTask.AlterTask(task, htData, fSynchronous);
return result;
}

FBA dual authentication problem

What I have?
I have configured FBA in one of the web applications with out of the box login page having dropdown box to select the either windows or FBA login. Everything is working fine.
What I want?
I want to have a custom login page having text boxes for Username and Password and a login button which will be used for authenticating both Windows and FBA users. To distinguish between the two different logins, I want to handle OnAuthenticate event and check if the user name contains a '\' then assume it is Windows user otherwise, it is FBA user.
This is the code written in OnAuthenticate event handler:
protected void signinControl_Authenticate(object sender, AuthenticateEventArgs e)
{
string fullUserName = signinControl.UserName;
string username = null;
if (fullUserName.Contains("\\")) //Windows user
{
string domain = fullUserName.Substring(0, fullUserName.IndexOf("\\"));
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain))
{
username = fullUserName.Substring(fullUserName.IndexOf("\\") + 1);
e.Authenticated = pc.ValidateCredentials(username, signinControl.Password);
}
}
else //FBA user
{
e.Authenticated = Membership.ValidateUser(fullUserName, signinControl.Password);
}
}
What problem am I facing?
The code above works well for FBA Users. But, when I try to login with a windows user, even though the e.Authenticated is set true after validating, it is throwing this error: "Your login attempt was not successful. Please try again.".
e.Authenticated = pc.ValidateCredentials(username, signinControl.Password);
I believe that, setting e.Authenticated to true should redirect the user from login page to the requested page. Can someone please help me if I have to do anything else to get Windows user signed in?
Update-1:
I used SetAuthCookie() method to set Cookie explicitly, still the same result.
FormsAuthentication.SetAuthCookie(username, true);
you should use the methode below for forms user
SPClaimsUtility.AuthenticateFormsUser(
Context.Request.UrlReferrer,
UserName.Text,
Password.Text);
and the windows part is declared like this:
protected void lbInternalUsers_OnClick(object sender, EventArgs e)
{
try
{
if (null != SPContext.Current && null != SPContext.Current.Site)
{
SPIisSettings iisSettings = SPContext.Current.Site.WebApplication.IisSettings[SPUrlZone.Default];
if (null != iisSettings && iisSettings.UseWindowsClaimsAuthenticationProvider)
{
SPAuthenticationProvider provider = iisSettings.WindowsClaimsAuthenticationProvider;
Redirect(provider);
}
}
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
}
private void Redirect(SPAuthenticationProvider provider)
{
string comp = HttpContext.Current.Request.Url.GetComponents(UriComponents.Query, UriFormat.SafeUnescaped);
string url = provider.AuthenticationRedirectionUrl.ToString();
if (provider is SPWindowsAuthenticationProvider)
{
comp = EnsureUrl(comp, true);
}
SPUtility.Redirect(url, SPRedirectFlags.Default, this.Context, comp);
}
private string EnsureUrl(string url, bool urlIsQueryStringOnly)
{
if (!url.Contains("ReturnUrl="))
{
if (urlIsQueryStringOnly)
{
url = url + (string.IsNullOrEmpty(url) ? "" : "&");
}
else
{
url = url + ((url.IndexOf('?') == -1) ? "?" : "&");
}
url = url + "ReturnUrl=";
}
return url;
}
as detailed here in the reference