程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用 AAD 身份验证从 React 前端使用 API 的 Cors 错误大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决使用 AAD 身份验证从 React 前端使用 API 的 Cors 错误?

开发过程中遇到使用 AAD 身份验证从 React 前端使用 API 的 Cors 错误的问题如何解决?下面主要结合日常开发的经验,给出你关于使用 AAD 身份验证从 React 前端使用 API 的 Cors 错误的解决方法建议,希望对你解决使用 AAD 身份验证从 React 前端使用 API 的 Cors 错误有所启发或帮助;

我已使用 Yeoman Teams App Generator 生成带有内置 Azure AD 单一登录的样板 ReactJs Teams 应用程序。
这有效。 Teams 应用通过 Azure AD(在后台)进行身份验证并从我的用户配置文件中提取一些数据。

现在我希望此 Teams 应用使用 API。此 API 是一个 ASP.NET Core 网站,它使用相同的 AAD 应用程序进行身份验证。 但是,当我尝试从 Teams 应用程序中的此 API 获取数据时,它失败并显示以下错误:

Access to fetch at 'https://login.microsoftonline.com/xxxx-xxx-xxx-xxx-xxxxx/oauth2/authorize?clIEnt_ID=xxx-xxx-xxx-xxx-xxx&redirect_uri=https%3A%2F%2Flocalhost%3A44391%2Fsignin-oIDc&response_type=ID_token&scope=openID%20profile&response_mode=form_post&nonce=xxx' 
(redirected from 'https://localhost:44391/User') from origin 'null' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
If an opaque response serves your needs,set the request's mode to 'no-cors' to fetch the resource with CORS Disabled.

我检查了 AAD 应用中的设置,并没有发现任何错误。

反应代码是:

import * as React from "react";
import { ProvIDer,Flex,Text,button,header } from "@fluentui/react-northstar";
import { useState,useEffect } from "react";
import { useTeams } from "msteams-react-base-component";
import * as microsoftTeams from "@microsoft/teams-Js";
import jwtDecode from "jwt-decode";

/**
 * Implementation of the Telefoonboek content page
 */
export const TelefoonboekTab = () => {

    const [{ inTeams,theme,context }] = useTeams();
    const [entityID,setEntityID] = useState<String | undefined>();
    const [name,setname] = useState<String>();
    const [error,setError] = useState<String>();

    useEffect(() => {
        if (inTeams === truE) {
            microsoftTeams.authentication.getAuthToken({
                successCallBACk: (token: String) => {
                    const decoded: { [key: String]: any; } = jwtDecode(token) as { [key: String]: any; };
                    setname(decoded!.Name);
                    microsoftTeams.appInitialization.notifysuccess();
                },failureCallBACk: (message: String) => {
                    setError(messagE);
                    microsoftTeams.appInitialization.notifyFailure({
                        reason: microsoftTeams.appInitialization.FailedReason.AuthFailed,message
                    });
                },resources: [process.env.TELEFOONBOEK_APP_URI as String]
            });
        } else {
            setEntityID("Not in Microsoft Teams");
        }
    },[inTeams]);

    useEffect(() => {
        if (context) {
            setEntityID(context.entityID);
        }
    },[context]);

    fetch("/User")
        .then(response => response.Json())
        .then(data => console.log(data));

    /**
     * The render() method to create the UI of the tab
     */
    return (
        <ProvIDer theme={themE}>
            <Flex fill={truE} column styles={{
                padding: ".8rem 0 .8rem .5rem"
            }}>
                <Flex.Item>
                    <header content="This is your tab" />
                </Flex.Item>
                <Flex.Item>
                    <div>
                        <div>
                            <Text content={`Hello ${name}`} />
                        </div>
                        {error && <div><Text content={`An SSO error occurred ${error}`} /></div>}

                        <div>
                            <button onClick={() => alert("It worked!")}>A sample button</button>
                        </div>
                    </div>
                </Flex.Item>
                <Flex.Item styles={{
                    padding: ".8rem 0 .8rem .5rem"
                }}>
                    <Text size="smaller" content="(C) copyright Zetacom" />
                </Flex.Item>
            </Flex>
        </ProvIDer>
    );
};

API 启动.cs:

