首页 文章

OAuth 2.0,Azure AD和OpenId Connect

提问于
浏览
1

我仍在尝试使用ASP.Net Core 2.0了解OAuth 2.0流程 . Microsoft提供的默认代码(见下文)与使用OAuth 2.0和OpenId Connect的Azure AD身份验证配合良好 .

我实际上正在测试授权代码流程 .

我试图更改下面的代码,以便它不使用OpenId Connect,而是使用普通的OAuth . (您可能想问为什么,我正在使用的供应商尚未支持OpenId Connect) .

因此,我需要使用纯OAuth来启用使用Azure AD的授权代码流 .

services.AddAuthentication(auth =>
            {
                auth.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                auth.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;

            })
            .AddCookie()

            .AddOpenIdConnect(opts =>
            {
                Configuration.GetSection("Authentication").Bind(opts);

                opts.Events = new OpenIdConnectEvents
                {
                    OnAuthorizationCodeReceived = async ctx =>
                    {
                        HttpRequest request = ctx.HttpContext.Request;
                        //We need to also specify the redirect URL used
                        string currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path);
                        //Credentials for app itself
                        var credential = new ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret);

                        //Construct token cache
                        ITokenCacheFactory cacheFactory = ctx.HttpContext.RequestServices.GetRequiredService<ITokenCacheFactory>();
                        TokenCache cache = cacheFactory.CreateForUser(ctx.Principal);

                        var authContext = new AuthenticationContext(ctx.Options.Authority, cache);

                        //Get token for Microsoft Graph API using the authorization code
                        string resource = "https://bupaau.onmicrosoft.com/4fa4b4a7-d34f-49af-8781-c8b39f0cf770";
                        AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                            ctx.ProtocolMessage.Code, new Uri(currentUri), credential, resource);

                        //Tell the OIDC middleware we got the tokens, it doesn't need to do anything
                        ctx.HandleCodeRedemption(result.AccessToken, result.IdToken);
                    }
                };
            });

如何关闭openId Connect并为授权代码流启用普通OAuth身份验证 .

-Alan-

1 回答

  • 1

    您可以使用 scope 参数值指定此值 . 对于OpenID Connect, scope 值设置为 openid . 这是规范关于授权请求的说法 .

    但是您需要注意一些Azure AD细节 . Azure AD文档中突出显示了这一点 . 对于OpenID Connect

    当您的Web应用程序需要对用户进行身份验证时,它必须将用户定向到/ authorize endpoints . 此请求类似于OAuth 2.0授权代码流的第一站,但有一些重要区别:请求必须在scope参数中包含范围openid . response_type参数必须包含id_token . 请求必须包含nonce参数 .

    这里还有OAuth 2.0 documentation的链接 . 您可能不会简单地删除OpenID Connect特定参数以获取OAuth 2.0响应,因为可能存在特定于实现的要求 .

相关问题