claimsResponse Always Return Null - c#

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...

Related

Xamarin : iOS Authentication error with Microsoft login

I am getting this error dialog even after logging in successfully using Microsoft login.
Here is the code to authenticate :
#region IMicrosoftLogin implementation
public async System.Threading.Tasks.Task<Xamarin.Auth.Account> LoginAsync()
{
window = UIApplication.SharedApplication.KeyWindow;
viewController = window.RootViewController;
var auth = new OAuth2Authenticator(
"key_here",//for non- prod
//for production
"openid email https://graph.microsoft.com/user.read",
new Uri("https://login.microsoftonline.com/common/oauth2/V2.0/authorize"),
new Uri("https://myapp_redirect_url"),// for non- prod
null
)
{
AllowCancel = true
};
auth.Completed += Microsoft_Auth_Completed;
var tcs1 = new TaskCompletionSource<AuthenticatorCompletedEventArgs>();
d1 = (o, e) =>
{
try
{
if (e.IsAuthenticated)
{
viewController.DismissViewController(true, null);
tcs1.TrySetResult(e);
}
else
{
viewController.DismissViewController(true, null);
}
}
catch (Exception)
{
tcs1.TrySetResult(new AuthenticatorCompletedEventArgs(null));
}
};
try
{
auth.Completed += d1;
if (viewController == null)
{
while (viewController.PresentedViewController != null)
viewController = viewController.PresentedViewController;
viewController.PresentViewController(auth.GetUI(), true, null);
}
else
{
viewController.PresentViewController(auth.GetUI(), true, null);
UserDialogs.Instance.HideLoading();
}
var result = await tcs1.Task;
return result.Account;
}
catch (Exception)
{
return null;
}
finally
{
auth.Completed -= d1;
}
//auth.Error += (object sender, AuthenticatorErrorEventArgs eventArgs) => {
// auth.IsEnabled = false;
//};
}
private void Microsoft_Auth_Completed(object sender, AuthenticatorCompletedEventArgs e)
{ /// Break point here is not getting triggered.
var authenticator = sender as OAuth1Authenticator;
if (authenticator != null)
{
authenticator.Completed -= Microsoft_Auth_Completed;
}
if (e.IsAuthenticated)
{
var a = e.Account;
}
else
{
}
}
Login async called on button click like this :
btnSignIn.Clicked += async (object sender, EventArgs e) =>
{
if (networkConnection != null && networkConnection.CheckNetworkConnection())
{
UserDialogs.Instance.ShowLoading("Loading", null);
var loginresult = await MicrosoftLogin.LoginAsync();
.....
MicrosoftLogin.cs
namespace projectnamescpace
{
public interface IMicrosoftLogin
{
Task<Account> LoginAsync();
}
}
Please help me.
I have already saw following link solutions and they aren't working for me.
https://forums.xamarin.com/discussion/5866/xamarin-auth-and-infinite-error-alerts
Authentication Error e.Message = OAuth Error = Permissions+error
https://forums.xamarin.com/discussion/95176/forms-oauth-error-after-authenticated-unable-to-add-window-token-android-os-binderproxy
The issue might be caused by the HostName been blocked because of Area Policy .
You could solve this by modifying the DNS (to 8.8.8.8 as an example) for your Mac as well.
Your device, Settings/Wi-Fi
Choose connected Wi-Fi pot
Press DHCP/DNS
Set to 8.8.8.8
Or you could connect phone to the VPN for your apps deployed to device to see corporate servers.

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

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

Questions on implementing Google OpenID on a certain Google Apps domain

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.

DotNetOpenAuth and Google

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.

Categories

Resources