2014-09-03 83 views
3

我們正在開發的當前應用程序由2個應用程序組成。一個WebApi應用程序和一個MVC前端應用程序。對於WebApi,我通過OWIN添加了對持票人授權的支持。這些應用程序作爲單獨的網站在同一個域中運行,但具有它們自己的子域site.xxx.xxx,api.xxx.xxxOWIN在WebAPI和MVC應用程序之間共享聲明

向WebAPi進行身份驗證,f.e.郵遞員按照設計工作,包括索賠在內的主要和身份對象都被正確初始化。

的問題是,當我想從MVC應用中登錄到的WebAPI。

有沒有什麼辦法在通過WebAPI通過/ token url登錄後在我們的MVC應用程序中獲得ClaimsPrincipal和ClaimsIdentity,有點分享OWIN上下文,還是應該在MVC應用程序內部實現相同的OWIN授權功能創建一個單獨的自動化「路線」?

回答

1

是的,有。夫婦注意事項

  • 您從web api獲取的令牌將默認加密。您的Web應用程序需要解密此令牌才能從不記名令牌中提取聲明。對於這一點,你必須有兩個服務器在同一臺機器密鑰(你的WebAPI的web.config和MVC的web.config需要具有相同的機鍵)
  • 你的MVC的Web應用程序需要線了兩個承載令牌和應用程序cookie。在您的登錄方法

    public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; } 
    
    static Startup() 
    { 
        OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); 
    } 
    
    
    public void ConfigureAuth(IAppBuilder app) 
    { 
        app.UseOAuthBearerAuthentication(OAuthBearerOptions); 
        app.UseCookieAuthentication(new CookieAuthenticationOptions 
        { 
         AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
         LoginPath = new PathString("/Account/Login") 
        }); 
    } 
    

    現在

    //Assume that the token that you got from web api is in the variable called accessToken 
    //Decrypt this token first. If your machine keys are the same, the following line will work 
    
    var unencryptedToken = Startup.OAuthBearerOptions.AccessTokenFormat.Unprotect(accessToken); 
    
    //Next, extract the claims identity from the token 
    var identity = unencryptedToken.Identity; 
    
    //Need to create a claims identity that uses a cookie (not a bearer token). An MVC app 
    //knows how to deal with a claims identity using an application cookie, but doesn't know 
    //how to deal with a claims identity using a bearer token. So this is a translation step 
    //from a web api authentication mechanism to the mvc authentication mechanism 
    
    var id = new ClaimsIdentity(identity.Claims, DefaultAuthenticationTypes.ApplicationCookie); 
    
    //At this moment, your new claims identity using an application cookie is ready, but we still 
    //need to sign in. Use the OWIN Auth manager from the context to sign in. This will create 
    //the application cookie and correctly populate User.IsAuthenticated(). From now on, you are 
    //logged in 
    
    AuthenticationManager.SignIn(id); 
    
+0

感謝您全面的回答:你startup.auth.cs可能包括這樣的事情。 「不保護」部分是我不知道存在的部分。在我期待已久的假期後,我可以試試這個辦公室。 – 2014-12-30 22:33:46

相關問題