Issue with login on Sitecore - asp.net

I am facing an issue when trying to log in on Sitecore (back office) I am redirected on the same login page even if credentials are correct.
While debugging, I could find that when on the login process, the user is redirected to http://hostname/sitecore/shell/Applications/Login/Users/Users.aspx?su=%2Fsitecore%2Fshell%2Fdefault.aspx%3Fsc_lang%3Den
But once it is there the below issue occurs:
Sitecore.Context.User.IsAuthenticated is set to false
Sitecore.Context.User is set to Sitecore/anonymous
However, the user have been registered and ticket have been created successfully. I could verify that by debugging and checking the cookies.

After more investigation, I found out that the issue was solved by adding below line on the global.asax.cs
public void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args)
{
string frameworkVersion = this.GetFrameworkVersion();
if (!string.IsNullOrEmpty(frameworkVersion) && frameworkVersion.StartsWith("v4.", StringComparison.InvariantCultureIgnoreCase))
{
args.User = SC.Context.User;
}
}
It set the user to the correct user instead of sitecore\anonymous.

Related

Can't get user information after login successfully in WSO2 Identity server

After login successfully into WSO IS with service URL (https://localhost:9443/services/")
I tried to get User Information as below :
try {
UserRealm realm = WSRealmBuilder.createWSRealm(serviceURL, authCookie, configCtx);
UserStoreManager storeManager = realm.getUserStoreManager();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But I had exception relating to this as below image. I can't get any info.
I tried and found out that the main error is I can't create ConfixContext with the following code :
configCtx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
I also read about ConfigContext in the below link and tried with other methods in this link but I can't create configContext.
http://axis.apache.org/axis2/java/core/apidocs/org/apache/axis2/context/ConfigurationContextFactory.html
I appreciate your help in this case.
Thanks
The problem is your runtime doesnt have org.wso2.carbon.user.api.UserStoreException class. Therefore you can't identify the real exception.
For now, just use Exception e instead, and see if you can log the real exception.

WIF, ADFS 2.0, wsignoutcleanup1.0 and wreply

I have set up a WIF web application, a custom STS and an ADFS 2.0 instance as the go between. I am having a hard time understanding the sign out process for my application. Currently, when my user clicks the sign out button, I am calling this code:
WSFederationAuthenticationModule.FederatedSignOut(null, new Uri("https://myrelyingpartyapp.com/?wa=wsignoutcleanup1.0"));
If I use this code, it works fine. All of the cookies and sessions are disposed of correctly. The only problem is that the browser just displays a little green check after the process is over. Obviously, I want to be redirected back to the login page of the STS. To accomplish this I attempted the following code:
WSFederationAuthenticationModule.FederatedSignOut(null, new Uri("https://myrelyingpartyapp.com/?wa=wsignoutcleanup1.0&wreply=" + HttpUtility.UrlEncode("https://myrelyingpartyapp.com/Default.aspx")));
My belief was that the wreply would cause the user to be redirected back to my relying party app where they would be unauthorized and therefore be redirected back to the STS login page. Instead this causes an error in ADFS (which I cannot see because of their helpful error page.) No matter what url I use for wreply, the error is thrown. Am I using wsignoutcleanup1.0 correctly? Just for reference, here is the code in my STS where I handle sign in/sign out requests:
if (action == "wsignin1.0")
{
SignInRequestMessage signInRequestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(Request.Url);
if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
{
SecurityTokenService securityTokenService = new CustomSecurityTokenService(CustomSecurityTokenServiceConfiguration.Current);
SignInResponseMessage signInResponseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(signInRequestMessage, User as ClaimsPrincipal, securityTokenService);
FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(signInResponseMessage, Response);
}
else
{
throw new UnauthorizedAccessException();
}
}
else if (action == "wsignout1.0")
{
SignOutRequestMessage signOutRequestMessage = (SignOutRequestMessage)WSFederationMessage.CreateFromUri(Request.Url);
FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequest(signOutRequestMessage, User as ClaimsPrincipal, signOutRequestMessage.Reply, Response);
}
All I needed for correct behavior was correct logout code. This code eventually logged my user out and did a proper cleanup:
var module = FederatedAuthentication.WSFederationAuthenticationModule;
module.SignOut(false);
var request = new SignOutRequestMessage(new Uri(module.Issuer), module.Realm);
Response.Redirect(request.WriteQueryString());
This code was put in the event handler of my logout button on my relying party app.

Getting Forms Authentication from an ASP.NET logon page used by Silverlight 4 application

This is supposed to just work. I've read all the articles I could find via google on the topic, tried to copy as much as I could from other articles on both StackOverflow and CodeProject and others, but regardless of what I try - it doesn't work.
I have a silverlight application that runs fine using Windows Authentication.
To get it running under Forms Authentication I've:
Edited the web.config file to enable Forms Authentication (and delete the Windows Authentication configuration):
<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="logon.aspx" defaultUrl="index.aspx" protection="All" path="/" timeout="30" />
</authentication>
Created a standard logon.aspx and logon.aspx.cs code behind page to take a user input name and password, and create a authentication cookie when the logon was successful, and then redirected the user to the root page of the web site, which is a silverlight application:
private void cmdLogin_ServerClick( object sender, System.EventArgs e )
{
if ( ValidateUser( txtUserName.Value, txtUserPass.Value ) )
{
FormsAuthentication.SetAuthCookie(txtUserName.Value, true);
var cookie = FormsAuthentication.GetAuthCookie(txtUserName.Value, true);
cookie.Domain = "mymachine.mydomain.com";
this.Response.AppendCookie(cookie);
string strRedirect;
strRedirect = Request["ReturnUrl"];
if ( strRedirect == null )
strRedirect = "index.aspx";
Response.Redirect( strRedirect, true );
}
}
So the redirect after successfully logging in launches my silverlight application.
However the user is not authenticated when executing the Silverlight startup code:
public App()
{
InitializeComponent();
var webContext = new WebContext();
webContext.Authentication = new FormsAuthentication();
ApplicationLifetimeObjects.Add( webContext );
}
private void ApplicationStartup( object sender, StartupEventArgs e )
{
Resources.Add( "WebContext", WebContext.Current );
// This will automatically authenticate a user when using windows authentication
// or when the user chose "Keep me signed in" on a previous login attempt
WebContext.Current.Authentication.LoadUser(ApplicationUserLoaded, null);
// Show some UI to the user while LoadUser is in progress
InitializeRootVisual();
}
The error occurs in the ApplicationUserLoaded method, which always has its HasError property set to true on entry to the method.
private void ApplicationUserLoaded( LoadUserOperation operation )
{
if((operation != null) && operation.HasError)
{
operation.MarkErrorAsHandled();
HandlerShowWebServiceCallBackError(operation.Error, "Error loading user context.");
return;
}
...
}
The error reported is as follows - from what it appears to me is that the user isn't considered authenticated on entry to the silverlight app, so it is directing the code to try to return the logon page, which is returning data unexpected by the silverlight app:
An exception occurred while attempting to contact the web service.
Please try again, and if the error persists, contact your administrator.
Error details:
Error loading user context.
Exception details:
Load operation failed for query 'GetUser'. The remote server returned an error: NotFound.
Any ideas?
Based on everything I read, this is supposed to be pretty simple and just work - so I'm obviously making a very basic error.
I'm wondering if after I authenticate the user on my logon.aspx web page, I need to somehow pass an authenticated WebContext instance over from the logon page to my silverlight application instead of creating a new instance in the silverlight app startup code - but have no idea how to do that.
Appreciate any or all suggestions.
I suspect the Response.Redirect("...", true);
According to this article you should pass false to keep the session.

Adding customized content on login page

Most of my ASP.NET website is accessible to an anonymous web users. However there are a few pages that I require authentication before I allow access. I control this via the web.config:
<authorization>
<allow users="*"/>
</authorization>
Currently my logon.aspx file is generic, but I would really like to include instructions telling the user why he was redirected to the logon page. Something like:
Before you can volunteer for a task, please logon so the system can identify you.
OR
You've attempted to edit an event. The system only allows Administrators to do this. Please logon so we can verify you are an administrator of this event.
The instructions on the logon page would depend on what the user was attempting prior to the forms authentication redirect.
My problem is how can the logon page determine what action was taken? Is there anyway to pass a custom querystring to the logon page? I guess I could decode the ReturnUrl and use that to try an determine what instructions to display. However that approach just feels....dirty. I don't like the logon page having a dependency on the URL names of other pages in the system.
Any suggestions?
You could use the HttpRequest.UrlReferrer Property to find out what was the user intention.
Or you could set a QueryString / Session variable before redirecting and use it to display some message.
Why dont you use custom exceptions to do this.
public class ClassName: Exception
{
protected ClassName() : base() {}
public ClassName(String message) : base(message) { }
}
Then you do
public class First: ClassName
{
public First() : base("message") {}
}
public class Second: ClassName
{
public Second() : base("message") { }
}
Now you just catch exceptions of type ClassName and get the message value and pass it into an asp label or textbox or however you wish to do it
You can also capture the redirect in global.asax's Application.EndRequest
void Application_EndRequest(object sender, EventArgs e)
{
if (!HttpContext.Current.Request.IsAuthenticated && HttpContext.Current.Response.StatusCode == 302 && HttpContext.Current.Response.RedirectLocation != null && HttpContext.Current.Response.RedirectLocation.ToLower().Contains("login.aspx"))
{
// do some switching or determining here, or have items preset in your HttpContext.Current.Items[]
HttpContext.Current.Response.RedirectLocation += "&Action=blah";
}
}

ASP.NET Windows Authentication logout

How do you logout when using Windows authentication in ASP.NET like this web.config?
<authentication mode="Windows" />
I've already tried the following unsuccessfully. It redirects, but does not log out the user.
void logoutButton_Click(object sender, EventArgs e) {
HttpContext.Current.Session.Clear();
HttpContext.Current.Session.Abandon();
ViewState.Clear();
FormsAuthentication.SignOut();
Response.Redirect("/");
}
Background Info:
I have to use Windows authentication because I need to impersonate the identity using Active Directory to gain access to local files. And I cannot impersonate using Forms authentication because the HttpContext.Current.User.Identity won't be a WindowsIdentity.
Impersonate using Forms Authentication
No server-side logout button will work when using "Windows" authentication. You must use "Forms" authentication if you want a logout button, or close the user's browser.
For IE browsers only, you can use the following javascript to logout the user if using Windows Authentication. (Note: closing the browser isn't required, but recommended since the user might be using a non-IE browser).
If the user clicks "No" to close the browser, then the user will be prompted for a username/password if they attempt to access a page on the site that requires authentication.
try {
document.execCommand("ClearAuthenticationCache");
}
catch (e) { }
window.close();
This code was taken from SharePoint's Signout.aspx page.
Windows authentication works at the IIS level by passing your Windows authentication token. Since authentication occurs at the IIS level you cannot actually log out from application code. However, there seems to be an answer to your problem here. It is the second question addressed and essentially involves using Forms Authentication and the LogonUser Windows api.
I had a SharePoint application with Windows authentication, I needed automatic logout after 15 minutes. I mixed up some codes and here is the result. it works in IE properly.
<script type="text/javascript">
var t;
window.onload = resetTimer;
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
function logout() {
try {
document.execCommand("ClearAuthenticationCache");
window.location.href = window.location.protocol.replace(/\:/g, '') + "://" + window.location.host + "/_layouts/customlogin14.aspx";
}
catch (e) { }
}
function resetTimer() {
window.clearTimeout(t);
t = window.setTimeout(logout, 900000);
}
put these codes in your master page, after 15 mins idle time you will see the login page.
hope this help somebody
I have this working using JavaScript in both IE and Firefox, though it logs you out of everything you're logged into in IE. It sort of works in Safari, but Safari throws up a phishing warning. Doesn't work in Opera.
try {
if (document.all) {
document.execCommand("ClearAuthenticationCache");
window.location = "/";
} else {
window.location = "http://logout:logout#example.com";
}
} catch (e) {
alert("It was not possible to clear your credentials from browser cache. Please, close your browser window to ensure that you are completely logout of system.");
self.close();
}
The best answers I have seen are found in related StackOverFlow questions:
Is there a browser equivalent to IE's ClearAuthenticationCache?
and
Logging a user out when using HTTP Basic authentication
Basically you need to send a AJAX request to the server with invalid credentials and have the server accept them.
Had alot of trouble with this, below is the code that works, hopefully someone finds it useful.
foreach (var cookie in Request.Cookies.Keys)
{
Response.Cookies.Delete(cookie);
}
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
Response.Cookies.Append("EdgeAccessCookie", "", new Microsoft.AspNetCore.Http.CookieOptions()
{
Path = "/",
HttpOnly = true,
SameSite = SameSiteMode.Lax, Expires = DateTime.Now.AddDays(-1)
});
Response.Redirect("https://adfs.[sitename].com/adfs/ls?wa=wsignout1.0");
I think you should use forms auth, but you can use ldap windows user account in forms like this:
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
{
// validate the credentials
bool isValid = pc.ValidateCredentials("myuser", "mypassword");
}

Resources