[英]Authorization has been denied for this request. Always
I've already created a MVC webApi project and now I want to use Authentication and Authorization. 我已经创建了一个MVC webApi项目,现在我想使用身份验证和授权。 I think I already implemented this security but for some reason something goes bad, when I write my credentials and I try to call some webApi methods the message "Authorization has been denied for this request" is shown. 我认为我已经实现了这种安全性,但由于某些原因,一些事情变得糟糕,当我编写我的凭据并尝试调用一些webApi方法时,会显示消息“此请求已被拒绝授权”。
This is the code that I implemented. 这是我实现的代码。
WebApiConfig: WebApiConfig:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Filters.Add(new AuthorizeAttribute());
}
Routing Config: 路由配置:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Routing", action = "LogIn", id = UrlParameter.Optional }
);
}
Controller: 控制器:
public class RoutingController : Controller
{
//
// GET: /Routing/
public ActionResult Index()
{
return View();
}
public ActionResult Projects()
{
return View();
}
public ActionResult Users()
{
return View();
}
public ActionResult LogIn()
{
return View();
}
[HttpPost]
public JsonResult LogInPost(string userName, string password)
{
User user = new User();
RoleByUser rByU = new RoleByUser();
password = UserController.EncriptPassword(password);
string url = string.Empty;
var checkUser = user.Get(userName);
var userExists = (from userInList in checkUser where userInList.UserName == userName && userInList.Password == password select userInList).FirstOrDefault();
if(userExists!= null)
{
var roles = (from roleByUser in userExists.listOfRole select roleByUser.RoleName.Trim()).ToArray();
IPrincipal principal = new GenericPrincipal(
new GenericIdentity(userExists.UserName), roles);
SetPrincipal(principal);
url = "Routing/Users";
}
return Json(url);
}
private void SetPrincipal(IPrincipal principal)
{
Thread.CurrentPrincipal = principal;
if (System.Web.HttpContext.Current != null)
{
System.Web.HttpContext.Current.User = principal;
}
}
}
HTML: HTML:
<link href="~/css/Style.css" rel="stylesheet" type="text/css" />
<div class="container">
<div class="card card-container">
<img id="STK" class="profile-img-card" src="Images/Softtek.png" />
<p id="profile-name" class="profile-name-card"></p>
<form class="form-signin">
<span id="reauth-email" class="reauth-email"></span>
<input type="text" id="txtUserName" class="form-control" placeholder="Email address" required autofocus />
<input type="password" id="txtPassword" class="form-control" placeholder="Password" required />
<div id="remember" class="checkbox">
<label>
<input type="checkbox" value="remember-me" /> Remember me
</label>
</div>
@*<button id="btnLogIn" class="btn btn-lg btn-primary btn-block btn-signin" >Sing In</button>*@
</form><!-- /form -->
<button id="btnLogIn" class="btn btn-lg btn-primary">Sing In</button>
<a href="#" class="forgot-password">
Forgot the password?
</a>
</div><!-- /card-container -->
</div><!-- /container -->
JS: JS:
$(document).ready(function () { $('#btnLogIn').click(logIn); }); $(document).ready(function(){$('#btnLogIn')。click(logIn);});
function logIn() {
$.ajax({
type: "POST",
url: "http://localhost:21294/Routing/LogInPost",
dataType: "json",
data: { userName: $('#txtUserName').val(), password: $('#txtPassword').val() },
success: function (data) {
if(data!= "" && data!= undefined && data!= null)
window.location.href = data;
},
error: function (err, e, error) {
toastr.error('Error')
}
});
You should add the [AllowAnonymous]
attribute to your Controller's LogInPost
您应该将[AllowAnonymous]
属性添加到Controller的LogInPost
When you added the AuthorizeAttribute
to your filters, it caused your controllers to assume they required authorization by default for all actions, including the one used to login. 将AuthorizeAttribute
添加到过滤器时,会导致控制器假定所有操作(包括用于登录的操作)默认需要授权。
Are you doing Windows Authentication? 你在做Windows身份验证吗? are you getting "Access Denied" error? 你收到“拒绝访问”错误?
At times IISEXpress and IIS does some trick and to overcome of that I have hosted the site in local iis (inetmgr), enable Authentication (windows if applicable) and now run it. 有时IISEXpress和IIS做了一些技巧并且克服了我在本地iis(inetmgr)中托管该站点的情况,启用身份验证(如果适用,则启用Windows)并立即运行它。
PS not all machines have IIS server installed by default so if inetmgr doesn't work then you have to install it from Control Panel --> Windows Features --> select all the features of IIS and ASP .NET PS并非所有机器都默认安装了IIS服务器,因此如果inetmgr不起作用,则必须从控制面板 - > Windows功能 - >选择IIS和ASP .NET的所有功能
Hope this will help. 希望这会有所帮助。
Sorry for such a late response - I found your question because, having switched from IIS-hosted web api to a self-hosted web api, I've just started experiencing the same problem. 很抱歉这么晚的回复 - 我找到了你的问题,因为,从IIS托管的网络API切换到自托管的网络API,我刚开始遇到同样的问题。
In my case, the problem was caused by how I was initialising Thread.CurrentPrincipal. 在我的情况下,问题是由我如何初始化Thread.CurrentPrincipal引起的。 Some background: 一些背景:
Previously, I was assigning this ClaimsPrincipal instance to Thread.CurrentPrincipal before passing the message onward to the remaining message handlers in the pipeline. 以前,我将此ClaimsPrincipal实例分配给Thread.CurrentPrincipal,然后将消息传递给管道中的其余消息处理程序。 However, the solution for me was to use instead the Principal member on the HttpRequestContext instance that belongs to the HttpRequestMessage instance that is passed to SendAsync. 但是,我的解决方案是在HttpRequestContext实例上使用Principal成员,该实例属于传递给SendAsync的HttpRequestMessage实例。 Hence (in F#), 因此(在F#中),
override this.SendAsync(request : HttpRequestMessage, cancellationToken : CancellationToken) =
// Do some user validation here first
// .. then setup the claims (method details omitted)
let principal = BuildClaimsPrincipal
// Assign to Principal on HttpRequestContext
let requestContext = request.GetRequestContext
requestContext.Principal <- principal
// Rest of method omitted...
Hope this is able to help you in some way. 希望这能够以某种方式帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.