0

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.

Jean Carli
  • 21
  • 5
  • http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api There are lots of articles in the ToC from that page as well – BlackICE Jan 22 '16 at 23:56
  • This answer may help also: http://stackoverflow.com/a/12525250/264607 – BlackICE Jan 23 '16 at 00:01

2 Answers2

1

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.

Jean Carli
  • 21
  • 5
0

Im assuming the "GetCurrentIdPhase" call is from an unrelated app with unrealted auth - if any auth.

The difficulty here is in using Authorize and the traidtional browser authentication flow. Here's an example of changing the pipeline a bit to use a different auth form for using console/desktop apps. You don't say where you are calling GetCurrentIdPhase from so I'll have to assume either a separate app. If its a web app and you are authenticated using the same tables, then you will have to share the token between them using for ex. the url blackice provided above.

If the app is a desktop/console/etc (not another app that the user had to auth against the same tables) then you can try this approach to change how auth is done to make it easier to access.

MVC WebAPI authentication from Windows Forms

Community
  • 1
  • 1
Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71
  • Thanks for your answer Adam, you are right, my method "GetCurrentIdPhase" is in another and unrelated application. I've already seen this Link you suggested me but I couldn't understand how it can helps me. – Jean Carli Jan 23 '16 at 18:04