如何使用 Owin 在 MVC 应用程序上获取 Azure B2C 访问令牌

Jos*_*ens 5 authentication cookies asp.net-mvc azure azure-ad-b2c

我的最新项目让我制作了一个 MVC 应用程序。该应用程序的基本要求是允许用户使用 Azure ADD B2C 登录并允许用户操作 Azure 应用服务数据库上的数据。按照此处的这篇文章,我已成功将用户登录到 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
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试过的事情:

  1. 设置ResponceType"access_token"
  2. 将 设置Scope为我的自定义发布范围"user_impersonation"
  3. I was pretty sure it didn't change anything for the better but I tried setting NameClaimType to "access_token"
  4. A few other things that just threw exceptions left and right.

This is my first MVC web application so I'm still trying to understand how exactly it works; especially the concept of cookies (and even how to store the access token I'm given). I have however found many helpful instructional videos and articles that have been helping me along. I just haven't found anything that deals with what I am trying to do. Any help or guidance would be greatly appreciated! Thanks!