【发布时间】:2019-05-08 15:14:04
【问题描述】:
我正在构建一个 MVC 应用程序,该应用程序在同一个项目中具有标准控制器和 APIController。所有功能都可以正常工作,我可以调用 Controllers 或 APIControllers 没问题。
我想要实现的是确保如果您从外部调用 /api/products 它不应该是可访问的,只有授权用户可以调用它。
我向我的 api 控制器添加了 Authorize 属性,我仍然可以调用它并从像 Postman 这样的客户端应用程序中获取结果。你可以在下面看到我的代码。
[Authorize] //System.Web.Http
public class ProductsController : ApiController
[HttpGet]
public IHttpActionResult Get()
这是我的 Startup.Auth.cs 文件中的内容。
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
如果我注释掉这段代码,我会从 APIController 得到正确的响应,但我也无法登录。
<Error>
<Message>Authorization has been denied for this request.</Message>
</Error>
不知道我错过了什么。据我了解,我不需要为我的 API 控制器创建自定义过滤器,我应该能够使用内置的授权功能。如果您需要更多详细信息或代码示例,请告诉我。
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-4 asp.net-web-api postman asp.net-authorization