.NET Core Web API和React的Active Directory身份验证

nba*_*man 1 authentication ldap active-directory reactjs .net-core

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

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

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

我什至从哪里开始?

nba*_*man 5

对我而言,第一步是设置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.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();
    }
Run Code Online (Sandbox Code Playgroud)

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

    public class AuthRequest
    {
        public string username { get; set; }
        public string password { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

现在,在我的React应用程序中,我所要做的就是使用LoginController可以从登录表单获取的用户名和密码向进行简单的提取请求。其结果将是一个智威汤逊,我可以保存到状态(但应保存的cookies: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
                })
            }
        })
Run Code Online (Sandbox Code Playgroud)

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

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

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

import * as signalR from '@aspnet/signalr';

var connection = new signalR.HubConnectionBuilder().withUrl('myHub', { accessTokenFactory: () => YOUR_JWT })
Run Code Online (Sandbox Code Playgroud)

而且,中提琴!一个能够进行授权的实时通信的.NET Core React应用程序!

  • 完美的答案。对于 2022 年和 NET6 仍然有效(服务器端略有变化 - NET6 使用“.AddJwtBearer”而不是“app.UseJwtBearerAuthentication”。谢谢。 (2认同)