Role user and admin not work - c#

I have i little problem in my roles, if i made login need show my name in bar menu, this work fine if i not use roles, but when i try use my roles check not work anymore. sorry my bad english
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Application_AuthenticateRequest()
{
// Check if user is logged in
if (User == null) { return; }
// Get username
string username = Context.User.Identity.Name;
// Declare array of roles
string[] roles = null;
using (Db db = new Db())
{
// Populate roles
UsuarioDTO dto = db.Usuario.FirstOrDefault(x => x.Login == username);
roles = db.RegraUsuario.Where(x => x.UsuarioId == dto.Id).Select(x => x.Regra.Nome).ToArray();
}
// Build IPrincipal object
IIdentity userIdentity = new GenericIdentity(username);
IPrincipal newUserObj = new GenericPrincipal(userIdentity, roles);
// Update Context.User
Context.User = newUserObj;
}
And in my Loyout.html
<ul class="nav navbar-nav">
#Html.Action("PaginaMenupartial", "Paginas")
#if(Request.IsAuthenticated)
{
//if user is loged show logout
<li>Sair</li>
}
else
{
if (ViewBag.Tile == "Login")
{
<li class="active">Entrar</li>
}
else
{ //if user is not loged show login
<li>Entrar</li>
}
}
// in this line below is my problem
#if (Request.IsAuthenticated && User.IsInRole("User"))
{
<li>#Html.Action("UsuarioNavPartial","Conta", new { area=""})</li>
}
</ul>
enter image description here
if i remove and leave only #if (Request.IsAuthenticated ) then work.
enter image description here
But i add #if (Request.IsAuthenticated && User.IsInRole("User")) not work, i check in all code and seems fine, some one can help me?

Make sure that the exact role is assigned to this specific user in the Database.
It has to be written exactly the same way.
I would also like to suggest, that you might want to use ENUMs or CONSTANTS as role names / symbols.
This way, a typo will not break a specific page (in case there is a typo again).
That wil ensure, that the role name is accessible and the same across the entire project.
I am assuming, that you will want to change roles later on or add / update.
This will also help with future development.

Related

ASP.net MVC - Get currently logged user role in view

