【问题标题】:Authorization has been denied for this request. Always此请求的授权已被拒绝。总是
【发布时间】:2015-10-07 22:29:40
【问题描述】:

我已经创建了一个 MVC webApi 项目,现在我想使用身份验证和授权。 我想我已经实现了这种安全性,但由于某种原因出现了问题,当我编写凭据并尝试调用一些 webApi 方法时,会显示消息“此请求的授权已被拒绝”。

这是我实现的代码。

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());
    }

路由配置:

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 }
        );
    }

控制器:

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:

<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:

$(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')
        }
    });

【问题讨论】:

    标签: c# asp.net authentication asp.net-web-api authorization


    【解决方案1】:

    您应该将[AllowAnonymous] 属性添加到控制器的LogInPost

    当您将AuthorizeAttribute 添加到过滤器时,它会导致您的控制器假定默认情况下他们需要对所有操作(包括用于登录的操作)进行授权。

    【讨论】:

    • 我认为问题在于我在哪里实现 Thread.CurrentPrincipal 和 Current.User,因为如果我在我的 API 控制器中添加属性 [AllowAnonymous] 应用程序工作正常,但如果我添加属性 [ Authorize(Roles = RoleEntity.Collaborator)] 例如应用程序无法识别此角色。所以这就是为什么我认为我应该在其他地方或以其他方式实现 CurrentPrincipal,你知道我应该在哪里实现吗?
    • 这是一个较晚的响应,但是如果用户尚未进行身份验证,您怎么能期望一个动作来授权角色呢?
    【解决方案2】:

    您是否在进行 Windows 身份验证?您是否收到“拒绝访问”错误?

    有时 IISEXpress 和 IIS 会采取一些技巧,为了克服这一点,我将站点托管在本地 iis (inetmgr) 中,启用身份验证(如果适用,Windows)并现在运行它。

    附:并非所有机器都默认安装了 IIS 服务器,因此如果 inetmgr 不起作用,那么您必须从控制面板安装它 --> Windows 功能 --> 选择 IIS 和 ASP .NET 的所有功能

    希望这会有所帮助。

    【讨论】:

    • 我正在实施自己的身份验证,并且收到此错误“此请求的授权已被拒绝”。我想是因为我应该在其他地方实现当前的主体,你知道我应该在哪里做吗?
    【解决方案3】:

    很抱歉这么晚才回复 - 我找到了您的问题,因为从 IIS 托管的 web api 切换到自托管的 web api 后,我刚刚开始遇到同样的问题。

    就我而言,问题是由我初始化 Thread.CurrentPrincipal 的方式引起的。一些背景:

    1. 我正在使用自定义 AuthenticationHandler(继承自 DelegationHandler)
    2. 在这个处理程序中,我重写了 SendAsync 方法来执行一些自定义用户验证。
    3. 如果验证成功,我会构造一个 ClaimsPrincipal 类的实例来包含有关当前用户的一些声明。

    以前,在将消息传递给管道中的其余消息处理程序之前,我将此 ClaimsPrincipal 实例分配给 Thread.CurrentPrincipal。但是,我的解决方案是改用 HttpRequestContext 实例上的 Principal 成员,该实例属于传递给 SendAsync 的 HttpRequestMessage 实例。因此(在 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...
    

    希望这能够以某种方式帮助您。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-22
      • 1970-01-01
      • 2019-07-17
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      • 2018-10-05
      相关资源
      最近更新 更多