简体   繁体   English

.Net 核心 Web API 未记录 204 响应

[英].Net Core Web API undocumented 204 Response

I am trying to create a .net core 6 Web Api that calls Microsoft Graph on behalf of what amounts to be an eventual Vue.Js client end user (with office 365 account and Azure Active Directory Registered).我正在尝试创建一个 .net core 6 Web Api 代表最终 Vue.Js 客户端最终用户调用 Microsoft Graph(具有 Office 365 帐户和 Azure Active Directory 注册)。 I haven't setup the client but I am trying to test the web api to make sure everythings working and my api calls all response with 204 (No Content).我没有设置客户端,但我正在尝试测试 web api 以确保一切正常,我的 api 调用所有响应都是 204(无内容)。 Postman also returns the same on those api calls. Postman 也会在那些 api 调用中返回相同的结果。 I suspect I haven't set the Graph Service Client up correctly but I can't find a way to fix it.我怀疑我没有正确设置图形服务客户端,但我找不到修复它的方法。

I setup authentication in my ConfigureServices like so我像这样在我的 ConfigureServices 中设置身份验证

            // Enable JWT Bearer Authentication
            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                Configuration.Bind("AzureAd", options);
                // Authority will be Your AzureAd Instance and Tenant Id
                options.Authority = $"{Configuration["AzureAd:Instance"]}{Configuration["AzureAd:TenantId"]}/v2.0";

                // The valid audiences are both the Client ID(options.Audience) and api://{ClientID}
                options.TokenValidationParameters.ValidAudiences = new string[] { Configuration["AzureAd:ClientId"], $"api://{Configuration["AzureAd:ClientId"]}" };
            });

            var options = new TokenCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
            };

            var authCodeCredential = new AuthorizationCodeCredential(Configuration["AzureAd:TenantId"], Configuration["AzureAd:ClientId"], Configuration["AzureAd:ClientSecret"],
            $"{Configuration["AzureAd:Instance"]}{Configuration["AzureAd:TenantId"]}/oauth2/v2.0/authorize", options);
            services.AddSingleton<GraphServiceClient>(_ => new GraphServiceClient(authCodeCredential, Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(', ')));
            
            AddSwagger(services);

With AddSwagger Being随着 AddSwagger 的出现

            services.AddOpenApiDocument(document =>
            {
                document.AddSecurity("bearer", Enumerable.Empty<string>(), new NSwag.OpenApiSecurityScheme
                {
                    Type = OpenApiSecuritySchemeType.OAuth2,
                    Description = "Azure AAD Authentication",
                    Flow = OpenApiOAuth2Flow.Implicit,
                    Flows = new NSwag.OpenApiOAuthFlows()
                    {
                        Implicit = new OpenApiOAuthFlow()
                        {
                            Scopes = new Dictionary<string, string>
                            {
                                { $"api://{Configuration["AzureAd:ClientId"]}/user_impersonation", "Access Application" },
                            },
                            AuthorizationUrl = $"{Configuration["AzureAd:Instance"]}{Configuration["AzureAd:TenantId"]}/oauth2/v2.0/authorize",
                            TokenUrl = $"{Configuration["AzureAd:Instance"]}{Configuration["AzureAd:TenantId"]}/oauth2/v2.0/token",
                        },  
                    },
                });

                document.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("bearer"));
            });

And then Create and User my GraphClient in the controller like So然后像这样在 controller 中创建并使用我的 GraphClient

        private readonly GraphServiceClient _graphServiceClient;
        public GraphController(GraphServiceClient graphServiceClient)
        {
            this._graphServiceClient = graphServiceClient;
        }

        [Authorize]
        [HttpGet("GetUserDetails")]
        public async Task<User> GetUserDetails()
        {
            try
            {
                User user = await _graphServiceClient.Me.Request().GetAsync();
                return user;
            }
            catch (Exception ex) 
            {
                return null;
            }
        }

I followed this document .我遵循了这份文件

If you want to use graph client to call graph api, then you need to set the auth provider first.如果你想使用graph client调用graph api,那么你需要先设置auth provider。 This is mentioned in the document I mentioned, you need to add AddMicrosoftGraph .This will make an authenticated GraphServiceClient available to controllers via dependency injection.我提到的文档中提到了这一点,您需要添加AddMicrosoftGraph 。这将使经过身份验证的 GraphServiceClient 通过依赖注入对控制器可用。

services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
                .EnableTokenAcquisitionToCallDownstreamApi(new string[] { "user.read" })
                .AddMicrosoftGraph(options =>
                {
                    options.Scopes = string.Join(' ', new string[] { "user.read" });
                })
                .AddInMemoryTokenCaches();

Or this code instead.或者改为此代码。

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    // Specify this is a web app and needs auth code flow
    //.AddMicrosoftIdentityWebApp(Configuration)
    // Add ability to call web API (Graph)
    // and get access tokens
    .EnableTokenAcquisitionToCallDownstreamApi(new string[] { "user.read" })
    //need to install Microsoft.Identity.Web.MicrosoftGraph
    //Add a GraphServiceClient via dependency injection
    .AddMicrosoftGraph(options =>
    {
        options.Scopes = string.Join(' ', new string[] { "user.read" });
    })
  // Use in-memory token cache
  // See https://github.com/AzureAD/microsoft-identity-web/wiki/token-cache-serialization
  .AddInMemoryTokenCaches();

My packages installed:我安装的包:

<ItemGroup>
    <PackageReference Include="Microsoft.Graph" Version="4.19.0" />
    <PackageReference Include="Microsoft.Identity.Web" Version="1.23.0" />
    <PackageReference Include="Microsoft.Identity.Web.MicrosoftGraph" Version="1.23.0" />
    <PackageReference Include="Microsoft.Identity.Web.UI" Version="1.23.0" />
  </ItemGroup>

The issue ended up being the问题最终成为

 authCodeCredential = new AuthorizationCodeCredential(Configuration["AzureAd:TenantId"], Configuration["AzureAd:ClientId"], Configuration["AzureAd:ClientSecret"],
            $"{Configuration["AzureAd:Instance"]}{Configuration["AzureAd:TenantId"]}/oauth2/v2.0/authorize", options);
            services.AddSingleton<GraphServiceClient>(_ => new GraphServiceClient(authCodeCredential, Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(', ')));

Where the authorization code being passed in was incorrect.传入的授权码不正确。 Unsure of how to fix this at the moment but replacing this line of code with a UsernamePasswordCredential instead gave the correct outputs.目前不确定如何解决此问题,但用 UsernamePasswordCredential 替换这行代码反而给出了正确的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM