0

How to get Token from DotNetOpenAuth OAuthAuthorizationServer sample with C#? I'm running the sample provided in Github. I want to get the token, for now unsuccessfull. Always get a 400, bad request. The request I've sending is as follows:

var request = WebRequest.CreateHttp("http://localhost:50172/OAuth/Token");
        request.Method = "POST";
        request.ContentLength = 0;
        request.Headers.Add("client_id", "sampleconsumer");
        request.Headers.Add("client_secret", "samplesecret");
        request.Headers.Add("grant_type", "authorization_code");
        request.Headers.Add("code", "teste");
        request.Headers.Add("redirect_uri", "");

        WebResponse response = null;

        try
        {
            response = request.GetResponse();
        }
        catch (Exception ex)
        {
            //400 -  bad request here.
        }

I have no skills with OAuth, this is my first attempt. I've searched a lot but still a bit confuse.

2
  • First you need to set redirect uri and 2cnd you sure that you want to send this request to localhost? And your try catch stuff makes no complete sense - use response.ensuresuccess() method in the try block Commented Sep 30, 2015 at 15:19
  • I'll set redirect uri a try it again. And yes, I'm using localhost for tests purpose only. Thank you. Commented Sep 30, 2015 at 17:21

1 Answer 1

1

Do not use headers for the ClientID and the other stuff, put it into the body.

This is how I get Token with the Client Credential Grant:

using Newtonsoft.Json;

...
var url = "http://localhost:50172/OAuth/Token"
var request = WebRequest.Create(url);
request.Method = "POST";

string data = "grant_type=client_credentials&client_id=" +
    "sampleconsumer&client_secret=samplesecret";
request.ContentType = "application/x-www-form-urlencoded";
byte[] dataStream = Encoding.UTF8.GetBytes(data);
request.ContentLength = dataStream.Length;
Stream newStream = request.GetRequestStream();

newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();

WebResponse response = request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
    string result = reader.ReadToEnd();
    accessToken = JsonConvert.DeserializeObject<AccessToken>(result);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.