I need to secure wcf services based on OAuth. In this case Java application is passing me a token which i need to validate based on Oauth in .Net layer and if token is passed then need to call wcf services.
I have checked several examples based on OAuth but not got any idea to achieve this . Please help me how to achieve this based on OAuth in .net.
Finally i solved this by below implementation
var authHeader = WebOperationContext.Current.IncomingRequest.Headers.GetValues("Authorization");
if (authHeader == null || authHeader.Length == 0)
{
throw new WebFaultException(HttpStatusCode.Unauthorized);
}
NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
var parts = authHeader[0].Split(' ');
if (parts[0] == "Bearer")
{
string token = parts[1];
outgoingQueryString.Add("token", token);
byte[] postdata = Encoding.ASCII.GetBytes(outgoingQueryString.ToString());
var result = string.Empty;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(oauthConfiguration.Setting.CheckUrl);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", GetAuthorizationHeader(oauthConfiguration.Setting.ClientId, oauthConfiguration.Setting.ClientSecret));
httpWebRequest.ContentLength = postdata.Length;
using (Stream postStream = httpWebRequest.GetRequestStream())
{
postStream.Write(postdata, 0, postdata.Length);
postStream.Flush();
postStream.Close();
}
var response = (HttpWebResponse)httpWebRequest.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Related
I have a Generic method SendRequest that sends request to get the OAuth token at the run time and then also uses to Send my request to the server. I have few POST and DELETE call that takes a body of list or a string. But I do not know how to set it. I know how to send the Json and by serialize it but I am having trouble how to add a body when its just a string or a list type.
public HttpWebResponse SendRequest(string postData = "", Authentication.TokenType tokenType = Authentication.TokenType.Valid)
{
var messageBody = postData;
var strResponseValue = string.Empty;
var request = (HttpWebRequest)WebRequest.Create(EndPoint);
if (EndPoint == StringBuilderUtil.GenerateRequestURL("token"))
{
request.ContentType = "application/x-www-form-urlencoded";
request.Host = "identity-authority." +
ConfigurationManager.AppSettings["TestEnvironment"];
Token = ConfigurationManager.AppSettings["GenericSpecialCode"];
}
else
{
request.ContentType = "application/json";
Token = Authentication.ChooseToken(tokenType);
}
if (HttpMethod == HttpVerb.POST)
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
// Add some headers that are common to all calls.
request.KeepAlive = true;
request.Headers.Add("Authorization", AuthType.ToString() + " " + Token);
request.Method = HttpMethod.ToString();
request.Headers.Add("Cache-Control", "no-cache");
var lbPostBuffer = Encoding.Default.GetBytes(messageBody);
request.ContentLength = lbPostBuffer.Length;
if (HttpMethod == HttpVerb.POST)
{
var PostStream = request.GetRequestStream();
PostStream.Write(lbPostBuffer, 0, lbPostBuffer.Length);
PostStream.Close();
}
return request.GetResponse() as HttpWebResponse;
}
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/ec6hh.png
how to add a body when its just a string or a list type.
If you are sending a string you don't have to do much apart from encoding and putting it into the stream.
list type goes the same way as object. You have to serialize it first.
There is logic already for the last two things.
var lbPostBuffer = Encoding.Default.GetBytes(messageBody);
request.ContentLength = lbPostBuffer.Length;
if (HttpMethod == HttpVerb.POST)
{
var PostStream = request.GetRequestStream();
PostStream.Write(lbPostBuffer, 0, lbPostBuffer.Length);
PostStream.Close();
}
I assume serialization happens before calling SendRequest method and if you are using Newtonsoft.Json it can be done with JsonConvert.SerializeObject
I have managed to successfully read my Facebook account by using the following code:
IAuthorizationState authorization = client.ProcessUserAuthorization();
if (authorization == null)
{
// Kick off authorization request
client.RequestUserAuthorization();
}
else
{
var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken));
Session["access_token"] = authorization.AccessToken;
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var graph = FacebookGraph.Deserialize(responseStream);
this.nameLabel.Text = HttpUtility.HtmlEncode(graph.Name);
}
}
}
I am now trying to POST to my Facebook news feed and I am struggling to find a guide to help me through it. I have tried to start it myself and for some reason it seems to throw back a 400: Bad Request error.
var request = WebRequest.Create("https://graph.facebook.com/me/feed?");
var postdata = "message=hello";
postdata += "&access_token" + Session["access_token"].ToString();
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();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Can anyone help me understand why my code is returning the error?
Use http://facebooksdk.net/ to make your job simple. Store access token and reuse for every request till it gets expired.
I am trying to make a simple call to a authorization Server with OAuth 2.0.
And I am very new to OAuth 2.0.
How do I make a call to the Authorization Server to get back my access token to send in the request header of request (if I am wording that correctly).
Below is what I have, Thanks in advance to any help.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Uri);
request.Method = "POST";
var uri = new Uri(Uri);
string postData = output;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
IAuthorizationState authorization = null;
AuthorizationServerDescription serviceDecription = new AuthorizationServerDescription
{
AuthorizationEndpoint = uri,
};
WebServerClient client = new WebServerClient(serviceDecription, Key, Secret);
client.AuthorizeRequest(request, authorization);
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
sr.ReadToEnd();
}
}
else
{
dataStream.Close();
response.Close();
}
}
What AS? how do users authenticate?
Typically, OAuth2 flows require user interaction with a browser (like described in this doc). It'd be great if you could add more context to what you are trying to do.
There are plenty of frameworks that you could use to avoid having to deal with lower level details of OAuth.
i used following code to get the access token from code as below
String code = HttpContext.Current.Request["code"];
string redirecturl = HttpContext.Current.Request["url"];
string Url = "https://accounts.google.com/o/oauth2/token";
string grant_type = "authorization_code";
string redirect_uri_encode = UrlEncodeForGoogle(url);
string data = "code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type={4}&access_type={5}";
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
string param = string.Format(data, code,configurationInfo.oauthclientid , configurationInfo.oauthclientsecretid, redirect_uri_encode, grant_type, "offline");
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
i am getting response as
The remote server returned an error: (400) Bad Request.
i do not know where i went wrong
waiting for your valuable comments
Google also provides a higher level library for accessing its services. I find it makes it much easier to work with its APIs.
http://code.google.com/p/google-api-dotnet-client/
I'm coding a C#.Net WPF 4.0 application that connects to Facebook and Twitter via oauth. With Facebook Graph API, I'm able to authorize, sign-in with oauth, exchange a temporary access_token to a almost persistent access token, and then, fetch any data only by adding the access_token next to my query, or posting on the wall, like this: [http://Url/query/access_token], and all of this without any SDK or any other library.
I tried to do the same with Twitter but I'm all mixed-up. I've been searching for examples on how to fetch some Json data the same way I do in Facebook, but I found nothing, probably because I don't know what to search. What is the flow that I need to follow to be able to make queries with only a direct url and a token?
you should do the following:
Get access token for the user: https://dev.twitter.com/docs/auth/obtaining-access-tokens
Use one of the REST APIs: https://dev.twitter.com/docs/api
Generate OAuth header and insert it into your request. Below is code from my app which uploads tweet and images into twitter - but GET requests will be similar. NOTE: I'm using 3rd-party OAuth class from https://cropperplugins.svn.codeplex.com/svn/Cropper.Plugins/TwitPic/OAuth.cs
var oauth = new OAuth.Manager();
oauth["consumer_key"] = Settings.TWITTER_CONSUMER_KEY;
oauth["consumer_secret"] = Settings.TWITTER_CONSUMER_SECRET;
oauth["token"] = item.AccessToken;
oauth["token_secret"] = item.AccessSecret;
var url = "https://upload.twitter.com/1/statuses/update_with_media.xml";
var authzHeader = oauth.GenerateAuthzHeader(url, "POST");
foreach (var imageName in item.Images.Split('|'))
{
var fileData = PhotoThubmnailBO.GetThumbnailForImage(imageName, ThumbnailType.FullSize).Photo;
// this code comes from http://cheesoexamples.codeplex.com/wikipage?title=TweetIt&referringTitle=Home
// also see http://stackoverflow.com/questions/7442743/how-does-one-upload-a-photo-to-twitter-with-the-api-function-post-statuses-updat
var request = (HttpWebRequest) WebRequest.Create(url);
request.Method = "POST";
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.Headers.Add("Authorization", authzHeader);
string boundary = "~~~~~~" +
Guid.NewGuid().ToString().Substring(18).Replace("-", "") +
"~~~~~~";
var separator = "--" + boundary;
var footer = "\r\n" + separator + "--\r\n";
string shortFileName = imageName;
string fileContentType = GetMimeType(shortFileName);
string fileHeader = string.Format("Content-Disposition: file; " +
"name=\"media\"; filename=\"{0}\"",
shortFileName);
var encoding = Encoding.GetEncoding("iso-8859-1");
var contents = new StringBuilder();
contents.AppendLine(separator);
contents.AppendLine("Content-Disposition: form-data; name=\"status\"");
contents.AppendLine();
contents.AppendLine(item.UserMessage);
contents.AppendLine(separator);
contents.AppendLine(fileHeader);
contents.AppendLine(string.Format("Content-Type: {0}", fileContentType));
contents.AppendLine();
// actually send the request
request.ServicePoint.Expect100Continue = false;
request.ContentType = "multipart/form-data; boundary=" + boundary;
using (var s = request.GetRequestStream())
{
byte[] bytes = encoding.GetBytes(contents.ToString());
s.Write(bytes, 0, bytes.Length);
bytes = fileData;
s.Write(bytes, 0, bytes.Length);
bytes = encoding.GetBytes(footer);
s.Write(bytes, 0, bytes.Length);
}
using (var response = (HttpWebResponse) request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception(response.StatusDescription);
}
}
}