Search code examples
asp.netasp.net-web-apiauthorize

How to consume a secure Rest MVC web api


I'm just a beginner on the .NET world and I've created a web api (.NET 4.5.2) and I'm using the annotation [Authorize] above my controllers like shown below:

[Authorize]
public class PhasesController : ApiController
{
    private TestReportEntities db = new TestReportEntities();

    // GET: api/Phases
    public IQueryable<Phase> GetPhase()
    {
        return db.Phase;
    }
}

I've already created my DB and I'm using the default tables that the web.api uses to manage the access, as you can see on this image:

My tables

I've already done a method to request to my web api, in another project/solution, it's working fine when I remove the annotation [Authorize] from my web api controllers.

this is an example about how I'm requesting my api:

public int GetCurrentIdPhase(int idProject)
    {
        int phaseId = -1;

        WebRequest request = WebRequest.Create(string.Concat(URL, string.Format("api/phases/?idProject={0}", idProject)));

        using (var resp = (HttpWebResponse)request.GetResponse())
        {
            using (var reader = new StreamReader(resp.GetResponseStream()))
            {
                string objText = reader.ReadToEnd();
                var phase = JsonConvert.DeserializeObject<List<Phase>>(objText);
                phaseId = phase[0].id;
            }
        }

        if (phaseId != -1)
        {
            return phaseId;
        }
        else
        {
            throw new Exception("Phase not found");
        }
    }

At the end of the day my questions are:

  1. How can I request a token to my api (POST - www.myApi/token) using the example above?
  2. How can I use the token, once I've got it, on every request to my API?

if you can help me I would really appreciate it.

Thanks.


Solution

  • I've created a method to get the Token from my Web API, this is the method:

    var request = (HttpWebRequest)WebRequest.Create(string.Concat(URL, "token"));
    
                    var postData = "grant_type=password";
                    postData += string.Format("&userName={0}", user);
                    postData += string.Format("&password={0}", pass);
                    var data = Encoding.ASCII.GetBytes(postData);
    
                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.ContentLength = data.Length;
    
                    using (var stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
    
                    var response = (HttpWebResponse)request.GetResponse();
    
                    string objText = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    var requestedToken = (JObject)JsonConvert.DeserializeObject(objText);
                    token = string.Concat(token, requestedToken["access_token"].Value<string>());
    

    And to request something to my API all I need to do is just add the token on the header of all requests like shown on the line below:

    request.Headers.Add(HttpRequestHeader.Authorization, getToke());
    

    Hope it can help someone else who is beginning to work with .NET web API like me.

    Regards.