首页 > 解决方案 > 如何使用 Owin 在 MVC 应用程序上获取 Azure B2C 访问令牌

问题描述

我的最新项目让我制作了一个 MVC 应用程序。该应用程序的基本要求是允许用户使用 Azure ADD B2C 登录并允许用户操作 Azure App Service 数据库上的数据。按照这里的这篇文章我已经成功地将用户登录到 B2C。但是,从登录应用服务开始,我无法进入应用程序的第二部分。我知道我需要从 B2C 获取访问令牌以传递给应用服务进行验证。我的问题是我只能获得一个 ID 令牌,该应用程序服务应该向我发送 401。我的 OWIN 启动类包含以下内容,就像文章一样:

public class Startup
{
    // App config settings
    private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
    private static string aadInstance = ConfigurationManager.AppSettings["ida:AadInstance"];
    private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
    private static string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];

    // B2C policy identifiers
    public static string SignUpPolicyId = ConfigurationManager.AppSettings["ida:SignUpPolicyId"];
    public static string SignInPolicyId = ConfigurationManager.AppSettings["ida:SignInPolicyId"];
    public static string ProfilePolicyId = ConfigurationManager.AppSettings["ida:UserProfilePolicyId"];

    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
    }

    public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        // Configure OpenID Connect middleware for each policy
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignUpPolicyId));
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(ProfilePolicyId));
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignInPolicyId));
    }

    // Used for avoiding yellow-screen-of-death
    private Task AuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
    {
        notification.HandleResponse();
        if (notification.Exception.Message == "access_denied")
        {
            notification.Response.Redirect("/");
        }
        else
        {
            notification.Response.Redirect("/Home/Error?message=" + notification.Exception.Message);
        }

        return Task.FromResult(0);
    }

    private OpenIdConnectAuthenticationOptions CreateOptionsFromPolicy(string policy)
    {
        return new OpenIdConnectAuthenticationOptions
        {
            // For each policy, give OWIN the policy-specific metadata address, and
            // set the authentication type to the id of the policy
            MetadataAddress = String.Format(aadInstance, tenant, policy),
            AuthenticationType = policy,

            // These are standard OpenID Connect parameters, with values pulled from web.config
            ClientId = clientId,
            RedirectUri = redirectUri,
            PostLogoutRedirectUri = redirectUri,
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = AuthenticationFailed
            },
            Scope = "openid",
            ResponseType = "id_token",

            // This piece is optional - it is used for displaying the user's name in the navigation bar.
            TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = "name",
                SaveSigninToken = true //important to save the token in boostrapcontext
            }
        };
    }
}

我尝试过的事情:

  1. 设置ResponceType"access_token"
  2. 设置Scope为我的自定义发布范围"user_impersonation"
  3. 我很确定它没有改变任何更好的东西,但我尝试设置NameClaimType"access_token"
  4. 其他一些只是左右抛出异常的事情。

这是我的第一个 MVC Web 应用程序,所以我仍在尝试了解它的工作原理;尤其是 cookie 的概念(甚至是如何存储我给定的访问令牌)。然而,我发现许多有用的教学视频和文章一直在帮助我。我只是没有找到任何与我正在尝试做的事情有关的东西。任何帮助或指导将不胜感激!谢谢!

标签: asp.net-mvcazureauthenticationcookiesazure-ad-b2c

解决方案


推荐阅读