Asp.net MVC4 : 컨트롤러와 작업 모두에 대한 권한 부여
컨트롤러와 작업 모두에 Authorize 속성이있는 경우 어느 것이 효과가 있습니까? 아니면 둘 다 적용됩니까?
질문 :
컨트롤러와 작업 모두에 Authorize 속성이있는 경우 어느 것이 효과가 있습니까? 양자 모두?
간단히 대답하려면 둘 다. 그 효과는 AND함께 두 가지 제한에 있습니다. 아래에서 이유를 설명하겠습니다.
세부
그래서 당신이 이것을 물을 수있는 몇 가지 이유가 있습니다.
- 메소드와 비교하여 액션에 추가 제약을 적용하는 방법을 알고 싶습니다. 예 :
- 컨트롤러 수준에서 "사용자"역할의 사용자를 적용합니다.
- 작업 수준에서 "admin"역할의 사용자를 추가로 시행합니다.
- 작업 수준에서 컨트롤러 제약 조건을 바꾸고 싶습니다.
- 작업 수준에서 컨트롤러 제약 조건을 제거하고 익명 사용자가 메서드를 사용할 수 있도록하려는 경우
MVC 버전을 지정하지 않았으므로 오늘 (MVC 4.5) 최신 버전으로 가정하겠습니다. 그러나 MVC 3을 사용하더라도 대답이 많이 바뀌지 않습니다.
[Anonymous]컨트롤러 재정의 [Authorize](케이스 3)
사례 3. 나는 커버 (의 사용이 필요하지 않습니다 [AllowAnonymous]이 대답 한 바와 같이) 모든 것을 SO 와 웹을 통해 모든 이미. 말하면 충분합니다. [AllowAnonymous]작업 을 지정 하면 컨트롤러가 작업을 수행하더라도 해당 작업을 공개 [Authorize]합니다.
당신은 또한에 의해 허가를 전체 웹 사이트의 제목을 만들 수 있습니다 글로벌 필터 사용 및 사용 AllowAnonymous공용을 할 몇 가지 행동 또는 컨트롤러를.
[Authorize] 가산 성 (케이스 1)
사례 1은 쉽습니다. 다음 컨트롤러를 예로 들어 보겠습니다.
[Authorize(Roles="user")]
public class HomeController : Controller {
public ActionResult AllUsersIndex() {
return View();
}
[Authorize(Roles = "admin")]
public ActionResult AdminUsersIndex() {
return View();
}
}
기본적 [Authorize(Roles="user")]으로 컨트롤러의 모든 작업은 "사용자"역할의 계정에서만 사용할 수 있습니다. 따라서 액세스 AllUsersIndex하려면 "사용자"역할에 있어야합니다. 그러나 액세스 AdminUsersIndex하려면 "사용자"역할과 "관리자"역할이 모두 있어야합니다. 예를 들면 :
- UserName : Bob, 역할 : user,에 액세스 할 수 없지만 액세스
AdminUsersIndex할 수 있음AllUsersIndex - UserName : Jane, 역할 : admin, 액세스 할 수 없음
AdminUsersIndex또는AllUsersIndex - 사용자 이름 : 팀, 역할 : 사용자 및 관리자, 수 액세스
AdminUsersIndex및AllUsersIndex
이것은 [Authorize]속성이 추가됨을 보여줍니다. 이것은 Users속성의 속성에 대해서도 마찬가지이며, 결합하여 Roles더 제한적으로 만들 수 있습니다 .
이 동작은 컨트롤러 및 작업 속성이 작동하는 방식 때문입니다. 속성은 함께 연결되어 순서 컨트롤러에 적용되고 조치됩니다. 첫 번째 권한이 승인을 거부하면 제어가 반환되고 작업의 속성이 호출되지 않습니다. 첫 번째가 인증을 통과하면 두 번째 것도 확인됩니다. Order(예 :)를 지정하여이 순서를 무시할 수 있습니다 [Authorize(Roles = "user", Order = 2)].
재정의 [Authorize](케이스 2)
사례 2는 더 까다 롭습니다. 위에서부터 [Authorize]속성은 컨트롤러, 액션의 순서로 검사됩니다. 사용자가 승인을받을 자격이 없음을 감지 한 첫 번째 사람이 이기고 다른 사람은 전화를받지 않습니다.
이를 해결하는 한 가지 방법은 아래와 같이 두 개의 새로운 속성을 정의하는 것입니다. 는 [OverrideAuthorize]에 연기 이외의 아무것도하지 않는다 [Authorize]; 유일한 목적은 우리가 확인할 수있는 유형을 정의하는 것입니다. 을 [DefaultAuthorize]사용하면 요청에서 호출되는 Action이 [OverrideAuthorize]. 그렇다면 우리는 액션 인증 확인을 연기하고 그렇지 않으면 컨트롤러 레벨 확인을 진행합니다.
public class DefaultAuthorizeAttribute : AuthorizeAttribute {
public override void OnAuthorization(AuthorizationContext filterContext)
{
var action = filterContext.ActionDescriptor;
if (action.IsDefined(typeof(OverrideAuthorizeAttribute), true)) return;
base.OnAuthorization(filterContext);
}
}
public class OverrideAuthorizeAttribute : AuthorizeAttribute {
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
}
}
그런 다음 다음과 같이 사용할 수 있습니다.
[DefaultAuthorize(Roles="user")]
public class HomeController : Controller {
// Available to accounts in the "user" role
public ActionResult AllUsersIndex() {
return View();
}
// Available only to accounts both in the "user" and "admin" role
[Authorize(Roles = "admin")]
public ActionResult AdminUsersIndex() {
return View();
}
// Available to accounts in the "superuser" role even if not in "user" role
[OverrideAuthorize(Roles = "superuser")]
public ActionResult SuperusersIndex() {
return View();
}
}
In the above example SuperusersIndex is available to an account that has the "superuser" role, even if it does not have the "user" role.
I would like to add something to Overriding [Authorize] (case 2)
OverrideAuthorizeAttribute and DefaultAuthorizeAttribute works fine, but I discover that you can also use OverrideAuthorizationAttribute which overrides authorization filters defined at a higher level.
[Authorize(Roles="user")]
public class HomeController : Controller {
// Available to accounts in the "user" role
public ActionResult AllUsersIndex() {
return View();
}
// Available only to accounts both in the "user" and "admin" role
[Authorize(Roles = "admin")]
public ActionResult AdminUsersIndex() {
return View();
}
// Available to accounts in the "superuser" role even if not in "user" role
[OverrideAuthorization()]
[Authorize(Roles = "superuser")]
public ActionResult SuperusersIndex() {
return View();
}
}
I made an adaptation of this answer's second case for ASP.NET Core 2.1.
The difference with ASP.NET Core's AuthorizeAttribute is that you don't have to call AuthorizeAttribute.OnAuthorization base method to proceed to normal authorization. This means that even if you don't explicitly call the base method, the base AuthorizeAttribute could still short-circuit authorization by forbidding access.
What I did is that I created a DefaultAuthorizeAttribute that does not inherit from AuthorizeAttribute, but from Attribute instead. Since the DefaultAuthorizeAttribute does not inherit from AuthorizeAttribute, I had to recreate the authorization behavior.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class DefaultAuthorizeAttribute : Attribute, IAuthorizationFilter
{
private readonly AuthorizeFilter m_authorizeFilter;
public DefaultAuthorizeAttribute(params string[] authenticationSchemes)
{
var policyBuilder = new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(authenticationSchemes)
.RequireAuthenticatedUser();
m_authorizeFilter = new AuthorizeFilter(policyBuilder.Build());
}
public void OnAuthorization(AuthorizationFilterContext filterContext)
{
if (filterContext.ActionDescriptor is ControllerActionDescriptor controllerAction
&& controllerAction.MethodInfo.GetCustomAttributes(typeof(OverrideAuthorizeAttribute), true).Any())
{
return;
}
m_authorizeFilter.OnAuthorizationAsync(filterContext).Wait();
}
}
public class OverrideAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext filterContext) { }
}
If use it on controller then, all methods of this controller will effected.
[Authorize]
public class SomeController(){
// all actions are effected
public ActionResult Action1
public ActionResult Action2
If you want to prevent for one of these actions, you can use something like this:
[Authorize]
public class SomeController(){
// all actions are effected
public ActionResult Action1
public ActionResult Action2
[AllowAnonymous]
public ActionResult Action3 // only this method is not effected...
참고URL : https://stackoverflow.com/questions/16709853/asp-net-mvc4-authorize-on-both-controller-and-action
'program story' 카테고리의 다른 글
| 더 이상 Bash 스크립팅을 사용할 수 있습니까? (0) | 2020.11.03 |
|---|---|
| Android에서 DigestUtils를 사용하여 메서드를 찾을 수 없음 (0) | 2020.11.03 |
| 작업자 스레드를 통해 ObservableCollection을 업데이트하려면 어떻게해야합니까? (0) | 2020.11.03 |
| 데이터 프레임의 레이블에서 열 인덱스 가져 오기 (0) | 2020.11.03 |
| 입력 유형 = 파일을 만드는 방법은 pdf 및 xls 만 허용해야합니다. (0) | 2020.11.03 |