2017-12-05 11 views
0

MVCとAPIコントローラをパラレルに使用するプロジェクトで作業しています。 MVCコントローラとトークンベースのAPIコントローラでCookieベースの認証を使用することはできますか?それを達成する方法?1つのプロジェクトでクッキーとトークンベースのパラレル化を使用する

私のStartup.authを以下のように構築し、[Authorize]属性を使用すると、Web APIが呼び出されている間にクッキーをチェックしてメソッドを実行できるため、期待通りに機能しませんトークンなし。

public partial class Startup 
{ 
    private string PublicClientId { get; set; } 
    private OAuthAuthorizationServerOptions OAuthOptions { get; set; } 

    public void ConfigureAuth(IAppBuilder app) 
    { 
     app.CreatePerOwinContext(DatabaseContext.Create); 
     app.CreatePerOwinContext<MobileUserManager>(MobileUserManager.Create); 
     app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); 

     app.UseCookieAuthentication(new CookieAuthenticationOptions 
     { 
      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
      LoginPath = new PathString("/AuthServices/SignIn"), 
      Provider = new CookieAuthenticationProvider 
      { 
       OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<MobileUserManager, UserEntity, int>(
        validateInterval: TimeSpan.FromMinutes(30), 
        regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager), 
        getUserIdCallback: (id) => (id.GetUserId<int>())) 
      } 
     }); 

     PublicClientId = "self"; 
     OAuthOptions = new OAuthAuthorizationServerOptions 
     { 
      AllowInsecureHttp = true, 
      TokenEndpointPath = new PathString("/token"), 
      AccessTokenExpireTimeSpan = TimeSpan.FromDays(180), 
      Provider = new ApplicationOAuthProvider(PublicClientId), 
      RefreshTokenProvider = new ApplicationRefreshTokenProvider() 
     }; 
     app.UseOAuthBearerTokens(OAuthOptions); 
    } 
} 

答えて

0
あなたは承認属性をオーバーライドして、現在とは何か、この(単なる疑似コード)のように必要とされる認証の種類をチェックしてみてください

public class AuthorizeAttribute : AuthorizeAttribute 
{ 
    private bool IsCookieAuthAllowed { get; } 

    public ApolloAuthorizeAttribute(bool isCookieAuthAllowed = false) 
    { 
     IsCookieAuthAllowed = isCookieAuthAllowed; 
    } 

    protected override bool IsAuthorized(HttpActionContext actionContext) 
    { 
     var identity = actionContext.ControllerContext.RequestContext.Principal?.Identity; 

     if (identity == null) 
      return false; 

     if (identity.IsCookie()) 
      return IsCookieAuthAllowed && identity.IsAuthenticated; 

     return base.IsAuthorized(actionContext); 
    } 
} 
関連する問題