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

查看:141
本文介绍了使用.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身份验证我选择了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();
    }

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

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身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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