validating web site credentials - c#

I have a website: "https://blahblah.com"
To authenticate to it, I do this (which works fine):
NetworkCredential credentials = new NetworkCredential();
credentials.UserName = AppVars.Username;
credentials.Password = AppVars.Password;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = credentials;
//.....
But how do I go about just validating the username and password if I want to add a login functionality?
UPDATED CODE:
private void btnLogIn_Click(object sender, EventArgs e)
{
Properties.Settings.Default.Username = txtUserName.Text;
Properties.Settings.Default.Password = txtPassword.Text;
using (PrincipalContext pc = new PrincipalContext( ContextType.Domain, AppVars.ixLibraryConnectionTestURL))
{
try
{
bool isValid = false;
isValid = pc.ValidateCredentials(AppVars.Username, AppVars.Password);
if (isValid == true)
{
//just testing
MessageBox.Show("is valid");
}
else
{
//just testing
MessageBox.Show("is not valid");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
the domain name looks something like this: https://xxxxxx-services.zzz999.org/pqg_4/lib/api/sdo/rest/v1

Use: System.DirectoryServices.AccountManagement namespace
// create a "principal context" - e.g. your domain (could be machine, too)
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
{
// validate the credentials
bool isValid = pc.ValidateCredentials("myuser", "mypassword");
}
You can read more about it here:
http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.aspx

Related

about forms authentication and redirect

Every time I try to Response.Redirect("tothepageIwant.aspx"); tt takes me to ~/Account/Logon.aspx
Why is this happening? I'm using Forms Authentication, with a custom method of authenticating, using PrincipalContext.ValidateCredentials.
If the credentials are valid, I want to Redirect.Response to the page I'm allowing the user to reach.
Instead, anytime I successfully login, it redirects me to the old Account/Logon.aspx.
Any suggestions? Anything I need to look out for when using Forms Authentication with custom method of authenticating?
EDIT (add code):
protected void Submit1_Click(object sender, EventArgs e)
{
var auth = new AuthClass();
var result = auth.ValidateCredentials(UserEmail.Text, UserPass.Text);
if (result)
{
Response.Redirect("~/Members/RollReport.aspx");
}
else
{
Msg.Text = "Not authorized to access this page.";
}
}
public bool ValidateCredentials(string user, string pass)
{
using (var pc = new PrincipalContext(ContextType.Domain, "Domain.name"))
{
// validate the credentials
try
{
var isValid = pc.ValidateCredentials(user, pass);
if (isValid)
{
var isAuth = AuthorizeUser(user);
return isAuth;
}
else
{
return false;
}
}
catch (ActiveDirectoryOperationException)
{
throw;
}
}
}
private bool AuthorizeUser(string user)
{
var isAuth = false;
var authList = (List<string>)HttpContext.Current.Cache["AuthList"];
foreach (var id in authList)
{
if (id == user)
{
isAuth = true;
}
}
return isAuth;
}
var userName = Request.ServerVariables["LOGON_USER"];//or some other method of capturing the value from the username
var pc = new PrincipalContext(ContextType.Domain);
var userFind = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName);
if(userFind != null)
{
HttpContext.Current.Session["username"] = userFind.DisplayName;
}
If you want to check and redirect.. store the value inside a session variable inside the Global.asax
protected void Session_Start(object sender, EventArgs e)
{
//declare and Initialize your LogIn Session variable
HttpContext.Current.Session["username"] = string.Empty;
}
On the Page_Load of your login page assign the value if the code above succeeds
if(HttpContext.Current.Session["username"] == null)
{
//Force them to redirect to the login page
}
else
{
Response.Redirect("tothepageIwant.aspx");
}
if you want to do the same thing inside a using(){} statement
string fullName = null;
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
using (UserPrincipal user = UserPrincipal.FindByIdentity(context,"yourusernamehere")) //User.Identity.Name
{
if (user != null)
{
fullName = user.DisplayName;
}
}
}
use the debugger and inspect all of the user. Properties ok

How do I save the username value to a cookie so I can retrieve it if the user wants to be remembered?

I am trying to implement a "Remember Me" for the username in a login page using cookies.
I am trying to do this by using Values.Add on the cookie object:
ck.Values.Add("username", txtUName.Value);
However, when I add a value in this way, authentication breaks. (If I remove the line authentication works again.)
How can I keep the username stored in the cookie without breaking it?
The full code for this bit is:
bool IsRemember = chkPersistCookie.Checked;
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUName.Value, DateTime.Now, DateTime.Now.AddMinutes(30), IsRemember, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie("MYCOOKIEAPP", cookiestr);
if (IsRemember)
{
ck.Expires = tkt.Expiration;
ck.Values.Add("username", txtUName.Value);
}
else
{
ck.Values.Add("username", txtUName.Value);
ck.Expires = DateTime.Now.AddMinutes(5);
}
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
I managed to get what I needed direct from the FormsAuthenticationTicket:
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value);
txtUName.Value = ticket.Name;
}
Try use this example from here and read what they write. I test it in my test project and it works.
protected void Page_Load(object sender, EventArgs e)
{
if(Request.Cookies["BackgroundColor"] != null)
{
ColorSelector.SelectedValue = Request.Cookies["BackgroundColor"].Value;
BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
}
}
protected void ColorSelector_IndexChanged(object sender, EventArgs e)
{
BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
HttpCookie cookie = new HttpCookie("BackgroundColor");
cookie.Value = ColorSelector.SelectedValue;
cookie.Expires = DateTime.Now.AddHours(1);
Response.SetCookie(cookie);
}

