使用.NET Core Web API和React进行Active Directory身份验证

编程入门 行业动态 更新时间:2024-10-28 04:20:15
本文介绍了使用.NET Core Web API和React进行Active Directory身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我不知道我是否不在正确的地方,但是我似乎找不到正确的指南来开始使用React/.NET Core 2.1 Web API和(本地)Active目录身份验证.

一般来说,我对.NET身份认证比较陌生,而对Active Directory身份认证则完全陌生.

我首先使用.NET Core 2.1 React模板并尝试向其添加auth,但是完全迷失了.

我什至从哪里开始?

解决方案

对我来说,第一步是设置JWT身份验证,如本MSDN博客文章中所述.

接下来,我必须找到一个库以用于根据Active Directory检查用户. 我选择了System.DirectoryServices.AccountManagement (适用于.NET Core).

现在,我必须创建一个具有[AllowAnonymous]属性的新控制器.我将其命名为LoginController,并创建了一个类似于以下内容的动作:

[AllowAnonymous] [HttpPost] // Notice: We get a custom request object from the body public async Task<IActionResult> Login([FromBody] AuthRequest request) { // Create a context that will allow you to connect to your Domain Controller using (var adContext = new PrincipalContext(ContextType.Domain, "mydomain")) { var result = adContext.ValidateCredentials(request.username, request.password); if (result) { // Create a list of claims that we will add to the token. // This is how you can control authorization. var claims = new[] { // Get the user's Name (this can be whatever claims you wish) new Claim(ClaimTypes.Name, request.username) }; // Read our custom key string into a a usable key object var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetSection("SOME_TOKEN").Value)); // create some signing credentials using out key var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); // create a JWT var token = new JwtSecurityToken( issuer: "mydomain", audience: "mydomain", claims: claims, // the claims listed above expires: DateTime.Now.AddMinutes(30), // how long you wish the token to be active for signingCredentials: creds); Since we return an IActionResult, wrap the token inside of a status code 200 (OK) return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) }); } } } } // if we haven't returned by now, something went wrong and the user is not authorized return Unauthorized(); }

AuthRequest对象可能看起来像这样:

public class AuthRequest { public string username { get; set; } public string password { get; set; } }

现在,在我的React应用程序中,我要做的就是使用用户名&向LoginController发出一个简单的获取请求.我可以从登录表单中获得的密码.结果将是一个我可以保存到状态的JWT(但应保存到cookie: react-cookie库变得无关紧要.

fetch(`login`, { method: "POST", headers: { 'content-type': 'application/json', 'accept': 'application/json', }, body: JSON.stringify({this.state.username, this.state.password}) }).then((response) => { if (response.status === 401) { // handle the 401 gracefully if this user is not authorized } else { // we got a 200 and a valid token response.json().then(({ token }) => { // handle saving the token to state/a cookie }) } })

您现在可以将[Authorize]属性添加到.NET Core应用程序中的任何控制器,并在传递JWT时向其发出获取请求 来自您的React客户端的strong>,如下所示:

await fetch(`someController/someAction`, { method: 'GET' headers: { 'content-type': 'application/json', 'authorization': `Bearer ${YOUR_JWT}` } }) .then(response => doSomething());

如果要将此JWT与SignalR一起使用 Hub,请将[Authorize]属性添加到.NET Core项目中的Hub中.然后,在您的React客户端中,当您实例化与集线器的连接时:

import * as signalR from '@aspnet/signalr'; var connection = new signalR.HubConnectionBuilder().withUrl('myHub', { accessTokenFactory: () => YOUR_JWT })

而且,中提琴!.具有授权的实时通信功能的.NET Core React应用程序!

I don't know if I'm just not looking in the right places, but I cannot seem to find the right guidance on where to begin working with React / .NET Core 2.1 Web API and (on-prem) Active Directory authentication.

I'm relatively new to .NET authentication in general, and completely new to Active Directory authentication.

I started by using the .NET Core 2.1 React template and attempting to add auth to it, but got completely lost.

Where do I even start?

解决方案

For me, step one was to set up JWT authentication, such as described in this MSDN blog post.

Next, I had to find a library to use to check a user against Active Directory. I chose System.DirectoryServices.AccountManagement (available for .NET Core).

Now, I had to create a new controller with an [AllowAnonymous]attribute. I called it LoginController, and created an action that looked like the following:

[AllowAnonymous] [HttpPost] // Notice: We get a custom request object from the body public async Task<IActionResult> Login([FromBody] AuthRequest request) { // Create a context that will allow you to connect to your Domain Controller using (var adContext = new PrincipalContext(ContextType.Domain, "mydomain")) { var result = adContext.ValidateCredentials(request.username, request.password); if (result) { // Create a list of claims that we will add to the token. // This is how you can control authorization. var claims = new[] { // Get the user's Name (this can be whatever claims you wish) new Claim(ClaimTypes.Name, request.username) }; // Read our custom key string into a a usable key object var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetSection("SOME_TOKEN").Value)); // create some signing credentials using out key var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); // create a JWT var token = new JwtSecurityToken( issuer: "mydomain", audience: "mydomain", claims: claims, // the claims listed above expires: DateTime.Now.AddMinutes(30), // how long you wish the token to be active for signingCredentials: creds); Since we return an IActionResult, wrap the token inside of a status code 200 (OK) return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) }); } } } } // if we haven't returned by now, something went wrong and the user is not authorized return Unauthorized(); }

The AuthRequest object could look something like this:

public class AuthRequest { public string username { get; set; } public string password { get; set; } }

Now, in my React app, all I have to do is make a simple fetch request to the LoginController with the user's username & password that I can get from a login form. The result will be a JWT I can save to state (But should save to cookies: the react-cookie library makes that trivial).

fetch(`login`, { method: "POST", headers: { 'content-type': 'application/json', 'accept': 'application/json', }, body: JSON.stringify({this.state.username, this.state.password}) }).then((response) => { if (response.status === 401) { // handle the 401 gracefully if this user is not authorized } else { // we got a 200 and a valid token response.json().then(({ token }) => { // handle saving the token to state/a cookie }) } })

You now have the ability to add the [Authorize] attribute to any of your controllers in your .NET Core application, and make a fetch request to it while passing your JWT from your React client, like this:

await fetch(`someController/someAction`, { method: 'GET' headers: { 'content-type': 'application/json', 'authorization': `Bearer ${YOUR_JWT}` } }) .then(response => doSomething());

If you wanted to use this JWT with a SignalR Hub, add the [Authorize] attribute to your Hub in your .NET Core project. Then, In your React client, when you instantiate the connection to your hub:

import * as signalR from '@aspnet/signalr'; var connection = new signalR.HubConnectionBuilder().withUrl('myHub', { accessTokenFactory: () => YOUR_JWT })

And, viola! A .NET Core React application capable of authorized real-time communication!

更多推荐

使用.NET Core Web API和React进行Active Directory身份验证

本文发布于:2023-11-14 08:53:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586768.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:身份验证   Web   Core   NET   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!