2015-10-07 52 views
8

私はすでに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 --> 
。10の

JS:

$(ドキュメント).ready(関数(){ $( '#の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') 
     } 
    }); 

答えて

11

あなたのフィルタにAuthorizeAttributeを追加すると、それはあなたのコントローラが前提とさせあなたのコントローラのLogInPost

[AllowAnonymous]属性を追加する必要があり、それらはものを含め、すべてのアクションのためにデフォルトで承認を必要とログインに使用されます。

+0

私は私のAPIコントローラに属性[のAllowAnonymous]を追加した場合、アプリが正常に動作しますので、私は、のThread.CurrentPrincipalとCurrent.Userを実施していますどこに問題があると思うが、私は、属性[承認(役割の追加場合= RoleEntity .Collaborator)]たとえば、アプリケーションはこのロールを認識しません。だからこそ私はCurrentPrincipalを他の場所や別の方法で実装すべきだと思うのですが、どこに抱かせるべきか分かりますか? – user3442776

+0

これは遅れていますが、ユーザーがまだ認証を受けていない場合に、ロールの承認を求めるアクションをどのように期待できますか? –

3

あなたは、Windows認証をやっていますか? 「アクセスが拒否されました」というエラーが表示されますか?

IISEXpressとIISは、ローカルのiis(inetmgr)でサイトをホストし、認証(該当する場合はウィンドウを有効にして)を実行して今すぐ実行するというトリックを克服します。

P.S.すべてのコンピュータにデフォルトでIISサーバーがインストールされているわけではないので、inetmgrが機能しない場合は、コントロールパネル - > Windowsの機能 - > IISおよびASP .NETのすべての機能をインストールする必要があります。

助けて。

+0

私は自分の認証を実装していますが、このエラーは「この要求に対して認証が拒否されました」と表示されています。現在のプリンシパルを他の場所に実装する必要があるためだと思います。どこでやるべきか分かりますか? – user3442776

2

な後半応答のため申し訳ありません - セルフホストのWeb APIにIISがホストするWeb APIを切り替えた、私はちょうど同じ問題を経験し始めました、ので、私はあなたの質問を見つけました。私の場合は

、問題は私がのThread.CurrentPrincipalを初期化された方法によって引き起こされました。いくつかの背景:

  1. 私はこのハンドラでは、カスタム(DelegationHandlerから継承)AuthenticationHandler
  2. を使用していますが、私はいくつかのカスタムユーザー検証を行うためのSendAsyncメソッドをオーバーライドしています。
  3. 検証が成功した場合、私は、現在のユーザーに関するいくつかの主張が含まれてClaimsPrincipalクラスのインスタンスを構築します。

以前、このClaimsPrincipalインスタンスをThread.CurrentPrincipalに割り当ててから、メッセージをパイプラインの残りのメッセージハンドラに渡しました。しかし、私のためのソリューションは、SendAsyncに渡されHttpRequestMessageインスタンスに属しHttpRequestContextインスタンスに代わり主要メンバーを使用することでした。したがって、(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... 

希望これは、いくつかの方法であなたを助けることができます。

関連する問題