Individual User Account between MVC and Webapi projects

Asked

Viewed 311 times

5

I have a MVC project with Individual User Accounts, I use Roles for access management and everything works well. Recently I had the need to create a file manager on another server, I created a WEB API project and communicate via Httpclient, the connection works however as I perform access validations in the WEB API based on the user already logged in the MVC project?

Follow connection 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 the context?

1 answer

2

I recently had to accomplish that. You can use Bearer Token Authentication for that reason.

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

When making requests for the WEB API you must pass this Token as Header Authorization Bearer token generated.

Here is a great project using . NET WEBAPI FRAMEWORK using JWT authentication. https://github.com/cuongle/WebApi.Jwt

If you are using . NET CORE follows another very useful link. https://blogs.msdn.microsoft.com/webdev/2016/10/27/bearer-token-authentication-in-asp-net-core/

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.