我正在为我们的公司开发一个实习生Web应用程序。因为它仅在我们公司中使用,所以我们愿意实施Windows身份验证。问题是,如果我已登录,则只需打开一个带有api的新标签,即可获取数据。
我尝试添加一些cors属性以进行限制,但这对我也不起作用。
Authentication.cs:
[HttpGet]
[Route("login")]
public IHttpActionResult AuthenticateUser() {
return GetHttpActionResult(() => {
WindowsPrincipal user = RequestContext.Principal as WindowsPrincipal;
if (user != null) {
return _viewModelFactory.CreateEmployeeViewModel(_timeTrackingPersistenceManager.GetEmployeeByUserName(User.Identity.Name));
} else {
return Content(HttpStatusCode.Unauthorized, "This user cannot be logged in");
}
});
}
WebApiConfig.cs:
public static void Register(HttpConfiguration config) {
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
ConfigureCors(ref config);
}
public static void ConfigureCors(ref HttpConfiguration config) {
string frontendAddress = "";
#if DEBUG
frontendAddress = ConfigurationManager.AppSettings["frontendPathLocal"];
#elif !DEBUG
frontendAddress = ConfigurationManager.AppSettings["frontendPathServer"];
#endif
var cors = new EnableCorsAttribute(frontendAddress, "*", "*") { SupportsCredentials = true };
config.EnableCors(cors);
config.Filters.Add(new AuthorizeAttribute());
}
一切正常,除了我可以从前端以外的其他页面访问数据之外,其他一切都很正常。
答案 0 :(得分:1)
如果您直接在浏览器中访问URL,Cors将不做任何事情。如果只希望从应用程序访问,则不能进行普通的Windows身份验证,因为正如您所说的,每个人都可以访问它。
您可以做的是将前端应用程序作为特殊服务帐户运行,并仅在后端限制对此帐户的访问。
如果您的前端直接在浏览器中运行,并且您想访问API,那么我怀疑是否还有其他方法可以“保护” API。即如果用户可以使用AJAX通过您的网站进行访问,除非您添加了一些魔术令牌,否则没有什么阻止他们直接这样做的,但是由于它在浏览器中运行,因此用户始终可以直接模拟对API的完全相同的请求。
P.S。为什么用户可以直接访问API的问题?显然,他们有权执行API允许的所有操作,但是,如果您只想通过自己的GUI进行操作,则必须在服务器端提供额外的安全层,这将使用我自己如上所述的服务帐户。>