Obtain MembershipUser in ASP.NET MVC - c#

I'm writing a new application in ASP.NET MVC. I've created a custom MembershipProvider that stores membership data in my own db schema. It all works, but how do I get the MembershipUser in my application, such that I can get the user key of the logged-on user and load model classes relating to that user?

You can use the following:
using System.Web.Security;
var user = Membership.GetUser();

Use the static Membership class to retrieve the user using GetUser. You'll need to configure your provider in the web.config file. On logon you get the username from, presumably, a text box on your form. Once logged on you can get it from the controller's User property.
string username = this.User.Identity.Name;
MembershipUser user = Membership.GetUser( username );

Related

Asp.net Identity 2.0 temporary password

In my MVC application user registration is implemented in two ways; the user register and then approved by the Administrator; or the Administrator can create a user. My question is: will it be possible to send a temporary password and then the user has to change it after first login, or can I flag this user to use external authentication first time.
I would appreciate your suggestions.
You can define a UserAccount class like this:
public class UserAccount
{
public int AccountId { get; set;}
public UserAccountState AccountState { get; set; }
public Guid ActivationCode { get; set; }
public string Password { get; set; }
}
Where UserAccountState is
public enum UserAccountState
{
PendingActivation = 0,
UsingTempPassword = 1
Normal = 2
}
When a new user just signed up. You can put his account to the PendingActivation state and send him a link to activate the account, something like this
www.MySite.com/Activate?code=F3D17EE
When user clicks on the link, you match the user account with the code, and do the following:
Generate a temp password for the account, e.g "TempPass12"
Change the account state to UsingTempPassword
Show the following message to user
"Your account is now activated. Click here to login with your temp password TempPass12"
After user login to your site with the temp password, your code should detect that the UserAccountState is in the UsingTempPassword state and subsequently redirect the user to the change password page.
After a new password is provided by the user, the account can be put to the Normal state.
Add a column in your password table, something like 'ForceToChangePassword'. Check that column every time an user logged in, if it was set to true, redirect user to the change password page.
My opinion is to use roles than using new columns, and checking things every time user logged in as it is not good when we thinking about performances.
Create three new roles it could be
Created - User created by admin
Registered - User registered by them self
Approved - Approved by admin
In your case if the user registered them self, then add them to ROLE 'Registered'. If the user created by admin then add them to ROLE 'Created'. Once admin approved or user change there password first time login, then you can add them to ROlE 'Approved'.
Then you can handle user self registration and admin creation controller actions to add users to correct ROlE.
There is a column called 'EmailConfirmed' already there, so that you can use that column for your purpose. Update that column when the user approved or successfully change the password on first login.
As you know that password field is nullable, so that you don't need to insert temporary passwords, (but you could if you want). You can keep password field as null and update it when the user first login. You need to change your views to support this scenario.
You can use asp.net identity framework supported methods in order to achieve this.
GenerateEmailConfirmationTokenAsync
GenerateEmailConfirmationToken
IsEmailConfirmedAsync
ConfirmEmailAsync
This role based scenario may help you to categorize users depending on there role and restrict access easily using [Authorize(Role = "RoleName")].
Let me know if you need anymore details.
Hope this helps.

How do you obtain user profile values in ASP.NET Identity 2 of current user?

In an MVC5 application how do you get values from the AspNetUsers table for the current user?
For example: one of the default fileds is PhoneNumber. How do you get the phonenumber of the current logged in user?
I am using Identity 2...
You need to get the IdentityUser object (probably a descendant like ApplicationUser in your application) from Entity Framework. There are a number of ways you could do this, depending on where you are and so on. But, for example, if you wanted to do that in the controller, where you have access to the currently logged in user with the User property, you could use UserManager<TUser>.FindById() like this:
// UserManager here is an instance of UserManager<ApplicationUser>
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
var number = user.PhoneNumber;

How to give user access in MVC C#?

I want to give the user access according to the user role.
I have two user roles. they are Admin and user.
I write my controller like this.
[Authorize(Roles = "Admin")] // my Problem is here. I don't know how to set the current user role
public ActionResult Index()
{
var query = from company in db.tblCompanies
select company;
return View(query.ToList());
}
But I don't know how to set the Roles = "Admin" after cutomer login.
In my user tale I have Roles coloum and it can save Admin or user.
But I don't know how to set and where should I set Roles = "Admin".
Based on your question what I get is you want to set the currently logged user to some role. So here is my answer to that.
To Add a User to a Role:
Roles.AddUserToRole(userName, roleName);
To Remove a User from a Role:
Roles.RemoveUserFromRole(userName, roleName);
Reference Links:
SO - How to Assign roles to User while creating their account
MSDN - Implementing a Custom Role Provider
MSDN - Roles.AddUserToRole Method
MSDN - Roles.RemoveUserFromRole Method
Take a look at this :
http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-7
You basically assign roles to your users via the ASP.NET Configuration website. Once done the user - role mapping is handled by default.

getting username which is set in UserData of FormsAuthenticationTicket

Im thinking of getting usernames of my site using this in my view(Razor syntax):
#MySite.Helpers.Utils.UserName
heres the utils class:
public class Utils
{
static FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
public static string UserName { get { return id.Ticket.UserData; } }
}
Are there any potential problems with this code?
The reason Im doing it like this is because Im going to store username in the userdata field of a new FormsAuthenticationTicket when the user logs in.
I'm handling it like this because Im using facebook connect and want to store there ID in the username field in the db and their usernames/fullnames in a separate table.
so my logic to handle facebook usernames and my site registered usernames needs to be handled differently. Upon login Im thinking of handling it there then setting userdata as the actual username.
therefore throughout the site i can just get the logged in users name using : #MySite.Helpers.Utils.UserName
does this sound ok? will the fact that its a static variable be an issue?
or is there a better way to manage this? session variables maybe?
thanks
The reason Im doing it like this is
because Im going to store username in
the userdata field of a new
FormsAuthenticationTicket when the
user logs in.
The username of the currently logged in user is already stored in the authentication cookie. You don't need to store it once again in the UserData. And in order to retrieve it in your Razor template you could simply:
#User.Identity.Name
Obviously it is recommended to decorate the controller action rendering this view with the [Authorize] attribute to ensure that a user is authenticated before accessing it or you might get a NullReferenceException with this code.
As an alternative you could write a helper:
public static MvcHtmlString Username(this HtmlHelper htmlHelper)
{
var identity = htmlHelper.ViewContext.HttpContext.User.Identity;
if (identity.IsAuthenticated)
{
return MvcHtmlString.Create(identity.Name);
}
return MvcHtmlString.Empty;
}
which you could use like this:
#Html.Username()

How to get the current user in ASP.NET MVC

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>

Categories

Resources