【发布时间】:2016-01-25 13:35:52
【问题描述】:
我的网站(带有实体框架的 ASP.NET MVC5)使用 Windows 身份验证系统。它非常有用,使我能够通过搜索 Active Directory 来获取有关用户的更多信息。我可以用电子邮件等信息自动填写表单字段...
Web.config:
[...]
<authentication mode="Windows" />
<authorization>
<deny users="?" />
</authorization>
[...]
我有一个 Powershell 脚本(执行另一项工作),它必须访问网站的一个页面才能发送一些信息。我需要提供对脚本的访问权限,无需任何身份验证(仅为此操作/页面关闭 Windows 身份验证)。我一开始使用了 AllowAnonymous 属性,它没有效果。
我的控制器中的操作:
[AllowAnonymous]
public ActionResult ReceiveData(string scriptVersion, string content)
{
try
{
if (scriptVersion != null && content != null)
{
HttpUtility.UrlDecode(content);
Xxxxx.UpdatexxxxxxServer(content); // I just replaced the name of my project
return new HttpStatusCodeResult(200, "OK");
}
return new HttpStatusCodeResult(403, "You're not allowed to do this.");
}
catch(Exception e)
{
return new HttpStatusCodeResult(400, "Unable to execute this request on the DB. Detailed error: " + e.Message);
}
}
Powershell 脚本(仅供参考,本题无需了解):
$url = "http://localhost:3349/Xxxxxx/ReceiveData"
$parameters = "scriptVersion=2&content=$([System.Web.HttpUtility]::UrlEncode($(Get-Content "$scriptFile")))"
$http_request = New-Object -ComObject Msxml2.XMLHTTP
$http_request.open('POST', $url, $false)
$http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
$http_request.setRequestHeader("Content-length", $parameters.length)
$http_request.setRequestHeader("Connection", "close")
$http_request.send($parameters)
当我的脚本到达发送方法时,他要求我提供凭据,我不想每次都提供凭据(而且我不想将我的凭据放在脚本中)。这就是为什么我希望在此操作上禁用 Windows 身份验证。
我进行了一些研究,试图找到任何可行的解决方案。我看到了这个主题:MVC 5.0 [AllowAnonymous] and the new IAuthenticationFilter 添加新过滤器后,AllowAnonymous 属性似乎在 MVC5 中不起作用。这就是我尝试添加自定义过滤器的原因:
public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
var user = filterContext.HttpContext.User;
if (user == null || !user.Identity.IsAuthenticated)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
}
我在 FilterConfig 上添加了它,并将 CustomAuthenticationAttribute 放在我的 Action ReceiveData 上。 没有更好的结果...所有操作都在此过滤器中进行,但我无法在我的操作上禁用 Windows 身份验证。
我修改后的操作:
[AllowAnonymous]
[CustomAuthenticationAttribute]
public ActionResult ReceiveData(string scriptVersion, string content) {
[...]
}
我不是专家,如果您能帮我找到解决方案并理解它,那就太好了。在此先感谢并为英语错误深表歉意,这不是我的母语。
【问题讨论】:
-
[AllowAnonymous]应该可以工作您是否将任何 AuthorizeAttribute 放在控制器级别?? -
@too_cool 我想你的意思是
AuthorizeAttribute? -
@DavidG 谢谢指出!!..
-
@too_cool 是的,我愿意,但似乎并没有更好。我通过 AllowAnonymousAttribute 了解了 MVC4 和 5 之间的区别:bartwullems.blogspot.de/2015/06/… 但是公开的解决方案对我不起作用。
标签: c# asp.net asp.net-mvc powershell authentication