I'm creating a simple website for multiple users. Now i'm trying to make the profile of each one so when they login they can see their data. The problem is that once logged in with one user and i login with another one my session gets "overwritten" and the new user become the old one. So i think i'm messing up with the session part.
I'm telling you what i've done.
Inside the login controller i call a the Login function, passing username and password.
Then i validate the user credentials to the database and if the user has been authenticated i do:
new_session = new UserSession();
new_session.SessionSet(obj);
Inside the "SessionSet" i just initialize some variables i need:
this.id_account = obj.id_account;
this.id_user = obj.id_user;
this.username = obj.username;
At this point i return the new_session to the Controller and if it is not null i just add it to the session:
Session.Add("user", new_session);
The problem now is how can i get this specific object form : views, classes and controllers?
If i write in a view:
(((UserSession)Session["user"]).username)
I get only the "user" object so when 2 users log in at the same time, the session refer always to the "user" one.
I googled it but i can't find an answer that fits to my needs.
get database UserSession data
see user with this useID Is logged in
if user logged in {not allaw login} else {allow login}
or write data in session with timeout
if(Session["users"] != null)
{
List<UserSession> users = (List<UserSession>)Session["users"];
var finduser = users.Where(a=> a.id_user == newUser.id_user).FirstOrDefault();
if(findUser == null)
{
//add user into session
}
}
else
{
Session.Add("users",newUser);
}
and web.config file set timeout logout and session equal
<sessionState mode="InProc" timeout="20"></sessionState>
<authentication mode="Forms">
<forms loginUrl="/Pages/Default" timeout="20" slidingExpiration="true" />
</authentication>
I am making an asp.net web site in C# and I have a database in slq server with a table Users(id, username, password, isAdmin). The column isAdmin is int with default value 0, so if the user is admin, isAdmin = 1 else isAdmin = 0.
I have a login form in the website and when the user logs in, it creates a Session("admin") or Session("user"), depending on the isAdmin value.
So, how can I restrict access on Session("user") to admin.aspx page and to the upload folder on the site?
I don't want to add roles management in IIS, because the admin can make other users into admins (updating the isAdmin to 1)
Thanks.
Don't keep standard user & admin in separate session variables. Rather create a class that maps to your User table and store user info in it in generic way. One property of that class would be .isAdmin (integer or even boolean). Then you could simple check something like in "admin.aspx"
UserInfo objUserInfo = (UserInfo)Session("user");
if (objUserInfo.isAdmin == 0) {
Response.Redirect("User.aspx");
}
something in this logic:
after logging in, save user role in session var first.
and then in the page_load of the restricted page, check user's role and if he is not admin, redirect him to relogin with an admin account.
protected void Page_Load(object sender, EventArgs e)
{
if(session["role"].ToString().compareTo("admin")==0)
{
//load page stuff
}
else
{
Response.Redirect(your login page);
}
}
Turn off directory browsing in IIS. Add this in your web.config to prevent users from browsing folders. This is will work in IIS 7+
<configuration>
<location path="Secured">
<system.webServer>
<directoryBrowse enabled="false" />
</system.webServer>
</location>
</configuration>
I have an web service call where I get a list of 5 access codes, a user will be able to login with one of those codes(basically feel special that they have the code, but nothing secure about it, as they could share codes if they wanted to)
I would want to be able to use the [Authorize] if at all possible. Won't be using a database, just that one api call. Is this possible?
Check the codes on login with a simple if statement
if{code1 == "edgwreggw" || code2 == "etgwg"....)
{
FormsAuthentication.RedirectFromLoginPage(data.username, true);
}
else
{
login fail
}
Webconfig
<authentication mode="Forms">
<forms loginUrl="~/UserAuthentication/SignIn" timeout="10" defaultUrl="~\Home\Index" />
</authentication>
So.. you really don't care about security but you want to hand out 1 of 5 codes to random people to use your web service.
Simple enough. Put the codes in an array. Check if the code passed in is one of those values. If not, end the request. If it is, process the request.
I am trying to figure out why HttpContext.User.Identity.Name is returning blank.
Code
public ActionResult Test()
{
string username = HttpContext.User.Identity.Name;
return Content(username);
}
Am I using this in the wrong context? I am trying to get the user's username.
Web.Config
<authentication mode="Windows" />
IIS
I have enabled Anonymous and nothing else is checked. I am running IIS 6.0.
Is there any type of information I need to add to assist with figuring this out? I am pretty stuck. I checked this question but do I need to set a Cookie to make this work?
I have enabled Anonymous and nothing else is checked. I am running IIS
6.0.
This means that you won't be prompted to login, so User.Identity.IsAuthenticated will be false and User.Identity.Name will be blank.
Uncheck Anonymous Authentication and check Windows Authentication.
IsAuthenticated returns false, and thus Identity.Name returns empty string because you haven't required authentication for that action. You have to enable Windows Authentication and require authentication for the action. Try requiring that the user be authorized for the action by decorating it with the [Authorize] attribute - which will initiate the authentication negotiation.
[Authorize]
public ActionResult Test()
{
if(Request.IsAuthenticated)
{
string username = HttpContext.User.Identity.Name;
return Content(username);
}
else
{
return Content("User is not authenticated");
}
}
If anyone else is experiencing this issue, verify "Load User Profile" option is set to true. Go to IIS application pools. Select your app pool from the list. Click on Advanced Settings and scroll down to Process Model section.
This solved the problem in my case.
If you are using FormsAuthentication.SetAuthCookie
then you need to add
<authentication mode="Forms" />
to
<System.Web>
in Web.config file.
Solution from here
In a forms model, I used to get the current logged-in user by:
Page.CurrentUser
How do I get the current user inside a controller class in ASP.NET MVC?
If you need to get the user from within the controller, use the User property of Controller. If you need it from the view, I would populate what you specifically need in the ViewData, or you could just call User as I think it's a property of ViewPage.
I found that User works, that is, User.Identity.Name or User.IsInRole("Administrator").
Try HttpContext.Current.User.
Public Shared Property Current() As
System.Web.HttpContext
Member of System.Web.HttpContext
Summary:
Gets or sets the System.Web.HttpContext object for the current HTTP request.
Return Values:
The System.Web.HttpContext for the current
HTTP request
You can get the name of the user in ASP.NET MVC4 like this:
System.Web.HttpContext.Current.User.Identity.Name
I realize this is really old, but I'm just getting started with ASP.NET MVC, so I thought I'd stick my two cents in:
Request.IsAuthenticated tells you if the user is authenticated.
Page.User.Identity gives you the identity of the logged-in user.
I use:
Membership.GetUser().UserName
I am not sure this will work in ASP.NET MVC, but it's worth a shot :)
getting logged in username: System.Web.HttpContext.Current.User.Identity.Name
UserName with:
User.Identity.Name
But if you need to get just the ID, you can use:
using Microsoft.AspNet.Identity;
So, you can get directly the User ID:
User.Identity.GetUserId();
In order to reference a user ID created using simple authentication built into ASP.NET MVC 4 in a controller for filtering purposes (which is helpful if you are using database first and Entity Framework 5 to generate code-first bindings and your tables are structured so that a foreign key to the userID is used), you can use
WebSecurity.CurrentUserId
once you add a using statement
using System.Web.Security;
We can use following code to get the current logged in User in ASP.Net MVC:
var user= System.Web.HttpContext.Current.User.Identity.GetUserName();
Also
var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; //will give 'Domain//UserName'
Environment.UserName - Will Display format : 'Username'
This page could be what you looking for:
Using Page.User.Identity.Name in MVC3
You just need User.Identity.Name.
Use System.Security.Principal.WindowsIdentity.GetCurrent().Name.
This will get the current logged-in Windows user.
For what it's worth, in ASP.NET MVC 3 you can just use User which returns the user for the current request.
If you are inside your login page, in LoginUser_LoggedIn event for instance, Current.User.Identity.Name will return an empty value, so you have to use yourLoginControlName.UserName property.
MembershipUser u = Membership.GetUser(LoginUser.UserName);
You can use following code:
Request.LogonUserIdentity.Name;
IPrincipal currentUser = HttpContext.Current.User;
bool writeEnable = currentUser.IsInRole("Administrator") ||
...
currentUser.IsInRole("Operator");
var ticket = FormsAuthentication.Decrypt(
HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value);
if (ticket.Expired)
{
throw new InvalidOperationException("Ticket expired.");
}
IPrincipal user = (System.Security.Principal.IPrincipal) new RolePrincipal(new FormsIdentity(ticket));
If you happen to be working in Active Directory on an intranet, here are some tips:
(Windows Server 2012)
Running anything that talks to AD on a web server requires a bunch of changes and patience. Since when running on a web server vs. local IIS/IIS Express it runs in the AppPool's identity so, you have to set it up to impersonate whoever hits the site.
How to get the current logged-in user in an active directory when your ASP.NET MVC application is running on a web server inside the network:
// Find currently logged in user
UserPrincipal adUser = null;
using (HostingEnvironment.Impersonate())
{
var userContext = System.Web.HttpContext.Current.User.Identity;
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["AllowedDomain"], null,
ContextOptions.Negotiate | ContextOptions.SecureSocketLayer);
adUser = UserPrincipal.FindByIdentity(ctx, userContext.Name);
}
//Then work with 'adUser' from here...
You must wrap any calls having to do with 'active directory context' in the following so it's acting as the hosting environment to get the AD information:
using (HostingEnvironment.Impersonate()){ ... }
You must also have impersonate set to true in your web.config:
<system.web>
<identity impersonate="true" />
You must have Windows authentication on in web.config:
<authentication mode="Windows" />
In Asp.net Mvc Identity 2,You can get the current user name by:
var username = System.Web.HttpContext.Current.User.Identity.Name;
In the IIS Manager, under Authentication, disable:
1) Anonymous Authentication
2) Forms Authentication
Then add the following to your controller, to handle testing versus server deployment:
string sUserName = null;
string url = Request.Url.ToString();
if (url.Contains("localhost"))
sUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
else
sUserName = User.Identity.Name;
If any one still reading this then, to access in cshtml file I used in following way.
<li>Hello #User.Identity.Name</li>