I'm trying to implement a Google OpenID login
I have the following questions:
Where can I get the value of the variable openidurl in the line
IAuthenticationRequest request = openid.CreateRequest(openidurl);
2.. How can I restrict the login for a certain Google Apps Domain only?
The code is the following:
protected void Page_Load(object sender, EventArgs e)
{
OpenIdRelyingParty openid = new OpenIdRelyingParty();
var response = openid.GetResponse();
if (response != null)
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
var fetch = response.GetExtension<FetchResponse>();
string email = string.Empty;
if (fetch != null)
{
email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
}
//FormsAuthentication.RedirectFromLoginPage(response.ClaimedIdentifier, false);
Session["email"] = email;
Response.Redirect("profile.aspx");
break;
}
}
}
protected void OpenLogin_Click(object src, CommandEventArgs e)
{
string openidurl = "https://www.google.com/accounts/o8/id?id=initial_id"; //auxiliary initial id. ??????
//The Request
using (OpenIdRelyingParty openid = new OpenIdRelyingParty())
{
IAuthenticationRequest request = openid.CreateRequest(openidurl);
var fetch = new FetchRequest();
fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
request.AddExtension(fetch);
// Send your visitor to their Provider for authentication.
request.RedirectToProvider();
}
}
}
Thanks in advance, this is the first time I use Google OpenIDs.
Related
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
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
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);
}
}
I have the following code:
protected void Page_Load(object sender, EventArgs e)
{
var openId = new OpenIdRelyingParty();
HttpContext httpContext = HttpContext.Current;
var headers = new WebHeaderCollection();
foreach (string header in httpContext.Request.Headers)
{
headers.Add(header, httpContext.Request.Headers[header]);
}
string requestUrl = string.Format("http://localhost:12345/Login/{0}",
httpContext.Request.Url.Query);
var requestInfo = new HttpRequestInfo(httpContext.Request.HttpMethod,
new Uri(requestUrl),
httpContext.Request.RawUrl, headers,
httpContext.Request.InputStream);
var response = openId.GetResponse(requestInfo);
if (response != null)
{
ClaimsResponse claimResponse = response.GetExtension<ClaimsResponse>();
lblUser.Text = claimResponse.FullName;
if (response.Exception != null)
{
lblError.Text = response.Exception.Message;
}
}
}
protected void btnTest_Click(object sender, EventArgs e)
{
try
{
using (OpenIdRelyingParty openId = new OpenIdRelyingParty())
{
string identifier = #"https://www.google.com/accounts/o8/id";
var request = openId.CreateRequest(identifier,
new Realm("http://localhost:12345/"),
new Uri("http://localhost:12345/Login/"));
request.AddExtension(new ClaimsRequest
{
Email = DemandLevel.Require
});
request.RedirectToProvider();
}
}
catch (Exception ex)
{
// TODO: log exception
throw;
}
}
When I execute the code, user is authenticated but ClaimsResponse is null.
Code works fine with MyOpenId.
Any help would be appreciated.
The information here is useful: Retrieve OpenId User Information (Claims) across providers
The gold nugget you are likely missing in your app is the AXFetchAsSregTransform.
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...