custom authorization and page protection in asp.net - 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.

Related

ASP.NET modify connectionstring at runtime

I need to change dataset connectionstrings to point to different DBs at run time.
I've looked at a number of solutions however they all seem to be related to WinForms or web application projects or other technology slightly different than what I'm using, so I haven't figured out how apply them.
The application is like a discussion. It's a web site project based on code originally written under VS2005, and there's no budget (or personal talent!) for major changes at this time. The app is written in vb.net; I can understand answers in c#. I'm working in VS2013.
The app has three typed datasets pointing to one MDF, call it "MainDB.mdf". There are dozens of tableadapters among the three datasets.
I'm going to deploy the app it as an "alpha/demo" version. I would like to use the same code base for all users, and a separate physical version of MainDB for each user, to reduce chances that the users crash each other.
The initial demo access URL will contain query string information that I can use to connect the user with the right physical database file. I should be able to identify the database name and thus the connection string parameters from the query string information (probably using replace on a generic connection string). If necessary I could use appsettings to store fully formed connection strings, however, I would like to avoid that.
I would like to be able to change the connection strings for all the datasets at the time that the entry point pages for the app are accessed.
Changing the tableadapter connection strings at each instantiation of the tableapters would require too much code change (at least a couple of hundred instantiations); I'd just make complete separate sites instead of doing that. That's the fall back position if I can't dynamically change the connectionstrings at runtime (or learn some other way to make this general scheme work).
Any suggestions on how to approach this would be appreciated.
Thanks!
UPDATE: Per comments, here is a sample instantiation of tableadapter
Public Shared Sub ClearOperCntrlIfHasThisStaff( _
varSesnID As Integer, varWrkprID As Integer)
Dim TA As GSD_DataSetTableAdapters.OPER_CNTRLTableAdapter
Dim DR As GSD_DataSet.OPER_CNTRLRow
DR = DB.GetOperCntrlRowBySesnID(varSesnID)
If IsNothing(DR) Then
Exit Sub
End If
If DR.AField = varWrkprID Then
DR.AField = -1
TA.Update(DR)
DR.AcceptChanges()
End If
End Sub
UPDATE: Below is the test code I tried in a test site to modify the connectionString in a single instantiation of a tableadapter. It feeds a simple gridview. I tried calling this from Page_Load, Page_PreLoad, ObjectDataSource_Init, and Gridview_Databind. At the concluding response.writes, the wrkNewConnString looks changed to TestDB2, and the TA.Connection.ConnectionString value looks changed to TestDB2, but the displayed gridview data is still from TestDB1. Maybe it needs to be called from somewhere else?
Sub ChangeTableAdapter()
Dim wrkNewConnStr As String = ""
Dim wrkSel As Integer
wrkSel = 2
wrkNewConnStr = wrkNewConnStr & "Data Source=.\SQLEXPRESS;"
wrkNewConnStr = wrkNewConnStr & "AttachDbFilename=D:\9000_TestSite\App_Data\TESTDB1.MDF;Integrated Security=True;User Instance=True"
Select Case wrkSel
Case 1
wrkNewConnStr = wrkNewConnStr.Replace("TESTDB1", "TESTDB1")
Case 2
wrkNewConnStr = wrkNewConnStr.Replace("TESTDB1", "TESTDB2")
Case 3
wrkNewConnStr = "Data Source=localhost; Initial Catalog=test01;"
wrkNewConnStr = wrkNewConnStr & " User ID=testuser1; Password=testuserpw1"
End Select
Try
Dim TA As New DataSetTableAdapters.NamesTableAdapter
TA.Connection.ConnectionString = wrkNewConnStr
Response.Write("1 - " & wrkNewConnStr)
Response.Write("<br/>")
Response.Write("2 - " & TA.Connection.ConnectionString)
Catch ex As Exception
Dim exmsg As String = ex.Message
Response.Write(exmsg)
End Try
End Sub
The connection string:
<add name="TestDB1ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=D:\9000_TestSite\App_Data\TESTDB1.MDF;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
UPDATE: the following post has lots of solutions, however, they seem to focus on web application projects, that have a project file with settings, which this web site project does not.
link with possible solutions
UPDATE: this next link was brought to my attention, and in working on it I did get it to work, however, it still relies either on having a web application project (with project file) or modifying each table adapter as they are instantiated. So, while I'm not going to implement it, I believe that is the technical answer.
modifying connection strings
sorry if this answer is too late, but I have exactly the same problem and eventually came up with a solution using Reflection.
My solution was to "save" a new default value for the connection string in the settings at run time, which means any further use of the table adapter uses the the new connection string.
It should be noted the term "save" is misleading as the new value is lost when the application closes.
Have tested and worked perfectly.
public void ChangeDefaultSetting(string name, string value)
{
if (name == null)
throw new ArgumentNullException("name");
if (value == null)
throw new ArgumentNullException("value");
Assembly a = typeof({Put the name of a class in the same assembly as your settings class here}).Assembly;
Type t = a.GetType("{Put the full name of your settings class here}");
PropertyInfo propertyInfo = t.GetProperty("Default");
System.Configuration.ApplicationSettingsBase def = propertyInfo.GetValue(null) as System.Configuration.ApplicationSettingsBase;
//change the "defalt" value and save it to memory
def[name] = value;
def.Save();
}

How to set the current user for WebPartManager?

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.

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"];

Identical asp.net web pages, except for 1 column. Currently 2 different aspx forms - can one set properties before redirecting?

I have 2 pages, which are identical, except for one column in a database (with sensitive information), which should not show in one of the pages.
E.g.
myPageIncludeSensitiveInfo.aspx
myPageExlucdeSensitiveInfo.aspx
At this point, each page is in a seperate code-behind file, and I need help on finding out how to do this in one page please. There is a pagebaseclass which is used for security.
I am not allowed to use Querystrings,
e.g. myPage.aspx?include=true
or myPage.aspx?exclude=true
In windows pages I would have had the option:
dim myPage1 as new myPage
myPage.bIncludeSensitiveInfo = False
myPage1.show()
but with asp.net forms it is a response.redirect and I don't know if one could set properties beforehand.
Thank you
If you are not allowed to use querystring-parameter(reasonable in this case), use the Session.
Session("includeSensitiveInfo") = True
Response.Redirect("myPage.aspx")
and on myPage.aspx (assuming columns means a column in a GridView and it's the first):
gridView1.Columns(0).Visible = Session("includeSensitiveInfo") IsNot Nothing _
AndAlso DirectCast(Session("includeSensitiveInfo"), Boolean)
Nine Options for Managing Persistent User State in Your ASP.NET Application

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