【发布时间】:2020-12-21 16:59:40
【问题描述】:
我在为 Web APi 使用基于角色的身份验证时遇到问题。
我有一个控制器类,其中控制器有一个名为 Myauthorize 的自定义授权属性。 我在控制器中有一个方法,只能通过管理员访问权限访问。 但是同样的方法也一直在使用 QA 访问权限进行调用。 有人可以帮忙解决以下问题吗?
请在下面找到代码。 控制器:
namespace Hosiptal.Controllers.office
{
[MyAuthorize(Constants.Roles.Admin)]
public class UserRolesController : ApiController
{
private readonly IRepository<EntityModels.Role> rolesRepository;
public UserRolesController(IRepository<EntityModels.Role> rolesRepository)
{
this.rolesRepository = rolesRepository;
}
// GET: Users
[HttpGet]
[Route("")]
public IEnumerable<Role> GetAll()
{
return this.rolesRepository.GetAll()
.ToArray()
.Select(r => Mapper.Current.Get<Role>(r));
}
}
}
MyAuthorize 已跟进。
namespace Hospital.Web.Filters.WebApi
{
public class MyAuthorize: AuthorizeAttribute
{
private readonly string[] allowedroles;
private static IUserProfileRepository UserProfileRepository
{
get { return IoC.Current.Resolve<IUserProfileRepository>(); }
}
public MyAuthorize(params string[] roles)
{
this.allowedroles = roles;
}
public override Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken
cancellationToken)
{
var claimsIdentity = actionContext.RequestContext.Principal.Identity as ClaimsIdentity;
var alias = claimsIdentity.Name.Split('@')[0];
if (alias == null)
{
throw new ArgumentNullException(nameof(actionContext));
}
user(alias);
return base.OnAuthorizationAsync(actionContext, cancellationToken);
}
public static GenericPrincipal user(string userName)
{
userName = userName.ToUpper();
var userProfile = UserProfileRepository.Get(userName) ?? new UserProfile()
{
UserName = userName,
Roles = new List<Role>(),
FirstLoginDateUtc = DateTime.UtcNow
};
return CreatePrincipal(userProfile);
}
public static GenericPrincipal CreatePrincipal(UserProfile user)
{
var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name,
user.UserName) }, "Custom");
return new GenericPrincipal(identity, user.Roles.Select(i =>
i.Name).ToArray());
}
}
}
如何根据访问级别在此处限制用户?
【问题讨论】:
-
如果您没有将调用的值分配给任何东西,为什么还要使用
user(alias);创建用户? -
你有它的方式,你还不如使用
[Authorize(Roles = "role1, role2, role3")] -
@insane_developer 是的,我还有其他可以通过多个角色访问的控制器。
-
@JuanR ,对不起,我已经添加了 user(alias) 方法的代码。请您检查一次。我不了解这里的角色机制。你能帮忙吗?
-
@Naurtosan 你试过
[Authorize(Constants.Roles.Admin)]吗?那应该做你需要的。我认为除了检查管理员角色之外,您还需要一些东西,这就是这样做的。
标签: c# authentication asp.net-mvc-4 asp.net-web-api rbac