首页 文章

如何将承载令牌转换为MVC应用程序的身份验证cookie

提问于
浏览
1

我有一个3层的应用程序结构 . 最终用户有一个cordova js应用程序,作为OpenID权限的identityserver3的实现,以及将通过cordova应用程序中的应用程序内浏览器访问的MVC应用程序 .

用户的起始入口点是cordova应用程序 . 他们通过应用程序内浏览器登录,然后可以访问应用程序功能或单击链接打开应用程序内浏览器并访问MVC应用程序 .

我们保护MVC网站的策略是使用不记名令牌身份验证,因为我们已经从应用程序登录过一次,并且当他们被定向到MVC应用程序时不想提示用户再次登录:

app.Map("/account", account =>
{
    account.UseIdentityServerBearerTokenAuthentication(new IdentityServer3.AccessTokenValidation.IdentityServerBearerTokenAuthenticationOptions()
    {
        Authority = "https://localhost:44333/core",
        RequiredScopes = new string[] { "scope" },
        DelayLoadMetadata = true,
        TokenProvider = new QueryStringOAuthBearerProvider(),
        ValidationMode = ValidationMode.ValidationEndpoint, 
    });
}

由于在查询字符串上持久化access_token非常痛苦,因此我实现了自定义OAuthBearerAuthenticationProvider:

public class QueryStringOAuthBearerProvider : OAuthBearerAuthenticationProvider
{
    private static ILog logger = LogManager.GetLogger(typeof(QueryStringOAuthBearerProvider));
    public override Task RequestToken(OAuthRequestTokenContext context)
    {
        logger.Debug($"Searching for query-string bearer token for authorization on request {context.Request.Path}");

        string value = GetAccessTokenFromQueryString(context.Request);

        if (!string.IsNullOrEmpty(value))
        {
            context.Token = value;
            //Save the token as a cookie so the URLs doesn't need to continue passing the access_token
            SaveAccessTokenToCookie(context.Request, context.Response, value);
        }
        else
        {
            //Check for the cookie
            value = GetAccessTokenFromCookie(context.Request);
            if (!string.IsNullOrEmpty(value))
            {
                context.Token = value;
            }
        }

        return Task.FromResult<object>(null);
    }
    [cookie access methods not very interesting]
}

这有效,并且允许MVC应用程序不必将访问令牌持久存储到每个请求中,但将访问令牌存储为通用cookie似乎是错误的 .

我真正想做的是使用访问令牌来处理OpenID endpoints 并发出一个表单身份验证样式cookie,它响应注销 . 我发现我可以添加 account.UseOpenIdConnectAuthentication(..) ,但如果我通过access_token进行身份验证,则只会跳过OpenIdConnectAuthentication位 . 有任何想法吗?

1 回答

  • 2

    你没有 - 访问令牌被设计用于调用web apis . 您使用来自OIDC的id_token对用户进行身份验证,并从您内部的声明中发出本地身份验证cookie . Microsoft OpenIdConnect身份验证中间件将为您完成大部分繁重工作 .

相关问题