Coding Platform: ASP.NET 4.0 Webforms with C#
I have two roles admin and member.
In my application, admin can manipulate most of the member data.
I know that in forms authentication a user can be unlocked like,
MembershipUser user = Membership.GetUser(clickeduserName);
user.UnlockUser();
Membership.UpdateUser(user);
My questions are,
How to lock a user in forms authentication?
Why is MembershipUser.IsLockedOut
Property set as ReadOnly?
Is it not the right way to LockOut
people as an administrator?
There are a few options discussed here: http://forums.asp.net/t/1435151.aspx
They vary from using IsApproved (settable) instead of IsLockedOut to mucking with the underlying SQL database to set the lockout flag.
You can make it lock the user (set .IsLockedOut to true) by doing the following:
MembershipUser user = Membership.GetUser("UserToLock");
for (int i = 0; i < Membership.MaxInvalidPasswordAttempts; i++)
{
Membership.ValidateUser(user.UserName, "Not the right password");
}
Excerpt from MSDN:
Normally, User's are LockedOut automatically when the MaxInvalidPasswordAttempts is reached within the PasswordAttemptWindow.
Users can also be locked out if you use the GetPassword or ResetPassword overload that accepts a password answer and the number of bad answers entered by the user reaches the value of Membership.MaxInvalidPasswordAttempts within the Membership.PasswordAttemptWindow.
A workaround could be to use IsApproved property like this:
MembershipUser user = Membership.GetUser();
user.IsApproved = false;
Membership.UpdateUser(user);
Related
I need some help with examples how to use Credential of a current user running application.
So in windows 7 you can run application using user loged in by simply running application or you can use "Run as a different User" option and run it as another user.
In my Active Directory I have 2 account Domain User and one with Domain Admin rights. I'm login Windows as a Domain User and when I need I'm using "Run as a different User" to launch some task as a Domain Admin.
So the task is to get my Credential and use it to perform some task, lets say rename active directory user name.
Best way to do this as I can see is to ask user running application to enter Domain Admin credential on then start application and use them for various task. Of course I can easily run application with "Run as a different User" but I still need to get this credential and use them.
I've searched through the web and I can't find this, all i could find is using credential for a web auth.
If you can show me some examples how to:
1) Ask user for a Admin user credential ( i can leave without this )
2) Get and use credentials of a user running application
I don't want to know password I know I can't. Don't really want to add to a WPF form password box I prefer to use windows API to handle this i've already entered user name and password using "Run as a different User".
PS: I sorry if this topic exists :( I guess I'm bad at creating correct search requests.
ADDED: to be more clear what I need. In powershell it will look like this:
# This Asks user to enter credentials
$cred = Get-Credential;
# this checks if I have rights to use them.
Get-ADDomain “DOMAIN” –Server “Domain.com” –Credential $cred;
Of course it's simplified as hell though the point is that I can use credentials user entered when ever it's needed.
The equivalent C# to your Get-ADDomain is quite simple, it is just
public void PerformSomeActionAsAdmin(string adminUsername, string adminPassword)
{
//Null causes the constructor to connect to the current domain the machine is on.
// |
// V
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, null, adminUsername, adminPassword))
{
//do something here with ctx, the operations will be performed as whoever's username and password you passed in.
}
}
if you don't want to connect to the current domain and instead want to connect to Domain.com then replace the null with the appropriate string.
EDIT: if you want to use secure strings you can't use System.DirectoryServices.AccountManagement.PrincipalContext, you will need to go with the lower level calls in System.DirectoryServices.Protocols. Doing this process is quite complex, here is a link to the MSDN article "Introduction to System.DirectoryServices.Protocols (S.DS.P)" explaining how to use it. It is a big complex read and honestly I don't think it is worth it to be able to use encrypted strings.
public void PerformSomeActionAsAdmin(NetworkCredential adminCredential)
{
using(LdapConnection connection = new LdapConnection("fabrikam.com", adminCredential))
{
// MAGIC
}
}
Do you want to check if the current user is a doman admin? start by looking at his code, it should help you get started identifying what AD groups the current user is in. This will give you a list of strings that are each group's name the current user belongs to. Then you can check that list against whatever AD group you are trying to check for. Replace YourDomain with your domain name:
WindowsIdentity wi = WindowIdentity.GetCurrent();
List<string> result = new List<string>();
foreach (IdentityReference group in wi.Groups)
{
result.Add(group.Translate(typeof(NTAccount)).ToString().Replace("YourDomain\\", String.Empty));
}
Since i'm not quite sure what you're trying to do, this also might be helpful. You'd have to get the user name and password from a textobx, password box etc. This could be used for an "override" to use, for example, a manager's credentials etc. to do something the current user wasn't allowed to do because of AD group membership etc.
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YourDomain"))
{
if (UserName.Contains("YourDomain\\"))
{
UserName = UserName.Replace("YourDomain\\", String.Empty);
}
//validate the credentials
bool IsValid = pc.ValidateCredentials(UserName, Password);
}
User is logged in and wants to do something major and I want them to re-enter their password so I can make sure that they are the user that is logged in.
How can I confirm that this password is for the account holder?
Would be happy to know how to do it via ASP.NET Identity or how to set up a stored proc to go against the AspNetUsers table or how to do it via Entity Framework.
How can I confirm that this password is for the account holder?
how to do it via ASP.NET Identity
To reverify the password of currently logged in user, provide the user VerifyView to enter password and use the following method to check if the user exists.
var user = await UserManager.FindAsync(User.Identity.Name,VerifyViewModel.Password)
If the user is found, the current request is the same from the account holder.
Membership.ValidateUser is from earlier version of Membership framework, not from ASP.NET Identity.
You can also use UserManager.CheckPassword() extension function:
UserManagerExtensions.CheckPassword Method
string id = User.Identity.GetUserId();
var user = UserManager.FindById(id);
if(!UserManager.CheckPassword(user, model.Password))
{
ModelState.AddModelError("Password", "Incorrect password.");
}
With Identity framework you never want to hit the database directly. Always use the API provided. The database structure has changed several times in the past few years, so introducing dependencies (e.g. on a data context) is adding work for no reason.
For async usage, see the answer already provided by jd4u.
For synchronously identifying that the password matches the current user, you need to first include:
using Microsoft.AspNet.Identity;
as this brings in a number of synchronous extension methods for identity framework.
You can then check with Find on the UserManager like this:
var user = UserManager.Find(User.Identity.Name, password);
if (user != null)
{
// It is them!
}
If the user is not null, then you have a match of password and current username.
You can use UserManager to do that:
if(UserManager.PasswordHasher.VerifyHashedPassword("hashedPassword", "password")
!= PasswordVerificationResult.Failed)
{
// password is correct
}
For more information see the link:
How to check password manually in Asp.Net identity 2?
I expected this code:
WindowsPrincipal principal = new WindowsPrincipal( WindowsIdentity.GetCurrent() );
public bool UserHasAdminRights( WindowsPrincipal principal, WindowsBuiltInRole role )
{
bool isAdmin;
// get the role information of the current user
if ( principal.IsInRole( role ) )
{
isAdmin = true;
}
else
{
isAdmin = false;
}
return isAdmin;
}
to return true when a user is in the Built-in Administrators group.
HOWEVER
MSDN for IsInRole states:
In Windows Vista, User Account Control (UAC) determines the privileges
of a user. If you are a member of the Built-in Administrators group,
you are assigned two run-time access tokens: a standard user access
token and an administrator access token. By default, you are in the
standard user role. When you attempt to perform a task that requires
administrative privileges, you can dynamically elevate your role by
using the Consent dialog box. The code that executes the IsInRole
method does not display the Consent dialog box. The code returns false
if you are in the standard user role, even if you are in the Built-in
Administrators group. You can elevate your privileges before you
execute the code by right-clicking the application icon and indicating
that you want to run as an administrator.
Question is how do I modify this code so that it returns true, if the user is in the built-in Admin group, WITHOUT requiring the user to elevate permissions during/before runtime?
Since I can't neatly post code in comments, like I can here, let me just suggest some pseudo code
var user = Windows.GetThisUser( me ); //current method (I said pseudo code)
function CheckIfImAdmin( user ) .... //current method
proposed method:
var administrativeUsers = Windows.GetUsersInRole( "admin" ); //use a SID here, much more reliable
foreach(user in administrativeUsers){
if (user == me) return true;
return false;
}
While this may look the same, it's not. Instead of querying the user to see if it's currently in a given role (non-escalated aren't) I'm focusing on who the administrators are and then asking if that group contains the user I want, namely the current user.
I was looking for the efficient way to track the logged users when using asp.net login control
if (!IsPostBack)
{
if (Membership.GetUser() != null)
{
var user = Membership.GetUser();
Session["user"] = user;
}
else
{
Session["user"] = "";
}
}
Any suggestions will be appreciated
why all this pain and why do you try to save it in the Session (which is user specific and not application specific), when you can simply get it from this object:
HttpContext.Current.User
check this one for details: How to get current user who's accessing an ASP.NET application?
You can get the user identity (if you're using asp.net forms membership) through:
HttpContext.Current.User.Identity.Name
On logging in, if the user is valid, use:
FormsAuthentication.SetAuthCookie(login.UserName, false);
rather than relying on Session to store user logged in state.
You can then check if a user is logged in by:
User.Identity.IsAuthenticated
And get their username doing:
User.Identity.Name
You can just simply use
User.Identity.Name
You can use User.Identity.Name
Please have a look at HttpContext.User Property
I'm currently working on a website that requires me to enable validation for different accounts.
I have 2 accounts - Admin and User.
My Admin account is able to view all the functions available in the website, but the User is only allowed a few functions.
What I have in mind is to disable the visibility of a button - btnUpload.
Below are the codes that I've came up with so far.
Mp.Mp login = new Mp.Mp();
bool result = login.AuthenticateUser(tbxUsername.Text, tbxPassword.Text);
if (result == true) {
Session.Add("Session_name", tbxUsername.Text);
//Session["Username"] = tbxUsername.Text;
Response.Redirect("Index.aspx");
}
I need help with the visibility of buttons to ensure that btnUpload appears only to Admin and not User.
May be you want some thing like this
if(Session["Session_name"] == "admin")
{
btnUpload.Visible = true;
}
else
{
btnUpload.Visible = false;
}
You have RollName AND RollID For Identify your user by that roleid.
You just need to check rollID at time of user login and store your user rollid in session and then check this rollid in whatever page where you need to check constrain regarding user role.
try
btnUpload.Visible = Session ["Session_name"] == "Admin";
How you are going to decide if the user is admin or a regular user? In simplistic scenario, your user data may have a flag that indicates whether user is an admin or not. Flexible approaches uses role based security - so if the user is member of particular role then he get access to certain features. So in such system, you can have a access right (or feature) for admin privileges and admin role will have this feature. In integrated authentication schemes, you can also use on windows groups or active directory groups as a security role. ASP.NET has good support for role based security (see this, this and this). Regardless of a implementation, once you decide is user is admin or not, controlling UI is very simple thing.