1
I am having difficulty in being able to restrict access to some menu items of my application, because there is a type of user who will have access only to certain items and the Admin user after logging in will have access to all content, that is, while not logged in the menu will be hidden displaying only two items, if the admin logs in it will have access to the entire menu, if the common user logs in it will have access only to a few menu items. Show me an example of how to do this, because even following the microsoft documentation I could not do this implementation on my system!
At the moment my problem is in this line of code:
public bool IsAdminUser()
{
if (User.Identity.IsAuthenticated)
{
var user = User.Identity;
ApplicationDbContext context = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore<ApplicationUser>(context));
var s = UserManager.GetRoles(user.GetUserId());
if (s[0].ToString() == "Admin")
{
return true;
}
else
{
return false;
}
}
return false;
}
Now the problem is here, not seeking admin user!
And here’s how I’m doing the menu
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - Meu Aplicativo ASP.NET</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="@Url.Action("Index", "Home")" class="navbar-brand">
<img src="http://www.ebasesistemas.com.br/assets/img/logo.png" title="title" alt="additional title" />
</a>
</div>
<div class="navbar-collapse collapse">
@if (ViewBag.displayMenu == "Yes")
{
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Início", "Index", "Home")</li>
<li>@Html.ActionLink("Cadastros", "Cadastros", "Home")</li><!---adm-->
<li>@Html.ActionLink("Relatorios", "Relatorios", "Home")</li><!--adm-->
<li>@Html.ActionLink("Contato", "Contact", "Home")</li><!--apenas logado-->
<li>@Html.ActionLink("Sobre", "About", "Home")</li><!--todos-->
</ul>
}
else
{
<h2> Seja bem vindo <strong>@ViewBag.Name</strong> :) .Você é um usuário com acesso premium!! </h2>
}
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="body-content">
@RenderBody()
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
here are the three models:
AccountViewModels
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace PaginaWeb.Models
{
public class ExternalLoginConfirmationViewModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
}
public class ExternalLoginListViewModel
{
public string ReturnUrl { get; set; }
}
public class SendCodeViewModel
{
public string SelectedProvider { get; set; }
public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; }
public string ReturnUrl { get; set; }
public bool RememberMe { get; set; }
}
public class VerifyCodeViewModel
{
[Required]
public string Provider { get; set; }
[Required]
[Display(Name = "Código")]
public string Code { get; set; }
public string ReturnUrl { get; set; }
[Display(Name = "Lembrar deste navegador?")]
public bool RememberBrowser { get; set; }
public bool RememberMe { get; set; }
}
public class ForgotViewModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
}
public class LoginViewModel
{
[Required]
[Display(Name = "Email")]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Senha")]
public string Password { get; set; }
[Display(Name = "Lembrar-me?")]
public bool RememberMe { get; set; }
}
public class RegisterViewModel
{
[Required]
[Display(Name = "Nome da Empresa")]
public string nomeEmpresa
{
get; set;
}
[Required]
[Display(Name = "Telefone")]
public string telefone
{
get; set;
}
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "O/A {0} deve ter no mínimo {2} caracteres.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Senha")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirmar Senha")]
[Compare("Password", ErrorMessage = "A senha e a senha de confirmação não correspondem.")]
public string ConfirmPassword { get; set; }
}
public class ResetPasswordViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "O/A {0} deve ter no mínimo {2} caracteres.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Senha")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirmar senha")]
[Compare("Password", ErrorMessage = "A senha e a senha de confirmação não coincidem.")]
public string ConfirmPassword { get; set; }
public string Code { get; set; }
}
public class ForgotPasswordViewModel
{
[Required]
[EmailAddress]
[Display(Name = "E-mail")]
public string Email { get; set; }
}
}
This is Identitymodels:
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace PaginaWeb.Models
{
// É possível adicionar dados do perfil do usuário adicionando mais propriedades na sua classe ApplicationUser, visite https://go.microsoft.com/fwlink/?LinkID=317594 para obter mais informações.
public class ApplicationUser : IdentityUser
{
public string nomeEmpresa
{
get; set;
}
public string telefone
{
get; set;
}
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Observe que o authenticationType deve corresponder àquele definido em CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Adicionar declarações de usuário personalizado aqui
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
Here Manageviewmodels:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
namespace PaginaWeb.Models
{
public class IndexViewModel
{
public bool HasPassword { get; set; }
public IList<UserLoginInfo> Logins { get; set; }
public string PhoneNumber { get; set; }
public bool TwoFactor { get; set; }
public bool BrowserRemembered { get; set; }
}
public class ManageLoginsViewModel
{
public IList<UserLoginInfo> CurrentLogins { get; set; }
public IList<AuthenticationDescription> OtherLogins { get; set; }
}
public class FactorViewModel
{
public string Purpose { get; set; }
}
public class SetPasswordViewModel
{
[Required]
[StringLength(100, ErrorMessage = "{0} deve ter pelo menos {2} caracteres.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Nova senha")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirmar nova senha")]
[Compare("NewPassword", ErrorMessage = "A nova senha e a senha de confirmação não correspondem.")]
public string ConfirmPassword { get; set; }
}
public class ChangePasswordViewModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Senha atual")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "{0} deve ter pelo menos {2} caracteres.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Nova senha")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirmar nova senha")]
[Compare("NewPassword", ErrorMessage = "A nova senha e a senha de confirmação não correspondem.")]
public string ConfirmPassword { get; set; }
}
public class AddPhoneNumberViewModel
{
[Required]
[Phone]
[Display(Name = "Número de telefone")]
public string Number { get; set; }
}
public class VerifyPhoneNumberViewModel
{
[Required]
[Display(Name = "Código")]
public string Code { get; set; }
[Required]
[Phone]
[Display(Name = "Número de telefone")]
public string PhoneNumber { get; set; }
}
public class ConfigureTwoFactorViewModel
{
public string SelectedProvider { get; set; }
public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; }
}
}
What code do you currently have?
– PauloHDSousa
Man I’ve done a lot of things, it’s even hard to show the codes here
– WPfan
Have the code with the MENU items I believe you will have to do a check on that.
– PauloHDSousa
@Paulohdsousa managed to solve the problem of the line of code that I put before, now the problem is in this part ai... You can not make an example of that there for me to base not???? I knew to do it using sitemap, more visual studio 2017 n allows more this!
– WPfan
How you are doing the MENU, is a PARTIAL VIEW with the links or you do on the server?
– PauloHDSousa
I will edit the question and put as to doing the menu, it is in the partial layout view!
– WPfan