How to set the current user for WebPartManager? - asp.net

From what I've been reading, the following code should first ensure that a MembershipUser record exists for "ArthurDent", then set "ArthurDent" as the current user, and finally assign his MembershipUser record to the variable mUser.
if (Membership.GetUser("ArthurDent") == null)
{
Membership.CreateUser("ArthurDent", "thisisapassword");
}
FormsAuthentication.SetAuthCookie("ArthurDent", true);
MembershipUser mUser = Membership.GetUser();
Instead, the variable mUser remains null.'
My goal is to programmatically set the current user to a valid record so that I can set a WebPartManager.DisplayMode on a page that started erroring out when I added BlogEngine to my web site.

This problem generally occurs when the application breaks a rule defined in the web.config file. For instance I ran your code in my local environment using Windows Authentication and CreateUser at first failed because the password string was of insufficient length. I padded the password with additional characters and was able to create user with the supplied code. Check the section to examine password prerequisites.
Upon first examination this looks like a configuration problem.

The answer is that BlogEngine actively suppresses the normal workings of Page.User.Identity, which Membership.GetUser() retrieves. When I replaced FormsAuthentication.SetAuthCookie with the following code from BlogEngine...
Security.AuthenticateUser("ArthurDent", "thisisapassword", true);
... it authenticated Arthur and logged him in.

Related

Dynamic connString (now stored in session, bad)

I working on a project where the connString is stored in a session variable. The problem is that the session runs out when the user is not around for a while (makes sense), thereby making the user having to log in again to create a new connection.
The user selects his database from a list of ODBC connection configured on the web server, therefore the different connStrings the user can chose from cannot be stored in the web.config as the user can add new ones as they wish.
I was wondering how to fix this problem. Should I just tell the user not to leave his computer for 20mins+ or can I perhaps store the connString someplace else? Ive seen websites making a pop-up saying "your session will expire in 5 mins, press ok to continue using the site", or something like that.
Furthermore it is not a possbility to make a static varible as the website is shared between many users, so if user1 choses "connString1" and user2 choses "connString2" afterwards, then user1 will unfortunatly be running on "connString2" aswell.
Hope you can help :)
**
Can this be a solution?:
I create a "BasePage" which my pages inherit from. In this basepage i create a hiddenfield and add the connString to the value property on load. Furthermore I will encrypt the connString so the user cannot see the value in the source code.
Then, if the session has a timeout, i will restore the session by using the value in the hiddenfield and the site will not crash.
Can you store the user's connection string preference in their Profile and then persist their profile? http://odetocode.com/articles/440.aspx
You should also be able to do this for anonymous users.
As an aside, I don't know how secure the Profile APIs are, they should be fine, but just in case, you might want to store an Enum value and then map that to a Connection string in your code.
You could use the app.config to get and set config files. Take a look at this to see implementation of storing files. Its just as easy to get settings.
ConfigurationManager doesn't save settings
//Edit: If you don't want the user to be able to see your connectionstring name then you can provice an another in hidden_html or cookie or session cookie. In this example I use a cookie. THis should solve your problem.
To set cookie:
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie["ConnectionString"] = "MyCOnnectionValue";
myCookie.Expires = DateTime.Now.AddDays(1d);//For one day.
Response.Cookies.Add(myCookie);//Will store the cookie within the users browser so your code can read from it at every request.
then:
if (Request.Cookies["UserSettings"] != null)
{
string userSettings;
if (Request.Cookies["UserSettings"]["ConString"] != null)
{ userSettings = Request.Cookies["UserSettings"]["ConString"]; }
}
string connectionStringNameToUse;
if(userSettings =="Connection1"){
connectionStringNameToUse = "here you can have your name of connectionsstring";
}etc with ypur other connectionsstrings here.
//Then use your connectionsstring here:
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionStringNameToUse ].ToString()))
{
cn.Open();
using (SqlCommand command = new SqlCommand
("delete TBL from RatingListObjects TBL where ( TBL.TradeObject1Id = #MY_ID ) or ( TBL.TradeObject2Id = #My_ID ) ", cn))
{
command.Parameters.Add(new SqlParameter("#MY_ID", customerToRemove.TradeObjectId));
command.ExecuteNonQuery();
}
}
On the other hand. I would go for saving the users database of choice in with the other user data in the db. But this is doable if you only want the user to have a chosen connectionsstring a certain time, set by the program. It wont allow them to see the connections string name. Hopes this helps, good luck!

Show Logged In User Name in redirect.aspx Page

