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

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

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

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

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

回答(1)

3 years ago

就在这里 . 要注意的事情

  • 默认情况下,您从Web api返回的令牌将被加密 . 您的Web应用程序需要解密此令牌才能从承载令牌中提取声明 . 为此,您必须在两台服务器上拥有相同的机器密钥(您的webapi web.config和mvc web.config需要具有相同的机器密钥)

  • 您的MVC Web应用程序需要连接承载令牌和应用程序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);