I know that there are a lot of topics about this issue but I already tried several solutions and cannot make it work.
So, I am trying to verify the currently logged user role in my view. As referred in the major part of topics about this in StackOverflow, I just have to do:
#User.IsInRole("Admin")
Unfortunately this always returns false even with the "Role" column, in the AspNetUsers table, of the current logged user is populated with "Admin".
I also tried below approach but it says that "UserManager does not exist in current context".
<p>#UserManager.GetRoles(userId)</p>
One of my suspects is that I am not correctly setting the role for the user upon registration. My AspNetRoles table is correctly populated but AspNetUserRoles table is empty.
How can I troubleshoot this to find what is wrong with my application so I can use #User.IsInRole(...) instruction?
Thanks in advance for any help.
This worked perfectly fine for me.
Just make sure you've seeded the roles in the database and also the registered user is assigned a role and this should work fine.
{
<a asp-action="StudentDashboard" asp-controller="Home">Dashboard</a>
}
else
if (User.IsInRole("College"))
{
<a asp-action="CollegeDashboard" asp-controller="Home">Dashboard</a>
}
else
if (User.IsInRole("Manager"))
{
<a asp-action="AdminDashboard" asp-controller="Home">Dashboard</a>
}
else
if (User.IsInRole("Admin"))
{
<a asp-action="AdminDashboard" asp-controller="Home">Dashboard</a>
}```
i think you did not write or you write but in the wrong way this below code on global.asax :
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
{
if (FormsAuthentication.CookiesSupported == true)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
//let us take out the username now
string Email = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
string roles = string.Empty;
using (DatabaseContext entities = new DatabaseContext())
{
var user = entities.TblUsers.Where(u => u.Email == Email).FirstOrDefault().IDRole;
//here
roles = entities.TblRoles.Where(x => x.IDRole == user).FirstOrDefault().RoleName;
}
//let us extract the roles from our own custom cookie
// and here
//Let us set the Pricipal with our user specific details
e.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(Email, "Forms"), roles.Split(';'));
}
catch
{
//somehting went wrong
}
}
}
}
Have you tried adding below at the top of the view page:
#using Microsoft.AspNet.Identity
Alternatively:
#if(Roles.IsUserInRole(User.Identity.GetUserName(), "Admin"))

Return user details after they have logged in

the code below works ok, just one issue, the code confirms if user logged in is Admin or not i.e. the code checks if the user name is within the AspNetUser table and returns a Boolean true or false.
But I also need the user GarageID to be returned, the GarageID field is held within the AspNetUser table any ideas how to do this?
private bool IsUserAdmin()
{
System.Security.Principal.WindowsIdentity identity = Context.Request.LogonUserIdentity;
//Debug.WriteLine(identity.Name);
string loginName = identity.Name;
//Debug.WriteLine(loginName);
TyrescannerWebApp.IdentityModel.tyrescannerdatabaseEntities dbcontext = new TyrescannerWebApp.IdentityModel.tyrescannerdatabaseEntities();
return content.AdminUsers.Any(a => a.LoginName == loginName);
}
You should use the role provider to determine if the user is in the current role.
if (System.Web.Security.Roles.IsUserInRole(loginName, "Admin"))
{
//Do something
}
else
{
//Display unauthorized message
}

Refresh sectionTree on new user login

I have a sectiontree which varies based on the current logged in users UserType.
The thing is that if i log-out from the backoffice, and logs in with a new user with a lower UserType, the tree is not refreshed - The code is not rerun to generate the tree.
This means that the user with a non administrative UserType can access administrative areas in the section, as long as an administrator have been logged in earlier on the same solution.
How would i make the SectionTree refresh on new users login?
Update
protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
{
var sectionApi = new SectionApiController();
// Root handler
if (id == Constants.System.Root.ToInvariantString())
{
this.RootHandler();
}
else if(id.Contains("COUNTRY_") || id.Contains("LEVEL_") )
{
var section = new IdConvert(id);
if ( section.Area.Equals("country") )
{
this.FirstLevelHandler(section.Id);
}
else if (section.Area.Equals("level"))
{
this.GetLevels(section.Id);
}
// Render clubs.
this.ClubHandler();
// Render levels
this.LevelHandler();
} else if(id.Contains("CLUB_")) {
}
else if(id.Contains("SPORTS_")) {
var Country = new IdConvert(id);
this.SportsHandler(Country.Id);
}
else if (id.Contains("QUESTIONS_"))
{
var Country = new IdConvert(id);
this.QuestionsHandler(Country.Id);
}
return this._nodes;
}
The Tree works fine, it renders what it should render. But It doesent refresh upon new user login.
I'm using the following to check wether or not a person is "admin"
public static bool IsAdministrator()
{
try
{
if (_curNewUser == null)
{
GetCurrentUser();
}
if (_curNewUser.UserType.Alias == "admin")
{
return true;
}
}
catch (Exception e) { }
return false;
}
Based on a comment you are not clearing _curNewUser when user logs out and that's why you are seeing this issue.
Instead of keeping the reference to _curNewUser you should use umbraco built in UmbracoContext.Current.Security.CurrentUser directly in your UserProvider and that will fix it, something like this:
public static bool IsAdministrator()
{
var user = UmbracoContext.Current.Security.CurrentUser;
return user != null && user.UserType.Alias == "admin";
}
No need for you to hook up to logout events or anything like that.

what is used in windows app on the place of Session?

i am new to windows programming, as we use Store user's details in Session when user successfully logged into a web application and check the session in master page every time, if it will null then redirect the user to login page. I want to do the same thing in Windows application, i have created a login form: the code is written below:
private void btnLogin_Click(object sender, EventArgs e)
{
clsLogin obj = new clsLogin();
DataTable dtLogin = obj.Login_Check(txtUserName.Text.Trim(), txtPassword.Text.Trim());
if (dtLogin.Rows.Count > 0)
{
if (dtLogin.Rows[0]["result"].ToString() == "3")
{
lblMessage.Text = "Password does not matched";
}
else
if (dtLogin.Rows[0]["result"].ToString() == "2")
{
lblMessage.Text = "User does not exists";
}
else
{
Staff.Home home = new Staff.Home();
this.Hide();
home.Show();
}
}
}
}
Now what i want to do is: store the user info some where and when user click on Log off then it will destroy that session and it will open the Login form.
i know it is a very silly question, as i am new to windows programming its tough for me, please help.
Apart from the obvious issues with the code:
Direct access to rows by index
Login being done in the event handler directly
You should have separate login service and data access service
I would:
Create a login service that maintains the current logged in user details and performs the authentication itself.
Create a data access service that the login service can call to access the datastore
Then in your event handler you just need to call:
if (loginService.Authenticate(username, password))
{
// Do your UI handling here
}
then the loginService will have a .CurrentUser property for example and you can go from there.
e.g.
public class LoginService
{
private User _currentUser;
public bool Authenticate(string username, string password)
{
if (_currentUser != null)
{
Logout();
}
else
{
var user = DataAccess.Get("users").SingleOrDefault(u => u.Username = username);
if (user == null)
{
throw new Exception("No user with that username found");
}
if (password == user.Password)
{
_currentUser = user;
return true;
}
else
{
return false;
}
}
}
public User CurrentUser
{
get { return _user; }
}
}
In a Web application it is supposed that there are multiple clients connected to the single server; you should use Session to distinguish between them and to pass data to each of them "there and back again". For a desktop application this problem does not exist at all - there is exactly one user and his data is all here: you do not need some special mechanism like Session for it.
This means that you may use a number of different approaches to pass data from your form. In your example it seems more logical to pass data to your "home" form directly, either through constructor
else
{
var userData = .... (txtUserName.Text);
Staff.Home home = new Staff.Home(userData);
this.Hide();
home.Show();
}
or through a property
else
{
var userData = .... (txtUserName.Text);
Staff.Home home = new Staff.Home();
home.UserData = userData;
this.Hide();
home.Show();
}
This is only an example, there are a lot alternatives - just think about this "single user, always on site" model.

How to check what the current users role is

How do I check in C# what the current users role is, and print it to the screen.
Thanks!
You can use Roles.GetRolesForUser() method to get all the rols user belong to . use it like this;
string[] rolesuserbelongto = Roles.GetRolesForUser();
you will have all roles in string array.
you can even pass a UserName as a parameter to get the roles for that particular User like this:
string[] rolesuserbelongto = Roles.GetRolesForUser("Shekhar_Pro");
The most general method is to get an IPrinciple and then call IsInRole() on it. How you get the Principle denpends on your runtime environment. This example works well for apps running under the user's account.
Example:
static void PrintIsInAdministrators()
{
// There are many ways to get a principle... this is one.
System.Security.Principal.IPrincipal principle = System.Threading.Thread.CurrentPrincipal;
bool isInRole = principle.IsInRole("MyDomain\\MyRole");
Console.WriteLine("I {0} an Admin", isInRole ? "am" : "am not");
}
Roles.GetRolesForUser(); gave me the error The Role Manager feature has not been enabled.
If you are using ASP.NET Identity UserManager you can get it like this:
var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roles = userManager.GetRoles(User.Identity.GetUserId());
If you have changed key for user from Guid to Int for example use this code:
var roles = userManager.GetRoles(User.Identity.GetUserId<int>());
string[] userroles = Roles.GetRolesForUser(Page.User.Identity.Name);
foreach(var role in userroles)
{
Response.Write(role);
}
This is what you are looking for:
#if (Request.IsAuthenticated)
{
if (User.IsInRole("Admin"))
{
<h1> I only show this text to admin users </h1>
}
}
Note: You can check the roles defined in your AccountController.cs file, if you have one implemented.
You can use user manager for that purpose:
var userRoles = await _userManager.GetRolesAsync(user);
Not entirely sure of you question.
You can do:
this.User.IsInRole();
//loop and check whether the user is in your role.
this would correspond to a page class, so you can write the above code only inside a page and this.User returns an IPrincipal.

Categories