Adding Windows User Name to database - c#

ASP.NET MVC3 newb here.
I am working on a MVC3 intranet application that uses windows authentication. Windows auth is setup and ready to go no problem.
What I need to happen is to capture the username (Domain\first.last) whenever a user accesses the app for the first time and then store that information into a database and associate that name to a another unique identifier (numeric and auto-incremented).
I already found a way to get the username:
string user = WindowsIdentity.GetCurrent().Name;
What I am having an issue with is taking that variable and storing it in my database.
Any suggestions, hints, tips or nudges towards helpful resources are greatly appreciated.
Apologies if this scenario was posted elsewhere, if it was then I was unable to locate it.
Cheers Guys!

Be careful - user names and display names can change. I would avoid storing them in the database.
Instead, look at storing the SID (id of the user). The User property of the WindowsIdentity returns the SID. You can store and update the user name for display purposes but don't rely on it for typing the authenticating user back to the previous user in your DB.
See this SO post as well:
How can I get the SID of the current Windows account?
Persist the SID (along with username for display only) and look up via SID.

I think what you are looking for here is really 'how to store some info in a database'
What database system?
Check out
http://www.datasprings.com/resources/articles-information/a-quick-guide-to-using-entity-framework
You can easily use the entity framework to store that value in the database which is what I think your question was really about. I do agree with Bryanmac though, you should be storing the SID not the login name in case the name changes. If you know it will NEVER change then you could store the name, but since they can technically change in Windows, I'd be aware of this.
If you have a specific question then on how to store that field using the Entity Framework, please post that.

When you create your MVC3 application, there is an option for "Intranet Application" that has all of the Windows Authentication stuff working already, you might want to check that out and pull over pieces of the code for your current project (or migrate what you have depending on how far you are).
It has some special code placed into Web.Config as well as the extra files it creates.
Read more here:
http://weblogs.asp.net/gunnarpeipman/archive/2011/04/14/asp-net-mvc-3-intranet-application-template.aspx
and here:
http://msdn.microsoft.com/en-us/library/gg703322%28VS.98%29.aspx
Also you'll want to use User.Identity.Name to reference the person viewing the website.

Related

change loginpath for specific user, ASP.Net, webforms

