此请求已被拒绝授权。总是

时间:2015-10-07 22:29:40

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

我已经创建了一个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')点击(登录); });

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

3 个答案:

答案 0 :(得分:12)

您应该将LogInPost属性添加到您的Controller的AuthorizeAttribute

当您将Kellys-MacBook-Air:~ kelly$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" It appears Homebrew is already installed. If your intent is to reinstall you should do the following before running this installer again: ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)" Kellys-MacBook-Air:~ kelly$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)" Failed to locate Homebrew! 添加到过滤器时,它会导致您的控制器假定所有操作都需要授权,包括用于登录的操作。

答案 1 :(得分:3)

您正在进行Windows身份验证吗?你收到“拒绝访问”错误了吗?

有时IISEXpress和IIS会做一些技巧并且要克服我在本地iis(inetmgr)中托管该站点的情况,启用身份验证(如果适用,则启用Windows),然后运行它。

P.S。并非所有计算机都默认安装了IIS服务器,因此如果inetmgr不起作用,则必须从控制面板安装它 - &gt; Windows功能 - &gt;选择IIS和ASP .NET的所有功能

希望这会有所帮助。

答案 2 :(得分:2)

很抱歉这么晚的回复 - 我发现了你的问题,因为我已经从IIS托管的网络API切换到自托管的网络API,我刚刚开始遇到同样的问题。

在我的情况下,问题是由我初始化Thread.CurrentPrincipal引起的。一些背景:

  1. 我使用自定义AuthenticationHandler(继承自DelegationHandler)
  2. 在此处理程序中,我重写了SendAsync方法以进行一些自定义用户验证。
  3. 如果验证成功,我构造一个ClaimsPrincipal类的实例,以包含有关当前用户的一些声明。
  4. 以前,我将此ClaimsPrincipal实例分配给Thread.CurrentPrincipal,然后将消息传递给管道中的其余消息处理程序。但是,我的解决方案是在HttpRequestContext实例上使用Principal成员,该实例属于传递给SendAsync的HttpRequestMessage实例。因此(在F#中),

    for item in [ 1, 2, 3, undefined, 5, 6]
      current = if item? then item else "error", break
    console.dir current
    

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