2016-07-01 17 views
3

私はMVCコントローラとWeb APIコントローラの間で同じ認証を使用しようとしています。 Web APIは同じプロジェクトにあり、/ Controllers/API /フォルダ内にあります。MVCとWeb APIのOwin認証

MVCを介してログインし、以下の例のようなクレームとクッキーを作成したときに、OWINを使用して認証する方法がわかりません。

var identity = new ClaimsIdentity(new[] 
{ 
    new Claim(ClaimTypes.Name,"Admin"), 
    new Claim(ClaimTypes.Role,"Administrator") 
    , "ApplicationCookie"); 

    var ctx = Request.GetOwinContext(); 
    var authManager = ctx.Authentication; 
    authManager.SignIn(identity); 
    return RedirectToAction("Index", "Home", null); 
    } 

すべてがMVCコントローラで正常に動作しますが、私は私のウェブAPIコントローラ上の[承認(役割=「管理者」]属性を使用して、それが正常に動作することはできません。それは関係なく、常にを通して私をすることができます。

おかげ

EDIT:唯一の方法私はこれに対処することができました静的クラスとプロパティストアIPrincipalを持った後、承認の属性をオーバーライドする場合、そのプロパティを探している役割があるかどうかをチェックされますそれは良いアイデアかどうかわからないのですか?

+0

私の答えを確認できますか? –

答えて

5

あなたの認証コードはどこに書かれていますか? MVCコントローラまたはWeb APIコントローラ?私はあなたのWeb APIコントローラに、他のアプリケーション(SPAやその他のWebアプリケーション)で後で使用できるようにすることをお勧めします。認証サーバー/リソースサーバーモデルを構築する必要があります。この文章をどのようにフレーム化するか)。あなたのケースでは、Web APIは両方とも、MVCサイトはリソースサーバーです。

以下

はここhttp://bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web-api-and-identity-2/

を説明するように、あなたが一度あなたのwebAPIsのstartup.csが見えるだろうというWEB APIとASP.NetアイデンティティでJWTを使用して認証サーバを構築JWT +クッキーのミドルウェア

のためのサンプルです

/// Configures cookie auth for web apps and JWT for SPA,Mobile apps 
    private void ConfigureOAuthTokenGeneration(IAppBuilder app) 
    { 
     // Configure the db context, user manager and role manager to use a single instance per request 
     app.CreatePerOwinContext(ApplicationDbContext.Create); 
     app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 
     app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); 

     //Cookie for old school MVC application 
     var cookieOptions = new CookieAuthenticationOptions 
     { 
      AuthenticationMode = AuthenticationMode.Active, 
      CookieHttpOnly = true, // JavaScript should use the Bearer 
      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,     
      LoginPath = new PathString("/api/Account/Login"), 
      CookieName = "AuthCookie" 
     }; 
     // Plugin the OAuth bearer JSON Web Token tokens generation and Consumption will be here 
     app.UseCookieAuthentication(new CookieAuthenticationOptions()); 

     OAuthServerOptions = new OAuthAuthorizationServerOptions() 
     { 
      //For Dev enviroment only (on production should be AllowInsecureHttp = false) 
      AllowInsecureHttp = true, 
      TokenEndpointPath = new PathString("/oauth/token"), 
      AccessTokenExpireTimeSpan = TimeSpan.FromDays(30), 
      Provider = new CustomOAuthProvider(),     
      AccessTokenFormat = new CustomJwtFormat(ConfigurationManager.AppSettings["JWTPath"]) 
     }; 

     // OAuth 2.0 Bearer Access Token Generation 
     app.UseOAuthAuthorizationServer(OAuthServerOptions); 
    } 

以下のようにあなたはここにhttps://github.com/tjoudeh/AspNetIdentity.WebApi/tree/master/AspNetIdentity.WebApi/Providers

をCustomOAuthProvider、CustomJwtFormatクラスを見つけることができますあなたはトークンがそれをデシリアライズし、このAでアクセストークン

  AccessClaims claimsToken = new AccessClaims(); 
      claimsToken = JsonConvert.DeserializeObject<AccessClaims>(response.Content); 
      claimsToken.Cookie = response.Cookies[0].Value;    
      Request.Headers.Add("Authorization", "bearer " + claimsToken.access_token); 
      var ctx = Request.GetOwinContext(); 
      var authenticateResult = await ctx.Authentication.AuthenticateAsync("JWT"); 
      ctx.Authentication.SignOut("JWT"); 
      var applicationCookieIdentity = new ClaimsIdentity(authenticateResult.Identity.Claims, DefaultAuthenticationTypes.ApplicationCookie); 
      ctx.Authentication.SignIn(applicationCookieIdentity); 

からクッキーを生成する受信したときに、あなたのMVCアプリで10

あなたのMVCコントローラでstartup.csに以下

public void Configuration(IAppBuilder app) 
    { 
      ConfigureOAuthTokenConsumption(app); 
    } 

    private void ConfigureOAuthTokenConsumption(IAppBuilder app) 
    { 
     var issuer = ConfigurationManager.AppSettings["AuthIssuer"]; 
     string audienceid = ConfigurationManager.AppSettings["AudienceId"]; 
     byte[] audiencesecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["AudienceSecret"]); 

     app.UseCookieAuthentication(new CookieAuthenticationOptions { CookieName = "AuthCookie" , AuthenticationType=DefaultAuthenticationTypes.ApplicationCookie }); 

     //// Api controllers with an [Authorize] attribute will be validated with JWT 
     app.UseJwtBearerAuthentication(
      new JwtBearerAuthenticationOptions 
      { 
       AuthenticationMode = AuthenticationMode.Passive, 
       AuthenticationType = "JWT", 
       AllowedAudiences = new[] { audienceid }, 
       IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] 
       { 
        new SymmetricKeyIssuerSecurityTokenProvider(issuer, audiencesecret)       
       } 

      }); 
    } 

を追加クッキーが作成され、MVCサイトの[Authorize]属性とWebAPIがこのクッキーを尊重します。

関連する問題