I'm having trouble restricting access to some menu items in my application because there is a type of user that will only have access to certain items and the Admin user after logging in will have access to all the content, while not logged in the menu will be hidden displaying only two items, if the admin log it will have access to the whole menu, if the ordinary user log in he will only have access to some 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, you are not looking for the admin user!
And here's how I'm doing the menu
<!DOCTYPE html>
@ ViewBag.Title - My ASP.NET Application @ Styles.Render ("~ / Content / css") @ Scripts.Render ("~ / bundles / modernizr")
@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)
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; }
}
}
Here's 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 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; }
}
}