C# React应用程序应通过MSAL针对ASP.Net核心API项目进行身份验证
我是一个全新的反应和MSAL。我创建了一个ASP.Net核心MVC Web应用程序,它连接到Azure中的数据库。它使用.NETCore3和IdentityUI。现在我必须创建一个react Web应用程序,它使用我的MVC Web应用程序的API 我需要使用我们现有的Azure AD进行身份验证,并创建React Webapplication作为用户界面。我的问题是从哪里开始,如何开始。React应用程序应该执行登录过程。应在现有数据库中管理用户的角色。在提出要求之前,MVC应用程序通过identity UI处理注册和登录,并将用户和角色存储在azure数据库中。现在用户应该通过azure ad进行身份验证 据我所知,msal,react应用程序应该重定向到azure ad登录,并将获得令牌,azure服务在成功登录后将重定向回react应用程序 react应用程序如何向我的MVC Web应用程序提供令牌?如何更改传递和验证令牌的控制器?我是否必须在startup.cs中为MSAL或身份验证设置一些内容 我为测试目的创建了一个控制器:C# React应用程序应通过MSAL针对ASP.Net核心API项目进行身份验证,c#,asp.net-mvc,reactjs,azure-active-directory,msal,C#,Asp.net Mvc,Reactjs,Azure Active Directory,Msal,我是一个全新的反应和MSAL。我创建了一个ASP.Net核心MVC Web应用程序,它连接到Azure中的数据库。它使用.NETCore3和IdentityUI。现在我必须创建一个react Web应用程序,它使用我的MVC Web应用程序的API 我需要使用我们现有的Azure AD进行身份验证,并创建React Webapplication作为用户界面。我的问题是从哪里开始,如何开始。React应用程序应该执行登录过程。应在现有数据库中管理用户的角色。在提出要求之前,MVC应用程序通过ide
public class TestAPIController : Controller
{
private readonly IBaseRepository<Articles> _BaseRepository;
public TestAPIController(IBaseRepository<Articles> _BaseRepository)
{
this._BaseRepository = _BaseRepository;
}
// GET
[HttpGet]
[Route("GetArticles")]
public async Task<IActionResult> GetArticles()
{
return Ok(JsonConvert.SerializeObject(await _BaseRepository.GetAllAsync()));
}
}
公共类测试控制器:控制器
{
专用只读IBaseRepository_BaseRepository;
公共测试控制器(IBaseRepository\u BaseRepository)
{
此.\u BaseRepository=\u BaseRepository;
}
//得到
[HttpGet]
[路线(“获取文章”)]
公共异步任务GetArticles()
{
返回Ok(JsonConvert.SerializeObject(wait _BaseRepository.GetAllAsync());
}
}
我的startup.cs如下所示:
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<BaseContext>(opts => opts.UseSqlServer(Configuration.GetConnectionString("My_ConnectionString")));
//CookiePolice
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.SignIn.RequireConfirmedEmail = true;
options.Stores.MaxLengthForKeys = 128;
})
.AddEntityFrameworkStores<BaseContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options =>
{
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
options.LoginPath = $"/Identity/Account/Login";
options.LogoutPath = $"/Identity/Account/Logout";
options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
options.SlidingExpiration = true;
options.Cookie.Name = Common.Common_Ressources.LoginCookieName;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
});
}
// 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("/Home/Error");
app.UseHsts();
}
app.UseRouting();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseCookiePolicy();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllers();
endpoints.MapRazorPages();
});
}
}
公共类启动
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddDbContext(opts=>opts.UseSqlServer(Configuration.GetConnectionString(“My_ConnectionString”));
//库克警察
配置(选项=>
{
options.checkApprovered=context=>true;
options.MinimumSameSitePolicy=SameSiteMode.None;
});
服务.附加性(选项=>
{
options.SignIn.RequireConfirmedEmail=true;
options.Stores.MaxLengthForKeys=128;
})
.AddEntityFrameworkStores()
.AddDefaultUI()
.AddDefaultTokenProviders();
services.configureApplicationOK(选项=>
{
options.Cookie.HttpOnly=true;
options.ExpireTimeSpan=TimeSpan.FromMinutes(30);
options.LoginPath=$“/Identity/Account/Login”;
options.LogoutPath=$“/Identity/Account/Logout”;
options.AccessDeniedPath=$“/Identity/Account/AccessDenied”;
options.SlidingExpiration=true;
options.Cookie.Name=Common.Common\u resources.LoginCookieName;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddRazorPagesOptions(选项=>
{
options.Conventions.AuthorizeAreaFolder(“Identity”,“Account/Manage”);
选项.约定.授权区域页面(“标识”,“/Account/Logout”);
});
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
app.UseHsts();
}
app.UseRouting();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseCookiePolicy();
app.UseAuthorization();
app.UseEndpoints(端点=>
{
MapControllerOute(“默认值”,“{controller=Home}/{action=Index}/{id?}”);
endpoints.MapControllers();
endpoints.MapRazorPages();
});
}
}
是否有一小段代码可以告诉我react应用程序应该如何获取令牌并将其传递给MVC应用程序?能否请你提供一些细节,我必须知道之前,实施这一点?我希望我能找到实现需求目标的最佳方法。每一段代码都能帮助我更好地理解它
提前感谢主要有两个步骤 1.使用azure ad保护您的webapi(服务器)。您可以参考此(TodoListService) 2.从react应用程序(客户端)获取访问令牌,然后使用令牌访问webapi 这是一个完整的教程,介绍了如何将MSAL与React一起使用以调用Microsoft Graph
在您的情况下,唯一不同的是,您将调用自己的API,而不是调用Microsoft Graph。@TonyJu不幸的是,我需要时间进行另一个项目,因此此项目必须稍后继续。稍后我将返回此线程。我们最终通过microsoft graph获得了令牌。令牌保存在localstorage中。令牌被传递到asp.net webapi,现在验证失败。但是你的意见帮助了我。