Individual User Account between MVC and WebApi projects

4

I have an MVC project with Individual User Accounts, I use Roles for access management and everything works fine. I recently had the need to create a file manager on another server, I created a WEB API project and I communicate via HttpClient, the connection works but how do I validate access in the WEB API based on the user already logged in the MVC project? >

Follow the connection that I use to delete a file.

MVC 5:

    [Authorize(Roles = "DeleteFile")]
    public ActionResult Delete(int id)
    {            
        HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = true };
        using (var cliente = new HttpClient(handler))
        {
            string urlAPI = ConfigurationManager.AppSettings["URL_WEBAPI"];
            urlAPI = string.Format("{0}delete//{1}", urlAPI, id);

            var result = await cliente.DeleteAsync(urlAPI);
            if (!result.IsSuccessStatusCode)
                return false;
        }
    }

WEB API

    [RoutePrefix("files")]
    public class FileController : ApiController
    {  
        [HttpDelete, Route("delete/{id}")]
        public async Task<IHttpActionResult> Delete(int id)
        {
            HttpStatusCode result = await FileBLL.DeleteFileAsync(id);
            return StatusCode(result);
        }
    }

If I try to use the [Authorize] in the WEB API the connection does not work, is there any way to keep the login in my MVC project and in the connection via HttpClient the WEB API understand that there is a user in context?     

asked by anonymous 04.06.2017 / 18:52

1 answer

2

Recently I had to accomplish this. You can use Bearer Token Authentication to do this.

Basically you should generate a JWT Token that you should store in your MVC5. I generate the token when I log into the WEB API itself and then save that token to use in the requests.

When requesting the Web API you must pass this Token as Header Authorization Bearer Tokened .

Here's a great project using WEBAPI.NET FRAMEWORK using JWT authentication. link

If you are using .NET CORE, here is another very useful link. link

I hope I have helped.

    
31.08.2017 / 03:23