使用 .NET Core Web API 和 React 进行 Active Directory 身份验证 [英] Active Directory Authentication with .NET Core Web API and React

查看:17
本文介绍了使用 .NET Core Web API 和 React 进行 Active Directory 身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道我是否只是没有在正确的地方寻找,但我似乎无法找到正确的指导,说明从何处开始使用 React/.NET Core 2.1 Web API 和(本地)Active目录认证.

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.

总的来说,我对 .NET 身份验证比较陌生,对 Active Directory 身份验证完全陌生.

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

我开始使用 .NET Core 2.1 React 模板并尝试向其中添加身份验证,但完全迷路了.

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

我什至从哪里开始?

推荐答案

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

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

接下来,我必须找到一个库来检查用户是否与 Active Directory 相匹配.我选择了 System.DirectoryServices.AccountManagement(适用于 .NET Core).

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).

现在,我必须创建一个具有 [AllowAnonymous] 属性的新控制器.我将其命名为 LoginController,并创建了一个如下所示的操作:

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.com"))
            {
                    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.com",
                            audience: "mydomain.com",
                            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 使这变得微不足道).

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
                })
            }
        })

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

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());

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

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 })

还有,viola!一个能够进行授权实时通信的 .NET Core React 应用程序!

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

这篇关于使用 .NET Core Web API 和 React 进行 Active Directory 身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