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

标签 reactjs authentication active-directory .net-core ldap

我不知道我是否只是没有找对地方,但我似乎找不到关于从哪里开始使用 React/.NET Core 2.1 Web API 和(本地)Active Directory 身份验证的正确指南。

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

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

我从哪里开始?

最佳答案

对我来说,第一步是到 设置 JWT 身份验证 , such as described in this MSDN blog post .

接下来,我不得不查找用于根据 Active Directory 检查用户的库 . I chose System.DirectoryServices.AccountManagement (可用于 .NET Core)。

现在,我不得不创建一个新的 Controller [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();
    }
AuthRequest对象可能如下所示:
    public class AuthRequest
    {
        public string username { get; set; }
        public string password { get; set; }
    }

现在,在我的 React 应用程序中,我所要做的就是 发出一个简单的获取请求 LoginController使用我可以从登录表单获取的用户用户名和密码。结果将是我可以保存到状态的 JWT(但应该保存到 cookie:the react-cookie library 使这变得微不足道)。
        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 应用程序中的任何 Controller 的属性,以及 发出获取请求 到它同时 通过您的 JWT 从你的 React 客户端,像这样:
await fetch(`someController/someAction`, 
  {  
      method: 'GET'
      headers: {
          'content-type': 'application/json',
          'authorization': `Bearer ${YOUR_JWT}`
      }
  })
  .then(response => doSomething());

如果您想 将此 JWT 与 SignalR 一起使用 Hub ,添加 [Authorize]归因于您的 Hub在您的 .NET Core 项目中。然后,在您的 React 客户端中,当您实例化与集线器的连接时:
import * as signalR from '@aspnet/signalr';

var connection = new signalR.HubConnectionBuilder().withUrl('myHub', { accessTokenFactory: () => YOUR_JWT })

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

关于reactjs - 使用 .NET Core Web API 和 React 进行 Active Directory 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52104413/

相关文章:

reactjs - 未定义的“_isMockFunction”

c# - 如何在 C# 中改进/简化用户登录 SELECT * FROM MySQL?

c# - 简单登录 C# 和 MySQL Web 应用程序

java - 使用 JNDI 连接到 AD - 为什么必须以用户名@域的格式提供安全主体?

javascript - 限制 Reducer 的结果

javascript - 按行 react chop 文本

javascript - 使用 ReactJS 在 ES6 类中嵌套 "this"绑定(bind)

java - 套接字认证服务器?

powershell - 查询 Azure Active Directory 的 UPN 和主 SMTP 地址,然后导出到 CSV

powershell - 查明安全帐户管理器 (SAM) 名称是用户还是组