A quick project I've been asked to knock together doesn't need crazy security, so, I've implemented a simple login screen that checks the Username & PW against the db.
User u = new User();
if (u.AuthenticateUser(txtUsername.Text, txtPassword.Text))
Session.Add("UserSeshAuthenticated", true);
Response.Redirect("Dashboard.aspx");
All the other pages share a MasterPage and in the Page_Load event:
if ((Session["UserSeshAuthenticated"] == null) || ((bool)Session["UserSeshAuthenticated"] == false))
{
fw.Write("UserSeshAuthenticated has been lost or something");
string path = HttpContext.Current.Request.Url.AbsolutePath;
Response.Redirect("Login.aspx?retpath=" + path);
}
else
{
lblLoggedInUsername.Text = Session["UserSeshAuthenticated"].ToString();
}
This all works very well on my development machine, but when I've published it to my server, by the time my MasterPage loads, it has lost the session variables.
Can anyone help ?... I'm supposed to have it live this afternoon & I didn't think I'd run into this problem !!!
Any help appreciated. Thanks a lot.
In your login code, you add "UserSeshAuthenticated" to the session, but not the User object. If the function u.AuthenticateUser() adds a copy of itself into the Session, that could be your problem. Try adding that in your result block instead. Like this:
User u = new User();
if (u.AuthenticateUser(txtUsername.Text, txtPassword.Text))
{
Session.Add("UserSeshAuthenticated", true);
Session.Add("oUser", u);
Response.Redirect("Dashboard.aspx");
}
Related
This might an odd question, but what I would like to achieve is a functionality that would allow specific users to view SharePoint pages as if they were logged in as different users.
Let's say we have a Student page and a Staff page. I am not a student, but I would like to log in as one to be able to view the Student page as a student would. Does that make sense? So, in a way, impersonation.
I have found some impersonation code, and it works fine, but it is not what I want. I was able to impersonate a user in a separate SPWeb object. But, how do I change the current user context of the active SPWeb object?
Here's what I've got:
private void ImpersonateUser()
{
string siteURL = "http://mywebsite/";
SPSite parentSite = new SPSite(siteURL);
SPUserToken systemToken = parentSite.SystemAccount.UserToken;
using (SPSite site = new SPSite(siteURL, systemToken))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
OpenUserContext(web, siteURL, #"domain\studentuser");
}
}
}
private void OpenUserContext(SPWeb web, string siteURL, string user)
{
try
{
SPUser ensure = web.EnsureUser(user);
SPSite impSite = new SPSite(siteURL, ensure.UserToken);
SPWeb impWeb = impSite.OpenWeb();
// Do something as impersonated user
label1.Text = "Currently logged in as: " + impWeb.CurrentUser.ToString() + "(" + impWeb.CurrentUser.Name + ")";
}
catch (Exception ex) { label1.Text = ex.Message + "<br>" + user; }
}
Thanks a lot.
While SharePoint does allow your code to interact with it while impersonating a user, it has no support to allow you to browse and view things as if you were another user.
You can, however, code your customizations to take in to account your desire and add the impersonation logic to them (but that's up to you to implement and SP will not help you there). Project Server does something like what you are asking but only when it comes to Project Server owned elements.
If your impersonation code is executing behind a custom .aspx page in SharePoint, you can programmatically add an xsltlistviewwebpart to the page to display one or more list views under your impersonated context.
I am using the WebBrowser control.
This works fine most of the time however wehn navigating to a new page or waiting for a new page to load can sometimes hangs.
Is there a way to catch this? i.e. if the page is failing to navigate or load after a certain amount of time then kill the process?
I am using the - webBrowser1_DocumentCompleted event to pick up ertain behaviours when the page loads/navigates as expected however not sure how to catch if a page is hanging??
Maby you should try to implement some kind of timeout logic? There are quite many samples in web about this. F.e. this one
Also you might be interested in this event of WebBrowserControl ProgressChanged
This is due to that webbrowser component is very basic model of internet explorer, and it get stuck at ajax pages. You can fix this problem explicitly to use latest version of internet explorer... Using this code...
try
{
string installkey = #"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION";
string entryLabel = "YourExe.exe";
string develop = "YourExe.vshost.exe";//This is for Visual Studio Debugging...
System.OperatingSystem osInfo = System.Environment.OSVersion;
string version = osInfo.Version.Major.ToString() + '.' + osInfo.Version.Minor.ToString();
uint editFlag = (uint)((version == "6.2") ? 0x2710 : 0x2328); // 6.2 = Windows 8 and therefore IE10
Microsoft.Win32.RegistryKey existingSubKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(installkey, false); // readonly key
if (existingSubKey.GetValue(entryLabel) == null)
{
existingSubKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(installkey, true); // writable key
existingSubKey.SetValue(entryLabel, unchecked((int)editFlag), Microsoft.Win32.RegistryValueKind.DWord);
}
if (existingSubKey.GetValue(develop) == null)
{
existingSubKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(installkey, true); // writable key
existingSubKey.SetValue(develop, unchecked((int)editFlag), Microsoft.Win32.RegistryValueKind.DWord);
}
}
catch
{
MessageBox.Show("You Don't Have Admin Previlege to Overwrite System Settings");
}
}
Right Click Both your Exe. And vshost.exe and Run as Administrator To Update Registry for this Application....
I have a problem when I try to connect an admin to my c# application.
I have created a local database to stock the main informations such as UserName, Password...
When the user enter the login interface, he enter his user name and password, then click to login like this:
<TextBox Name="UserNameBox"></TextBox>
<PasswordBox Name="PasswordBox"></PasswordBox>
<Button Content="Connection" Click="ConnectionClick"></Button>
The event click role is to check if the admin can log in, or not:
private void ConnectionClick(object sender, RoutedEventArgs e)
{
var username = UserNameBox.Text;
var password = PasswordBox.Password;
Admin admin = new Admin();
if((username == admin.UserName) && (password == admin.Password))
{
this.Close()
MainPage retourpageprincipale = new MainPage();
retourpageprincipale.Show();
}
else
{
MessageBox.Show("Bad Username/Password combo!");
}
}
I have created some fake users into my local database (Admin) and when I enter the correct login/password, I have the MessageBox. I always have the MessageBox.
Does anybody know what I am doing wrong?
I won't give You an answer, but I will show you what should be done in such cases:
Try to debug - put break point in line if((username == admin.UserName) && (password == admin.Password)) and using watch expression try to find out where is the problem
If step one is impossible - try to log everything to file, but remember after find a bug delete this logging because you will log admin password :)
Above steps should give you the answer
As always: Im quite the noob, as you will prob see from the question.
I am playing around with Azure Wams in Xamarin.Android, and it seems to be a great tool. It logs in a user in Xamarin.Android greatly. My problem comes when i want the user to be able to log out and then log in with another account (im using Google for authentication). I used to be able to use it with a log out button, like this:
When logging in the AuthenticationToken is saved in a String for later use. So when the user confirms he wants to log out, i just UserAuth = String.Empty and then i call ConnectToMobileService() again:
public async Task ConnectToMobileService ()
{
try
{
CurrentPlatform.Init ();
client = new MobileServiceClient(
Constants.ApplicationURL,
Constants.ApplicationKey, progressHandler);
if (string.IsNullOrEmpty(UserAuth)) {
await Authenticate();
UserId = user.UserId;
await CreateTables();
await CheckUserId ();
}
else if (!string.IsNullOrEmpty(UserAuth)) {
client.CurrentUser = new MobileServiceUser(UserId);
client.CurrentUser.MobileServiceAuthenticationToken = (UserAuth);
await CreateTables();
}
}
catch (Exception e)
{
CreateAndShowDialog(e, "Error");
}
}
This used to re-launch the authentication-window for me, and the user logged in with hes new account - while the info is saved in preferences for use in other activities and so on. Well, after updating Xamarin and upgrading my license to Indie, this is no longer the case. Now it launces Authenticate for a short second, and then it goes straight back and acts as if the user logged in the exaxt way he did before.
I realize this i probably because there is some sharedpreference saved somewhere for the Wams. Ive studied the methods for clearing these i Java, but i have not been able to recreate them in C#.
client.Logout () does not seem to clear them alone. This is how i tried to recreatet the rest of it:
private void ClearPreferences(){
var prefs = this.GetSharedPreferences("UserDate", 0);
var editor = prefs.Edit ();
editor.Clear ();
editor.Commit ();
}
This does nothing. So, can anyone help me along? How do i reset it, so the users are able to log in with another account - or for example let a friend log in on their phone? Thanks in advance!
OK, so it turns out the info is stored as cookies by the auth provider. You have to both log out and clear the cookies. And it then works like a charm. This is how to clear cookies:
client.Logout ();
ClearCookies ();
await ConnectToMobileService ();
}
public static void ClearCookies () {
Android.Webkit.CookieSyncManager.CreateInstance (Android.App.Application.Context);
Android.Webkit.CookieManager.Instance.RemoveAllCookie ();
}
I have the following C# code in my code behind for a regular Web Application:
protected void Page_Load(object sender, EventArgs e)
{
if (!validTime())
{
btnEdit.Enabled = false;
btnSubmit.Enabled = false; btnSubmit2.Enabled = false;
lblSuccess.Text = "It is not currently the time to edit picks for this week.";
lblSuccess.ForeColor = System.Drawing.Color.Red;
if (picksMade())
{
displayCurrentPicks();
}
}
else
{
if (picksMade())
{
btnEdit.Enabled = true;
btnSubmit.Enabled = false;
btnSubmit2.Enabled = false;
displayCurrentPicks();
lblSuccess.Text = "Viewing your current picks";
lblSuccess.ForeColor = System.Drawing.Color.Green;
if (Session["Success"] != null && Session["Success"].ToString() != String.Empty)
{
lblSuccess.Text = Session["Success"].ToString();
lblSuccess.ForeColor = System.Drawing.Color.Green;
Session.Remove("Success");
}
}
else
{
btnEdit.Enabled = false;
btnSubmit.Enabled = true; btnSubmit2.Enabled = true;
displayCreatePicks();
lblSuccess.Text = "Create your picks for this week";
lblSuccess.ForeColor = System.Drawing.Color.Green;
}
}
}
The problem is, this code works great when I test it using ASP.NET Development Server. When I publish it to my live server it has some different behavior.
I have a web method that inserts data into my database with this signature:
[WebMethod]
public static void savePicks(List<string> Points, List<string> Teams, List<string> TieBreaker)
Again, on the test server it runs and works great. The problem is, when the method returns it should refresh the page, and it does, but on the live server my code in the page_load event is not run? or is run differently? It never calls the displayCurrentPicks() method? Or if it does, it does not run correctly? except it runs perfectly on the test server.
I have no way to check this stepping through the code because when I do it works great, on the test server. The live server is hosted on Godaddy.
And I have tried everything. I have tried doing page refreshes after the correct methods and in my javascript to force the page_load event to be run again. Nothing works. I have been at this for a few days now. And I am sure all my code is publishing. I have done all the usual 'stupid checks'. The data is making it to the database, the picksMade() function returns true when there is data there. The data is there by the time the page refreshes.
Why does the live server not run the code I publish to it? Why does it run something different? Or Behave differently? I understand it is a different server, but shouldn't it run the code the same?
What exactly does the function validTime() do? If you are checking for specific time constraints it may be that your development server is set to your local time zone and that is why it is working but on your live server the timezone may be different. Just a guess though.