Login with gmail account through c# .net

i am using DotNetOpenID dll for logging my sample application through gmail authentication through c# .net
code which i used was
protected void Page_Load(object sender, EventArgs e)
{
OpenIdRelyingParty rp = new OpenIdRelyingParty();
var r = rp.GetResponse();
if (r != null)
{
switch (r.Status)
{
case AuthenticationStatus.Authenticated:
NotLoggedIn.Visible = false;
Session["GoogleIdentifier"] = r.ClaimedIdentifier.ToString();
Response.Redirect("About.aspx"); //redirect to main page of your website
break;
case AuthenticationStatus.Canceled:
lblAlertMsg.Text = "Cancelled.";
break;
case AuthenticationStatus.Failed:
lblAlertMsg.Text = "Login Failed.";
break;
}
}
}
protected void OpenLogin_Click(object src, CommandEventArgs e)
{
string discoveryUri = e.CommandArgument.ToString();
OpenIdRelyingParty openid = new OpenIdRelyingParty();
var b = new UriBuilder(Request.Url) { Query = "" };
var req = openid.CreateRequest(discoveryUri, b.Uri, b.Uri);
req.RedirectToProvider();
}
it works well when i click the gmail login button it goes to the gmail page and authenticate as i need.
but my problem is AuthenticationStatus.Authenticated status was failed after authentication always even though i am giving correct username and password of gmail account
Waiting for valuable response and comments
As par your requirement.You should try this code or see this link :
Gmail credentials for Authentication of ASP.net Website
protected void Page_Load(object sender, EventArgs e)
{
OpenIdAjaxRelyingParty rp = new OpenIdAjaxRelyingParty();
var response = rp.GetResponse();
if (response != null)
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
NotLoggedIn.Visible = false;
Session["GoogleIdentifier"] = response.ClaimedIdentifier.ToString();
var fetchResponse = response.GetExtension<FetchResponse>();
Session["FetchResponse"] = fetchResponse;
var response2 = Session["FetchResponse"] as FetchResponse;
string UserName = response2.GetAttributeValue(WellKnownAttributes.Name.First) ?? "Guest"; // with the OpenID Claimed Identifier as their username.
string UserEmail = response2.GetAttributeValue(WellKnownAttributes.Contact.Email) ?? "Guest";
Response.Redirect("Default2.aspx");
break;
case AuthenticationStatus.Canceled:
lblAlertMsg.Text = "Cancelled.";
break;
}
}
}
protected void OpenLogin_Click(object sender, CommandEventArgs e)
{
string discoveryUri = e.CommandArgument.ToString();
OpenIdRelyingParty openid = new OpenIdRelyingParty();
var url = new UriBuilder(Request.Url) { Query = "" };
var request = openid.CreateRequest(discoveryUri); // This is where you would add any OpenID extensions you wanted
var fetchRequest = new FetchRequest(); // to fetch additional data fields from the OpenID Provider
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.First);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.HomeAddress.Country);
request.AddExtension(fetchRequest);
request.RedirectToProvider();
}
I'm not familiar with DotNetOpenID dll. However, I would recommend using Fiddler to do a capture of the data in the POST that is being sent during login and ensure that you are sending the correct content in your post. C# provides HttpWebRequest class and HttpWebResponse class in System.Net. Is there any reason you aren't using the these from the System.dll instead?
Make sure that when you get your cookies back from your POST that you put them in your cookie collection for any subsequent request.
There is a nice sample class to handle requests in this post answered by cement

C# UserPrincipal Object reference not set to an instance of an object

