2016-02-17 29 views
14

Cookie Middleware認証を使用してasp.netコアmvc​​ 6アプリケーションを作成しようとしています。 私のコードがエラーなしでコンパイル、それでもログイン成功後、私は、ユーザー権限がありませんよ。ここAsp.Net MVC 6 Cookie認証 - 認証が失敗します

だ私のstartup.cs

 app.UseCookieAuthentication(options => 
     { 
      options.AuthenticationScheme = "CookieAuth"; 
      options.LoginPath = new PathString("/Account/Login/"); 
      options.AccessDeniedPath = new PathString("/Account/Login/"); 
      options.AutomaticAuthenticate = true; 
      options.AutomaticChallenge = true; 

     }); 

はまた私のコントローラにアクションをログイン設定:

public async Task<IActionResult> Login(LoginViewModel model) 
    { 

     User foundUser = _userManager.findUser(model.UserName, model.Password); 


     if (foundUser != null) 
     { 
      List<Claim> userClaims = new List<Claim> 
      { 
       new Claim("userId", Convert.ToString(foundUser.UserID)), 
       new Claim(ClaimTypes.Name, foundUser.UserName), 
       new Claim(ClaimTypes.Role, Convert.ToString(foundUser.RoleID)) 
      }; 

      ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims)); 
      await HttpContext.Authentication.SignInAsync("CookieAuth", principal); 


      return RedirectToAction("Index", "Dashboard"); 
     } 
     return View(); 
    } 

そして、最終的にDashboard/Indexアクション

[Authorize] 
public IActionResult Index() 
{ 
    return View(); 
} 

私はいくつかのbreakpoiログインアクションのntsとすべてがうまくいくようです。 Cookieも正しく設定されています。

そして今、私は私がサインインした後、ダッシュボード/インデックスに行くことができない方法を知りません。 私は原因/アカウント/ログイン/にリダイレクトしていますたびにコンフィギュレーション設定に

私は何をやっています違う ?

答えて

17

ログイン時にClaimsIdentityを作成する場合は、authenticationTypeを指定する別のコンストラクタを使用する必要があります。

あなたがすべき

代わりの

ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims)); 

ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims, "local")); 

特許請求の範囲を持っているClaimsIdentityを作成できるようになりましたが、 はfalseに設定にisAuthenticatedました。実は、これは今...

がtrueに設定さにisAuthenticatedしているために、デフォルトで、私はドミニクBaierのさんのブログhereからこの情報を得た認証タイプ

を指定する必要があります。

クッキーのミドルウェアhereを、(伝説的な)Dominick Baier/leastprivilegeも使っている素晴らしい例があります。

EDIT:

This answerauthenticationType文字列のために使用されるべきかについての詳細な情報が含まれています。

+2

ありがとうございました!私の人生の2時間を失った:( – Kuba

+1

2時間以上が失われたが、少なくとも私は理由を知っている! –

+1

これで4時間を過ごした。 'authenticationType'パラメータのために" Cookie "、" JWT "、または使用されたスキームは何ですか? – Omar