OWIN在WebAPI和MVC应用程序之间共享声明

时间:2014-09-03 09:15:53

标签: owin asp.net-web-api2 claims

我们正在开发的当前应用程序包含2个应用程序。 WebApi应用程序和MVC前端应用程序。对于WebApi,我通过OWIN添加了对承载令牌授权的支持。这些应用程序在同一个域中作为单独的网站运行,但具有自己的子域site.xxx.xxx,api.xxx.xxx

对WebAPi进行身份验证,f.e。使用邮递员,按设计工作,主要和身份对象,包括索赔,正确初始化。

当我想从Mvc应用程序中登录WEbApi时出现问题。

有没有办法在通过WebAPI通过/ token url在某种程度上共享OWIN上下文登录之后在我们的MVC应用程序中获取ClaimsPrincipal和ClaimsIdentity,或者我们是否应该在MVC应用程序中实现相同的OWIN授权功能来创建一个单独的自动化“路线”?

1 个答案:

答案 0 :(得分:1)

是的,有。值得注意的事情

  • 默认情况下,您从网络API返回的令牌将被加密。您的Web应用程序需要解密此令牌才能从承载令牌中提取声明。为此,您必须在两台服务器上拥有相同的机器密钥(您的webapi web.config和mvc web.config需要具有相同的机器密钥)。
  • 您的MVC网络应用程序需要连接承载令牌和应用程序Cookie。您的startup.auth.cs可能包含以下内容:

    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);