这是ASP.NET MVC2(RTM)System.Web.Mvc.AuthorizeAttribute类中的当前代码: -
public virtual void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (this.AuthorizeCore(filterContext.HttpContext))
{
HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
cache.SetProxyMaxAge(new TimeSpan(0L));
cache.AddValidationCallback(
new HttpCacheValidateHandler(this.CacheValidateHandler), null);
}
else
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
Run Code Online (Sandbox Code Playgroud)
所以,如果我'授权'然后做一些缓存的东西,否则抛出401 Unauthorized响应.
问题:这3条缓存线有什么作用?
欢呼:)
我正在阅读一本关于MVC2的书,并在OutputCache部分中说明:
警告在前面的"授权过滤器如何与输出缓存交互"一节中,我解释说[授权]具有特殊行为,以确保未经授权的访问者只是因为它已经被缓存而无法获取敏感信息.但是,除非您明确地阻止它,否则缓存输出仍然可以传递给与最初生成它的用户不同的授权用户.防止这种情况的一种方法是将特定内容项的访问控制实现为授权过滤器(派生自AuthorizeAttribute),而不是简单地在操作方法中内联强制授权逻辑,因为AuthorizeAttribute知道如何避免被输出缓存绕过.仔细测试以确保授权和输出缓存以您期望的方式进行交互.
这在MVC3中仍然如此吗?
如果是肯定的,有什么方法可以防止这种情况发生?(因为书中的解释太模糊了).
问候.
在我的应用程序(ASP.NET MVC 3)中,我有一个BaseController类,我的所有控制器继承,并且在该BaseController中我重写了OnActionExecuting方法以检查以确保填充了Session变量,因为我需要访问所有其他操作方法中的那个在申请中.我还有一个我定义的自定义Authorize属性,它扩展了AuthorizeAttributeClass.在该属性中,我重写OnAuthorization以检查我在BaseController OnActionExecuting方法中加载的相同Session变量,以查看是否应该允许用户继续.
BaseController
public class BaseController : Controller
{
private ISessionUserService sessionUserService;
public BaseController(ISessionUserService sessionUserService)
{
this.sessionUserService = sessionUserService;
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if (User != null && User.Identity.IsAuthenticated && this.sessionUserService.Current == null)
{
this.sessionUserService.Start(accountID, User.Identity.Name);
// If we weren't successful in reloading the SessionUser
// variable, redirect the user to the Sign In view
if (this.sessionUserService.Current == null)
{
filterContext.Result = new RedirectResult(Url.Action("SignIn", "Access", new { area = string.Empty }));
return;
}
} …Run Code Online (Sandbox Code Playgroud) c# asp.net-mvc authorization authorize-attribute actionfilterattribute
所以我发现在[Authorize]标签上有些东西让我有所启发,但没有什么可以解决我的问题.
我的场景是我有Web Api方法,我希望使用RestSharp进行集成测试.但是RestSharp正在获取我的登录页面,而不是调用的结果.
[Authorize]
public Item GetItem([FromBody] int id)
{
return service.GetItem(id);
}
Run Code Online (Sandbox Code Playgroud)
该产品使用自定义登录系统,我真正想要的是一种只为集成测试禁用[授权]徽章的方法.但是我读到你可以允许匿名用户,它会"禁用"徽章,所以在解决方案中,我有一个集成测试项目,在那个项目中我有一个App.config文件.在那个文件中,我把:
<location>
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
Run Code Online (Sandbox Code Playgroud)
但这似乎也不起作用.任何有关正在发生的事情的解释,为什么它不起作用以及如何才能使这项工作将不胜感激.
我试图设置一个Thread.CurrentPrincipal,但是没有用(也许我做错了 - 你能在代码中设置"任何东西"吗?).如果有帮助,则在httpmodule中处理身份验证.
c# integration-testing web-config authorize-attribute asp.net-web-api
我在一个方法上使用了几个Authorize Filter.
[SessionState(SessionStateBehavior.Required)]
public class AuthenticationFilterAttribute : AuthorizeAttribute {}
[HttpPost]
[AuthenticationFilter]
[ValidateAntiForgeryToken]
public void SaveProgress(string data) {}
Run Code Online (Sandbox Code Playgroud)
它们都是授权过滤器,所以我希望AuthenicationFilter在ValidateAntiForgeryToken过滤器之前运行.但ValidateAntiForgeryToken在身份验证过滤器之前运行.
我知道这可以通过Order属性来解决.但我想知道这种行为的原因,并且我想确保它以该顺序执行(在相应的过滤器类型中 - authorize,action..so on).
我试图在ASP.NET MVC中围绕Forms身份验证.MVC 5在我的具体情况下,如果重要的话.
我的应用程序不使用密码,只使用电子邮件地址作为用户名.
调试Login方法时,我可以清楚地看到模型有效,我的(自定义)MembershipProvider按预期验证用户.
然后它重定向到提供的returnUrl(为了测试的目的,我有一个AuthorizeAttributeon/Home/About).
可悲的是,我立刻被抛回到Login视野中,所以很明显我错过了整个过程的基本要素(并且,通过扩展,对整个身份验证/身份验证过程的基本洞察,我必须承认,因为我很少使用它).
Login方法:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if(ModelState.IsValid && Membership.ValidateUser(model.Email, ""))
{
FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
return RedirectToLocal(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "Email address unknown");
}
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
LoginViewModel:
public class LoginViewModel
{
[Required]
[Display(Name = "Email")]
[EmailAddress]
public string Email { get; set; }
[Display(Name = "Remember me?")] …Run Code Online (Sandbox Code Playgroud) c# asp.net asp.net-mvc forms-authentication authorize-attribute
CustomAuthorizeAttribute我的Web Api项目中定义了默认值.
config.Filters.Add(new CustomAuthorizeAttribute());
Run Code Online (Sandbox Code Playgroud)
但是我有一个特殊的控制器,我想使用一个SpecialAuthorizeAttribute.
[SpecialAuthorize]
public class MySpecialController : ApiController
Run Code Online (Sandbox Code Playgroud)
在Asp.Net vNext中,我们有一个新属性来覆盖默认过滤器,但是如何让它在Web Api 2中工作呢?
编辑1:
一种可能的(但不是理想的)解决方案是使CustomAuthorizeAttribute检查Controller或Action范围内是否有另一个AuthorizeAttribute.在我的情况下,我只有SpecialAuthorizeAttribute所以:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<SpecialAuthorizeAttribute>().Any() || actionContext.ActionDescriptor.GetCustomAttributes<SpecialAuthorizeAttribute>().Any())
{
return;
}
base.OnAuthorization(actionContext);
}
public override System.Threading.Tasks.Task OnAuthorizationAsync(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
{
return base.OnAuthorizationAsync(actionContext, cancellationToken);
}
}
Run Code Online (Sandbox Code Playgroud) 在我要做的核心工作中,我想要的是如果您访问www.mysite.com/admin/index,我想呈现一个局部视图,该视图显示附加了模型的“未经授权”。我真的不希望该网站显示www.mysite.com/error/unauthorized/,因为当有人真的打电话给我并告诉我在“ / error / unauthorized”页面上出现错误时,这不是很有用说“我在/ admin / index页上遇到未经授权的错误”。
我有从AuthorizeAttribute继承的CustomAuthorizeAttribute,工作正常,除了重定向之外。
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// returns boolean if it is good or not
}
Run Code Online (Sandbox Code Playgroud)
然后,我有了HandleUnauthorizedRequest,这是我需要传递部分模型的地方:
if (context.RequestContext.HttpContext.User.Identity.IsAuthenticated)
{
base.HandleUnauthorizedRequest(context);
}
else
{
var viewResult = new PartialViewResult();
viewResult.ViewName = "~/Views/Shared/Unauthorized.cshtml";
viewResult.Model = new ViewModels.Unauthorized() { MyData = "My Data" }; // obviously can't do this as it is read-only
context.Result = viewResult;
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以删除viewResult.Model并只使用ViewBag,但我真的希望有某种方法可以将模型传递给Partial
c# authorize-attribute asp.net-mvc-partialview asp.net-mvc-5
我想向我的 .NET Core API 添加授权。假设我有一个具有以下操作的 PersonController:
GetPerson(根据 id 检索 Person)
PostPerson(添加新人员)
DeletePerson(删除一个人)
[Route("[controller]")]
[ApiController]
public class PersonController : ControllerBase
{
[HttpGet("{id}")]
public async Task<ActionResult<PersonModel>> GetPerson(int id)
{
//
}
[HttpPost]
public async Task<ActionResult<PersonModel>> PostPerson(PersonModel model)
{
//
}
[HttpDelete("{id}")]
public async Task<ActionResult> DeletePerson(int id)
{
//
}
}
Run Code Online (Sandbox Code Playgroud)
对于这个例子,我将使用两个角色。“ SuperAdmin ”应该能够执行所有操作,“ PersonReader ”应该只能执行 GetPerson 调用。尝试将 PostPerson 或 DeletePerson 作为 PersonReader 应该会失败。
我创建了以下授权策略:
options.AddPolicy("SuperAdmin", policy =>
policy.RequireAuthenticatedUser()
.RequireRole("SuperAdmin")
);
options.AddPolicy("PersonReader", policy =>
policy.RequireAuthenticatedUser()
.RequireRole("PersonReader")
);
Run Code Online (Sandbox Code Playgroud)
但现在我想将这些策略绑定到控制器操作,说明需要哪些策略才能执行控制器操作。我知道这可以通过这样的authorizationAttribute来完成:[Authorize(Policy="X"]但我希望能够在不使用AuthorizationAttributes的情况下做到这一点。
为什么我无法使用[授权]属性?
我不会讲太多细节,但是控制器的源代码是生成的。这意味着一旦再次生成,所有手动更改都将被覆盖。因此,授权不应该在控制器中。
在 …
我在 .Net Core 3.1 Api 中使用基于角色的身份验证。我正在使用 Jwt 令牌和用户声明。基于角色的身份验证工作正常。但在某些控制器中,我想确保用户获得他/她自己的数据。因为如果一名员工在请求中发送其他员工 ID,他/她可以获得该资源数据,我不希望这样。
我有电子邮件、ID 和令牌中的角色以及其他一些数据。
我想要的是类似 [Authorize(Roles="Employee", Id={userId})]
[HttpGet("getUserInventory")]
//[Authorize(Roles="Employee", Claims.Id={userId})]
public IActionResult getUserInventory([FromQuery] int userId)
{
var inventories = _userInventoryExportService.GetGlobalInventory(userId);
if(inventories.Success)
{
return Ok(inventories.Data);
}
return BadRequest(inventories.Message);
}
Run Code Online (Sandbox Code Playgroud) asp.net authorize-attribute jwt asp.net-core-webapi asp.net-core-3.1
c# ×8
asp.net-mvc ×5
asp.net ×2
asp.net-core ×1
caching ×1
filter ×1
jwt ×1
outputcache ×1
web-config ×1