Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何配置React客户端、.NET Core 3.1后端、单租户SSO_Reactjs_Asp.net Core_Azure Active Directory_Single Sign On - Fatal编程技术网

Reactjs 如何配置React客户端、.NET Core 3.1后端、单租户SSO

Reactjs 如何配置React客户端、.NET Core 3.1后端、单租户SSO,reactjs,asp.net-core,azure-active-directory,single-sign-on,Reactjs,Asp.net Core,Azure Active Directory,Single Sign On,我想知道这是否可能 我将我的整个API锁定在一个[Authorize]标记后面 我的startup类的配置如下: using Application.TestEntities; using FluentValidation.AspNetCore; using MediatR; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.AzureAD.UI; using Microsof

我想知道这是否可能

我将我的整个API锁定在一个[Authorize]标记后面

我的startup类的配置如下:

using Application.TestEntities;
using FluentValidation.AspNetCore;
using MediatR;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.AzureAD.UI;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Persistence;

namespace API
{
    public class Startup
    {
        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.AddDbContext<DataContext>(opt =>
            {
                opt.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
            });
            services.AddCors(opt =>
            {
                opt.AddPolicy("CorsPolicy", policy =>
                {
                    policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:3000");
                });
            });
            services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
                .AddAzureADBearer(opt => Configuration.Bind("AzureAd", opt));

            services.AddMediatR(typeof(List.Handler).Assembly);
            services.AddControllers().AddFluentValidation(cfg => cfg.RegisterValidatorsFromAssemblyContaining<Create>());
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseMiddleware<ErrorHandlingMiddleware>();
            if (env.IsDevelopment())
            {
                // app.UseDeveloperExceptionPage();
            }

            app.UseCors("CorsPolicy");

            app.UseRouting();