I'm a complete stranger to ASP.NET. But, I've had a project to do using it & faced a problem.
It is :
I have a login.aspx File - Where Users provide login User name & Password
If Login details (match Data Base) OK then User automatically redirects to logged_in.aspx.
There's a label (lbl_show) in redirected logged_in.aspx.
I need to show Logged in Username in it.
I read bunch of articles & came with nothing because of my lack of understanding so please help me.
se session variables in order to pass any value from one page to another.
Assign the Username value to the session variable and use it in your logged_in page as follows:
// In login page
Session["UserName"] = txtUserName.text;
//In logged_in page
label1.text = Session["UserName"];
Also refer the following link for State Management:
http://www.codeproject.com/Articles/492397/State-Management-in-ASP-NET-Introduction
You need to set an Authentication Cookie. It's easy and will allow you to leverage ASP.NET functionality easily (many built-in controls and also user-access control). I detail how in this SO post:
Using cookies to auto-login a user in asp.net (custom login)
The problem with the code
// In login page
Session["UserName"] = txtUserName.text;
//In logged_in page
label1.text = Session["UserName"];
Is casting is missing it should be
label1.text = Session["UserName"].ToString();
Edit 1
As Session contains object and if you have something other than object then you will have to explicitly cast it in your require type.
Suppose you have array in you Session then you will have to cast it back to array.
String[] Names={"abc","def","ghi"};
Session["NamesCol"]=Names;
Then if you want to use it you will have to cast it as follow
String[] NewNames=(string[])Session["NamesCol"];

Change Umbraco member password with out knowing old password

I need a functionality to change umbraco member password programatically.user can add their new password in the field I had set on umbraco node.and when they publish the node new password will come in effect.I had find a way to change current password to given one
member.ChangePassword(oldPassword, password);
But this requires oldpassword to work.and I cant provide it as user has already changed old password in the umbraco node.then I tried to get old password programatically.
string theUserPassword = Membership.GetUser(username).GetPassword();
but this also throws an error
Password Retrieval Not Enabled.
Is there any way to get old password programatically?Or Am I going in the wrong direction?
Umbraco uses the Microsoft Membership Provider.
You probably have set the property "EnablePasswordRetrieval" to false.
If you don't know the password but need to change it, you can reset the password bij using the ResetPassword method.
I know this is an old post and an answer has already been accepted, but you can actually achieve what the OP wants to do by using the return value of the ResetPassword method for the oldValue parameter of the ChangePassword method:
member.ChangePassword(member.ResetPassword(), "New Password")
This allows you to change the password for a user to a specific value without knowing their existing password.
Another option to an old question:
I am using Umbraco 7.2.4 and here is how I change the password.
var member = Services.MemberService.GetByUsername("username");
Services.MemberService.SavePassword(member, "new password");
Where "Services.MemberService" is from ApplicationContext.Current.Services.MemberService.
The first line of code is where you get the member for which you want to change the password. This can also be done by email or id.
Services.MemberService.GetByEmail("email")
Services.MemberService.GetById(id)
The second line is where you change the password. It is automatically hashed.

custom authorization and page protection in asp.net

need to solve a custom authorization issue.
I already have four tables in my database named:
1. Usermaster
2.Roles
3.RoleMenu
4.Menu
I have implemented this and its working perfectly.
My only issue now is that an authenticated user can view an unauthorized page by simply entering the page url in the browser.
Any useful ideas apart from forms authentication and folder level access?
I had a project similar to this and i can't seem to find the code anywhere as it was quite awhile ago. I remember the premise though. What i did was i set up a key in the webconfig that had usernames allowed access in a pipedelimited string. Behind the code i would pull in that key as well as the user trying to access the page. I would then search the string and try and match the user. If a match was found the page would load, if a match wasn't found it would redirect them to a page telling them they didn't have access and who to contact to request access. I'll look for the code and edit if i find it.
EDIT
WebConfig
<appSettings>
<add key="Users" value="user1|user2|user3|..." />
</appSettings>
This piece goes above the
For the .aspx.vb page
Dim DomainUserName() As String = Request.ServerVariables("LOGON_USER").Split("\")
Dim UserName As String = DomainUserName(1)
Dim Users() As String = ConfigurationManager.AppSettings("Users").ToString.Split("|")
Dim isAllowedAccess As Boolean = False
For i As Integer = 0 To Users.Count - 1
If UserName = Users(i) Then
isAllowedAccess = True
Exit For
End If
Next
If isAllowedAccess = False Then
Response.Redirect("Default.aspx")
End If
Essentially our logins are domain\username so what i'm doing is extracting just the name using a split. I'm then populating the accepted users into an array splitting on the pipe and looping through them searching for a match. when the match is found it allows them access, if a match isn't found they are redirected back to the home page.

ASP.NET / VB.NET Check If a (different) User IsInRole

I have an ASP.NET application on our company's intranet. And a funky security requirement.
I need to check to see if a given username is in a certain role. I cannot use
Page.User.IsInRole("MyDomain\MyGroup")
because
Page.User.Identity.Name
Returns an empty string. Because of some lovely specifications for this program, I have to keep anonymous access enabled in IIS. Seems to rule out any page.user.identity stuff.
So I did find a way to (at least) get the current user (from System.Environment.UserName), but I need to bounce it against the domain group to see if they're in it. Or, better yet, get a list of users within a given domain so I can check myself. Something like...
Dim UserName as String
UserName = System.Environment.UserName
If User(UserName).IsInRole("MyDomain\MyGroup") Then
MyFunction = "Success"
End If
-OR -
Dim GroupUsers as String()
GroupUsers = GetDomainUserNames("MyDomain\MyGroup")
Anybody have any ideas?
You can call IsUserInRole from the Roles static class. Here is a sample and some reference materials.
Roles.IsUserInRole(username, rolename);
link: http://msdn.microsoft.com/en-us/library/system.web.security.roleprovider.isuserinrole.aspx

Resources