I am receiving the classic, Object reference not set to an instance of an object in my project when viewing the hosted website. Works when building a debug version locally.
Live
Example of code that is showing error message:
using System.DirectoryServices.AccountManagement;
protected void Page_Load(object sender, EventArgs e)
{
try
{
String username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
username = username.Substring(3);
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "dc");
UserPrincipal user = UserPrincipal.FindByIdentity(pc, username);
string NTDisplayName = user.DisplayName;
//String NTUser = user.SamAccountName;
lblntuser.Text = NTDisplayName;
}
catch (Exception Ex)
{
lblntuser.Text = Ex.Message;
System.Diagnostics.Debug.Write(Ex.Message);
}
}
Try this:
protected void Page_Load(object sender, EventArgs e)
{
try
{
// you need to also take into account that someone could get to your
// page without having a Windows account.... check for NULL !
if (System.Security.Principal.WindowsIdentity == null ||
System.Security.Principal.WindowsIdentity.GetCurrent() == null)
{
return; // possibly return a message or something....
}
String username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
// if the user name returned is null or empty -> abort
if(string.IsNullOrEmpty(username))
{
return;
}
username = username.Substring(3);
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "dc");
UserPrincipal user = UserPrincipal.FindByIdentity(pc, username);
// finding the user of course can also fail - check for NULL !!
if (user != null)
{
string NTDisplayName = user.DisplayName;
//String NTUser = user.SamAccountName;
lblntuser.Text = NTDisplayName;
}
}
catch (Exception Ex)
{
lblntuser.Text = Ex.Message;
System.Diagnostics.Debug.Write(Ex.Message);
}
}

claimsResponse Always Return Null

hello i have a following code in asp.net. i have used DotNetOpenAuth.dll for openID. the code is under
protected void openidValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
// This catches common typos that result in an invalid OpenID Identifier.
args.IsValid = Identifier.IsValid(args.Value);
}
protected void loginButton_Click(object sender, EventArgs e)
{
if (!this.Page.IsValid)
{
return; // don't login if custom validation failed.
}
try
{
using (OpenIdRelyingParty openid = this.createRelyingParty())
{
IAuthenticationRequest request = openid.CreateRequest(this.openIdBox.Text);
// This is where you would add any OpenID extensions you wanted
// to include in the authentication request.
ClaimsRequest objClmRequest = new ClaimsRequest();
objClmRequest.Email = DemandLevel.Request;
objClmRequest.Country = DemandLevel.Request;
request.AddExtension(objClmRequest);
// Send your visitor to their Provider for authentication.
request.RedirectToProvider();
}
}
catch (ProtocolException ex)
{
this.openidValidator.Text = ex.Message;
this.openidValidator.IsValid = false;
}
}
protected void Page_Load(object sender, EventArgs e)
{
this.openIdBox.Focus();
if (Request.QueryString["clearAssociations"] == "1")
{
Application.Remove("DotNetOpenAuth.OpenId.RelyingParty.OpenIdRelyingParty.ApplicationStore");
UriBuilder builder = new UriBuilder(Request.Url);
builder.Query = null;
Response.Redirect(builder.Uri.AbsoluteUri);
}
OpenIdRelyingParty openid = this.createRelyingParty();
var response = openid.GetResponse();
if (response != null)
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
// This is where you would look for any OpenID extension responses included
// in the authentication assertion.
var claimsResponse = response.GetExtension<ClaimsResponse>();
State.ProfileFields = claimsResponse;
// Store off the "friendly" username to display -- NOT for username lookup
State.FriendlyLoginName = response.FriendlyIdentifierForDisplay;
// Use FormsAuthentication to tell ASP.NET that the user is now logged in,
// with the OpenID Claimed Identifier as their username.
FormsAuthentication.RedirectFromLoginPage(response.ClaimedIdentifier, false);
break;
case AuthenticationStatus.Canceled:
this.loginCanceledLabel.Visible = true;
break;
case AuthenticationStatus.Failed:
this.loginFailedLabel.Visible = true;
break;
// We don't need to handle SetupRequired because we're not setting
// IAuthenticationRequest.Mode to immediate mode.
////case AuthenticationStatus.SetupRequired:
//// break;
}
}
}
private OpenIdRelyingParty createRelyingParty()
{
OpenIdRelyingParty openid = new OpenIdRelyingParty();
int minsha, maxsha, minversion;
if (int.TryParse(Request.QueryString["minsha"], out minsha))
{
openid.SecuritySettings.MinimumHashBitLength = minsha;
}
if (int.TryParse(Request.QueryString["maxsha"], out maxsha))
{
openid.SecuritySettings.MaximumHashBitLength = maxsha;
}
if (int.TryParse(Request.QueryString["minversion"], out minversion))
{
switch (minversion)
{
case 1: openid.SecuritySettings.MinimumRequiredOpenIdVersion = ProtocolVersion.V10; break;
case 2: openid.SecuritySettings.MinimumRequiredOpenIdVersion = ProtocolVersion.V20; break;
default: throw new ArgumentOutOfRangeException("minversion");
}
}
return openid;
}
for above code i am always getting
var claimsResponse = response.GetExtension<ClaimsResponse>();
i am always getting claimsResponse= null. what is the reason why it happen. is there any requirement which is required for openid like domain validation for RelyingParty?? please give me answer as soon as possible.
This is a repost of: https://stackoverflow.com/questions/1311726/claimsresponse-always-return-null. More details are provided in this post, but still...

Categories

Resources