            app.UseAuthentication();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
使用Application.testenties;
使用FluentValidation.AspNetCore;
使用MediatR;
使用Microsoft.AspNetCore.Authentication;
使用Microsoft.AspNetCore.Authentication.AzureAD.UI;
使用Microsoft.AspNetCore.Builder;
使用Microsoft.AspNetCore.Hosting;
使用Microsoft.EntityFrameworkCore;
使用Microsoft.Extensions.Configuration;
使用Microsoft.Extensions.DependencyInjection;
使用Microsoft.Extensions.Hosting;
使用持久性;
名称空间API
{
公营创业
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddDbContext(opt=>
{
opt.UseSqlite(Configuration.GetConnectionString(“DefaultConnection”);
});
services.AddCors(opt=>
{
opt.AddPolicy(“CorsPolicy”,policy=>
{
policy.AllowAnyHeader().AllowAnyMethod().WithOrigins(“http://localhost:3000");
});
});
services.AddAuthentication(AzureADDefaults.BeareAuthenticationScheme)
.AddAzureADBearer(opt=>Configuration.Bind(“AzureAd”,opt));
AddMediatR(typeof(List.Handler).Assembly);
services.AddControllers().AddFluentValidation(cfg=>cfg.RegisterValidatorsFromAssemblyContaining());
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
app.UseMiddleware();
if(env.IsDevelopment())
{
//app.UseDeveloperExceptionPage();
}
附录UseCors(“公司政策”);
app.UseRouting();
app.UseAuthentication();
app.UseEndpoints(端点=>
{
endpoints.MapControllers();
});
}
}
}
设置my appsettings.json后:

{
  "ConnectionStrings": {
    "DefaultConnection": "Data source = blahblah.db"
  },
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "<MyTenantId>",
    "ClientId": "<MyClientId>"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

{
“连接字符串”:{
“DefaultConnection”:“数据源=blahblah.db”
},
“蓝精灵”:{
“实例”:https://login.microsoftonline.com/",
“租户”:“,
“客户端ID”:”
},
“日志记录”:{
“日志级别”:{
“默认值”:“信息”,
“Microsoft”:“警告”,
“Microsoft.Hosting.Lifetime”:“信息”
}
}
}
在客户端,我在index.tsx中使用react aad msal:

import React from "react";
import ReactDOM from "react-dom";
import { Router } from "react-router-dom";
import { createBrowserHistory } from "history";
import "react-toastify/dist/ReactToastify.min.css";
import "react-widgets/dist/css/react-widgets.css";
import "./app/layout/styles.css";
import App from "./app/layout/App";
import * as serviceWorker from "./serviceWorker";
import ScrollToTop from "./app/layout/ScrollToTop";
import dateFnsLocalizer from "react-widgets-date-fns";
import { AzureAD } from "react-aad-msal";
import { authProvider } from "./app/common/util/authProvider";

new dateFnsLocalizer();

export const history = createBrowserHistory();

ReactDOM.render(
  // <React.StrictMode>
  <AzureAD provider={authProvider} forceLogin={true}>
    <Router history={history}>
      <ScrollToTop>
        <App />
      </ScrollToTop>
    </Router>
  </AzureAD>,
  // </React.StrictMode>,
  document.getElementById("root")
);

serviceWorker.unregister();
从“React”导入React;
从“react dom”导入react dom;
从“react Router dom”导入{Router};
从“历史”导入{createBrowserHistory};
导入“react toastify/dist/react toastify.min.css”;
导入“react widgets/dist/css/react widgets.css”;
导入“/app/layout/styles.css”;
从“/App/layout/App”导入应用程序;
将*作为serviceWorker从“/serviceWorker”导入;
从“/app/layout/ScrollToTop”导入ScrollToTop;
从“日期fns”导入dateFnsLocalizer;
从“react aad msal”导入{AzureAD};
从“/app/common/util/authProvider”导入{authProvider}”;
新的dateFnsLocalizer();
export const history=createBrowserHistory();
ReactDOM.render(
// 
,
// ,
document.getElementById(“根”)
);
serviceWorker.unregister();
authProvider.ts:

import { MsalAuthProvider, LoginType } from "react-aad-msal";

const config = {
  auth: {
    authority:
      "https://login.microsoftonline.com/<MyTenantId>",
    clientId: "<MyClientId>",
    redirectUri: "http://localhost:3000",
  },
  cache: {
    cacheLocation: "localStorage" as
      | "localStorage"
      | "sessionStorage"
      | undefined,
    storeAuthStateInCookie: true,
  },
};

export const authenticationParameters = {
  scopes: ["<WhatDoIEvenPutHere?>"],
};

const options = {
  loginType: LoginType.Redirect,
  tokenRefreshUri: window.location.origin,
};

export const authProvider = new MsalAuthProvider(
  config,
  authenticationParameters,
  options
);
从“react aad msal”导入{MsalAuthProvider,LoginType};
常量配置={
认证:{
授权:
"https://login.microsoftonline.com/",
客户ID:“,
重定向URI:“http://localhost:3000",
},
缓存:{
cacheLocation:“localStorage”作为
|“本地存储”
|“会话存储”
|未定义,
是的,
},
};
导出常量authenticationParameters={
作用域:[“”],
};
常量选项={
loginType:loginType.Redirect,
tokenRefreshUri:window.location.origin,
};
export const authProvider=新的MsalAuthProvider(
配置,
身份验证参数,
选择权
);
我们的目标是将我的API和React应用程序锁定在Azure AD身份验证之后,这样您就必须在我的租户上才能访问它们中的任何一个。 用户将通过客户端中的组件重定向到Microsoft登录页面。登录后,他们将获得对React应用程序以及API端点的访问权

问题是,这可能吗?如何在Azure中进行注册?客户机注册一次,API注册一次?还是两个应用程序都引用的一个注册?示波器呢?公开API

编辑:

我。。。你觉得我明白了吗

在Azure中注册一次

以SPA身份验证http://localhost:3000 作为重定向URI。 选中隐式授权下的“访问令牌”和“ID令牌”

公开应用程序ID为URI“API://(guid)”的API 添加作用域:任意命名-我使用了“api”,所以它显示为“api://(guid)/api”

API权限->添加权限->我的API->选择应用程序并检查先前添加的范围

在authProvider.ts中放入作用域:[“(guid)/(YourScopeName)”],因此我的是[“(guid)/api”]

它现在似乎起作用了。在postman中,我可以输入我从登录中获得的承载令牌,并获取数据,当我禁用它时,我将获得401。这就是我想要的


对于阅读本文的任何人,请让我知道我是否做了任何错误或不可取的事情。

来自我在原始帖子中的编辑:

在Azure中注册一次

以SPA身份验证http://localhost:3000 当你