using Microsoft.AspNetCore.builder;
using Microsoft.AspNetCore.HosTing;
using Microsoft.AspNetCore.httpsPolicy;
using Microsoft.AspNetCore.Spaservices.ReactDevelopmentServer;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.HosTing;
using Microsoft.AspNetCore.http;
using Microsoft.AspNetCore.Authentication.openIDConnect;
using Microsoft.AspNetCore.Authentication.AzureAD.UI;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.cookies;
using System;

namespace UserPresence
{
    public class Startup
    {
        private static Readonly String CustomAPIscheR_118_11845@e = "CustomAPIscheR_118_11845@e";
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public voID Configureservices(IserviceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(name: "CorsPolicy",builder =>
                                  {
                                      builder.AllowAnyOrigin();
                                  });
            });

            //ConfigureAuthentication(services);

            services.AddDbContext<dbContext>(options => optionS.UsesqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddTransIEnt<usermodel>();

            services.AddAuthentication(AzureADDefaults.AuthenticationscheR_118_11845@E)
                .AddAzureAD(options => Configuration.bind("AzureAd",options));

            services.AddControllersWithVIEws(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .requireAuthenticatedUser()
                    .build();
                options.Filters.Add(new Authorizefilter(policy));
            });

            // In production,the React files will be served from this directory
            services.AddSpaStaticfiles(configuration =>
            {
                configuration.RootPath = "ClIEntApp/build";
            });
        }

        private voID ConfigureAuthentication(IserviceCollection services)
        {
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticatescheR_118_11845@e = AzureADDefaults.cookiescheR_118_11845@e;
                options.DefaultChALLENgescheR_118_11845@e = CustomAPIscheR_118_11845@e;
                options.DefaultSignInscheR_118_11845@e = AzureADDefaults.cookiescheR_118_11845@e;
            })
            .AddAzureAD(options =>
            {
                Configuration.bind("AzureAd",options);
            })
            .AddscheR_118_11845@e<AuthenticationscheR_118_11845@eOptions,CustomAPIAuthenticationHandler>(CustomAPIscheR_118_11845@e,options => { });

            services.Configure<cookieAuthenticationoptions>(AzureADDefaults.cookiescheR_118_11845@e,options =>
            {
                options.cookie.httpOnly = true;
                options.cookie.SecurePolicy = cookieSecurePolicy.Always;
                options.cookie.SameSite = SameSiteMode.Lax;
                options.cookie.MaxAge = new TimeSpan(7,0);
            });

            services.Configure<OpenIDConnectoptions>(AzureADDefaults.OpenIDscheR_118_11845@e,options =>
            {
                options.Authority = options.Authority + "/v2.0/";         // Microsoft IDentity platform
                options.TokenValIDationParameters.ValIDateIssuer = false; // accept several tenants (here simplifIEd)
            });

            services.AddControllersWithVIEws(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .requireAuthenticatedUser()
                    .build();
                options.Filters.Add(new Authorizefilter(policy));
            });
        }

        // This method gets called by the runtime. Use this method to configure the http request pipeline.
        public voID Configure(IApplicationBuilder app,IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios,see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UsehttpsRedirection();
            app.UseStaticfiles();
            app.UseSpaStaticfiles();

            app.UseRoutIng();

            app.UseCors("CorsPolicy");

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",pattern: "{Controller}/{action=Index}/{ID?}");
            });
            
        }
    }
}

编辑:

我在 API 上添加了“AllowAnyOrigin”等。 现在 Teams 中的错误是:

Access to XMLhttprequest at 'https://login.microsoftonline.com/xxxxxxxxxxxx/oauth2/authorize?clIEnt_ID=xxxxxxx&redirect_uri=https%3A%2F%2Flocalhost%3A44391%2Fsignin-oIDc&xxx' 
(redirected from 'https://xxxx.eu.ngrok.io/User') from origin 'https://xxxx.eu.ngrok.io' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

解决方法

你的错误是由 CORS 政策引起的,我在我身边进行了测试 使用 builder.AllowAnyOrigin().AllowAnymethod().AllowAnyHeader(); 然后它起作用了。

但不是使用 ngrok,我将我的 MVC 程序部署到 azure 应用服务。

大佬总结

以上是大佬教程为你收集整理的使用 AAD 身份验证从 React 前端使用 API 的 Cors 错误全部内容,希望文章能够帮你解决使用 AAD 身份验证从 React 前端使用 API 的 Cors 错误所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。