I recently started working on a site that another developer built (who is not within the company anymore, so can't ask him)
On the site there is several separate accounttypes for users, so when a user logs in, the user comes to one of two specified login-start pages.
Some users have two accounttypes. When that's the case I want to make a dropdownlist that holds both startpage-options (let's call them a, and b)
If they choose option a) from the ddl, the a-startpage will be that users permanent startpage until the user changes it to b, then b will be that specific users permanent startpage.
the project is made with C#, ASP.NET, with Webforms, MS SQL.
any suggestions that might lead me in the right direction is much appreciated
/S
there are at least 2 possible solutions that require little effort:
a cookie on the user's system: when accessing the system for the
first time (or after a system change or a browser's cookies clearing)
the application takes the user to the dropdown page and let the user choose the
preferred login-start page. on subsequent accesses the choice is read from the cookie and then the user is forwarded to the expected page. the biggest advantage IMHO is that no changes to the backend structure are required and the changes on the fronted are minimal.BEWARE: do not trust what you get
reading the cookie and always double check that the page suggested
by the cookie is actually allowed for the user.
an attribute of the user: the user choice is saved in the user's profile and read on subsequent accesses.this approach requires some change in the backend because a new attribute must be added to the user entity and maybe also the tools (stored procedure, method, whatever) needed to interact with that new attribute have to be created.this solution requires less or no checks/validation because the information is stored server side so you can redirect 'blindly' to the login-start page.
there is not a 'right' solution because it mainly depends on what you are allowed to do and your skills.are you allwed to alter the backend's structure? what you know better, backend or frontend development?which one is easier for you to change? is there any policy/guideline to follow while developing that favor one of these approaches?
So in the end i solved it like this.
Firstly i created an int(allows null) column called "changesite" in the db (member/user)table so i could use the members id.
Then i connected it to the dropdownlist where the members/users can choose their startpage (in my case i made the ddl only visible to the members if they are the type of user that has the both user accounts).
if the user chooses the first option a 1 got saved in the db, and for the second option a 2. (This method could be used with any number of startpages you might have).
Then in .cs file were users got redirected to their designated startpage it was as simple as creating an if, else-statement, with the value from changesite as identifier.
Basically if the value from column changesite == null, do nothing. If changesite == 1 redirect to the first startpage and else redirect to the second startpage.
A big thx to Paolo for his inputs.

Is there any basic string obfuscation I can use whilst pair programming?

Whilst pair programming with database systems, sometimes we end up temporarily hardcoding credentials (typically of our own accounts), which leads to slight awkwardness with the partner trying to look away whenever the password is onscreen. Is there any simple way of using basic obfuscation (ie, rot13) to hardcode a password without other developers taking a quick look and seeing my password?
It doesn't need to be secure. It only needs to grease the social aspect. I don't want anything complex involving super secure encryption or reading passwords out of files etc. This has to be quick to implement (i.e. 10 seconds max) whilst coding on the fly. Ideally I want something like:
string password = string.rot13("zlcnffjbeq");
Does anything like this already exist?
To configure SQL Server for Windows integrated security
From the Windows Start menu, select Microsoft SQL Server, and then select Enterprise Manager.
Open the node for the server and expand the node for the database you want to give users permissions for.
Right-click the Users node and select New Database User.
In the Database User Properties dialog box, enter domain\username in the Login name box, and then click OK. Additionally, configure the SQL Server to allow all domain users to access the database.
From MSDN. Connection strings become Server=x;Initial Catalog=y;Integrated Security=true instead of Server=x;Initial Catalog=y;User=you;Pwd=yourpassword.
I would suggest to store your password in a config file. For source control, use a dummy one. Then after getting latest version of the config file on your PC, you can modify the config by adding your password.
You could use base64 and just keep the base64 version of your password somewhere handy for cut and paste, bearing in mind that your system admin will have a blue fit if they find out about this. Both the suggestions in comments (#Oli/#CodeCaster) are preferable to this, imo.
DPAPI is more work but arguably a balanced solution to your requirement, with some security.
The .NET Framework provides access to the data protection API (DPAPI),
which allows you to encrypt data using information from the current
user account or computer. When you use the DPAPI, you alleviate the
difficult problem of explicitly generating and storing a cryptographic
key.
Maybe you can store your password in a String variable like here
/* Variable that stores the password */ string pwd = "12345";
string password = string.rot13(pwd);
and tab it out of the visual range of the editor. This would be a proper solution to your problem.
Then you can use the string variable somewhere else in your code and no one can see your password unless he scrolls to the right

ASP.Net /IIS Automatic Site Creation

I am looking for some open source ASP.net script that basically creates an IIS site automatically. Basically a user will enter the domain name they want (myname.mysite.com [it will always be a subdomain of mysite.com]) they would pick a username and password, and enter some other contact information. I would also add some other options that are specific to our program but these will be coded later and are not important to this question. Once they click submit it would create the Databases, DNS, create default pages, set permissions to those pages, etc.. Has anyone seen anything that can do this or would I need to create something like this from the ground up?
You can use Microsoft.Web.Administration as in this blogpost
Or you can use System.DirectoryServices as shown here

Changing the membership providers ApplicationName during runtime. How?

I have a bit of a unique situation here. I'm making a web application that is going to have
the ability to login with different web applications credentials. For example you can login/register with my site or you can login/register with your YouTube account. I'm not using OpenID because I need to have access to YouTube's data in this case.
I'm using ASP.NET MVC 3 EF4 with custom Membership, role, profile providers.
The problem is user names can't be unique because someone with a YouTube user name could have the same user name as someone that registered with my site. So I got around with by specifying a user type in my user table. This is pretty much a composite key (user id and user type).
I have a custom authorize attribute that is checking for the role that the user is in but now I need to implement a custom IPrincipal because I need to pass a user type. Only problem is where do I store that? the session?
Originally I thought this is what the Application table was for, and I had momentary success with that but read there is threading issues, and I was getting session faults all over the place it wasn't that great :(
I'm wondering what the best way to do with is because I can't use the overridden methods in the providers because I have to add a UserType parameter to some of the methods, but then this breaks the functionality of the provider.
EDIT:
I basically need to have the ability to change the ApplicationName at runtime pro-grammatically. I tried doing this, the only problem was when I stopped my development server but left my browser open then ran my dev server again it wouldnt keep the application name.
EDIT:
I've changed my application to use OAuth, I never found a good solution.
I basically need to have the ability
to change the ApplicationName at
runtime pro-grammatically. I tried
doing this, the only problem was when
I stopped my development server but
left my browser open then ran my dev
server again it wouldnt keep the
application name.
If you need to change the ApplicationName, this means you need to select a provider at runtime.
The only way to do this is to NOT use the singleton "Membership" as it uses the provider defined in web.config.
Instead each time you need your provider use :
MembershipProvider userProvider = Membership.Providers[UserProviderName];
Just set UserProviderName the way you want. I would go with a custom global authorization or preAction filter which detect the provider from some cookie or other session variable and put the provider in the HttpContextBase.Items collection which lives for one and only one request.
The best answer to this problem is answered on stackoverflow here: Membership provider with different ApplicationName in area
Here's the code they used:
Membership.Providers["MyOtherProvider"].ValidateUser(username, pwd);
Ryan,
Hmmm... can you work-around the problem by prepending the issuing-authority (local or YouTube) to the username field itself... Example usernames: "LOCAL/corlettk", "YOUTUBE/corlettk"???
Ok, you'll need a custom Authenticator in order to split the complex-string, and flick-pass the login-request to appropriate underlying Authenticator... but once that's done, (I guess) you're all set to deal EASILY with the much bigger problem (from your perspective) of Authorisation.
I percieve that you're a smart guy... have you considered-and-dismissed this approach allready?
Cheers. Keith.
PS: Yes, I'm a hacker... but I have bad habit of hacking stuff up that WORKS... so they've given-up trying to educate me.

How do you get user info from a company's domain/network settings in C#?

I was told that user info like name, address, phone, etc are stored on the network (obviously only if a person has given that info). This is the info that Outlook gets when searching for users on the network (the info that Outlook populates the Contact card with). This obviously works because I can search for anyone in my company's network and I get results for people all over the world that are on our network.
The program I am working on is internal to our company and one of my tasks is to pre-populate a form with that info.
My question is, how do I get this information? Where is it stored? What object do I use to get it?
EDIT: I was a little general on this. What I really need is the current user's info ('current' being whoever is logged on to the computer and using my program). What is the best way to get it?
To read from Active Directory, the classes you need are in System.DirectoryServices.dll. The important ones are DirectorySearcher and DirectoryEntry. Take a look at the the first 2 answers to this other question to get more code: How to get the current user's Active Directory details in C#
Update: To get the current user's info, take their logon name and then do a search in Active Directory for a user with the same user ID. Something like this:
adSearch.Filter = "(sAMAccountName=" + Environment.UserName + ")";
(In ASP.Net you would get the user name elsewhere.)
If you're using Active Directory, then you can query that information from there, given the domain and username. It's basically an LDAP store, but there's tonnes of info on the web for how to implement it.
Here's another question that specifically asks how to retrieve this information from Active Directory:
How to get the current user's Active Directory details in C#
In a desktop app, to get the current logged-on user's Windows username, you can use Environment.UserName.
One additional tip to go along with the answers David and Neil Barnwell provided:
You can get their ID using HttpContext.Current.User.Identity.Name.
If you want use this from an assembly or some other back end code, make sure you add using System.Web.
To answer your question of "is there a way to get the current domain controller..." one way that has been helpful for me is to use the nltest command [1] like this:
C:\>nltest /dsgetdc:yourdomain.com
It should output all kinds of useful stuff.
[1] http://support.microsoft.com/kb/247811

Categories

Resources