Shopify and Private Applications - c#

I have created a private app for use on my website (The idea is the website will act as the front end using shopify's api to connect to the store).
When I create the application, if I edit it there is an example url which looks like this:
https://926b44aa1af222f2089ffa4988bc146b:49a28c7ccfa3b29b2a9af8019b2723cc#kudos-6.myshopify.com/admin/products.json
f you click that link, you can see the products I have set up.
Now, if I take that URL and put it into my website using jQuery $.get, I get an error stating Invalid API key or access token (unrecognized login or wrong password which is really infuriating as you can imaging.
I tried to add a header using the ApiPassword which looks like this:
"X-Shopify-Access-Token": "49a28c7ccfa3b29b2a9af8019b2723cc"
But I get the same error.
Now this is probably due to not allowing cross origin headers, etc. So I created a function in c#:
public string Get()
{
using (var wc = new WebClient())
{
return wc.DownloadString("https://926b44aa1af222f2089ffa4988bc146b:49a28c7ccfa3b29b2a9af8019b2723cc#kudos-6.myshopify.com/admin/products.json");
}
}
Which I expected to work, but it doesn't. I get the same error.
So I tried:
public string Get()
{
using (var wc = new WebClient())
{
wc.Headers.Add("X-Shopify-Access-Token", "926b44aa1af222f2089ffa4988bc146b");
return wc.DownloadString("https://926b44aa1af222f2089ffa4988bc146b:49a28c7ccfa3b29b2a9af8019b2723cc#kudos-6.myshopify.com/admin/products.json");
}
}
and guess what, I get the same error.
So I tried using the secret:
public string Get()
{
using (var wc = new WebClient())
{
wc.Headers.Add("X-Shopify-Access-Token", "e63081c23cd05b64205dbdb670d60241");
return wc.DownloadString("https://926b44aa1af222f2089ffa4988bc146b:49a28c7ccfa3b29b2a9af8019b2723cc#kudos-6.myshopify.com/admin/products.json");
}
}
Same error.
Can anyone tell me why?

So, for anyone else having this problem, here is the solution:
First, add these lines to your WebApiConfig:
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.Remove(config.Formatters.XmlFormatter);
Then, use your Api password as the access token like this:
public string Get()
{
using (var wc = new WebClient())
{
wc.Headers.Add("X-Shopify-Access-Token", "49a28c7ccfa3b29b2a9af8019b2723cc");
return wc.DownloadString("https://kudos-6.myshopify.com/admin/orders.json");
}
}
and that is it. If you do it like that, it will work.

I had a same issue and fixed it by adding a header information.. I am accessing API through windows service..
So I have created a custom app in Shopify and
I was getting authentication error as I was only passing in API Key and APi password.
You need to attach Admin API token to the header and also use API key and API password.
var restSharpClient = new RestClient(_shopifyBaseStoreURL);
restSharpClient.Authenticator = new HttpBasicAuthenticator(_privateAppAPIKey, _privateAppPassword);
restSharpClient.AddDefaultHeader("X-Shopify-Access-Token", "shpXXXX");
I also added in.when making a GET / PUT request..
restSharpRequest.Method = Method.GET;
restSharpRequest.AddHeader("content-type", "application/json");
restSharpRequest.AddHeader("Accept", "application/json");
restSharpRequest.AddHeader("X - Shopify - Access - Token", "shxxxxxxxxxxxxxxxx");

You can retrieve products using jQuery like this:
$.ajax({
type: 'GET',
url: 'http://yourshop.myshopify.com/products.json',
dataType: 'jsonp',
success: function(data) {
console.log(data);
}
});

You should STOP and quit this pattern while you are ahead. Do you not see the folly of putting your API token with access to your shop in a public website? There is nothing stopping any Tom, Dick or Jane from molesting your shop and ruining your e-commerce day.
Instead, make yourself a front-end that uses an App Proxy to access your backend goods. At least that is secure, and ensures no one can mess with your shop.

Related

How to call api get call on spotify for my user c#

Im trying to get a list of liked songs from my Spotify User via API.
I get the Access Token for the calls to make, even when im using a song ID i get the JSON response for that song.
Now the unclear part, the routing to get my user liked songs is
/me/tracks
with some additional param for the checking like limit etc...
When i make a GET call the responce is 401 not authorised
even for the normal response routing /me i get this message.
Am i missing one important step?
Here the code for calling the list
public async Task<Songs> Get_Liked_Songs(string auth_token)
{
using (var result = new HttpClient())
{
result.BaseAddress = new Uri(address_for_songs);
result.DefaultRequestHeaders.Accept.Clear();
result.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
result.DefaultRequestHeaders.Add("Authorization", $"Bearer {auth_token}");
var rez_songs = await result.GetAsync($"/v1/me/tracks");
var songs = await rez_songs.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Songs>(songs);
}
}

Getting a 404 when calling Authentication API using auth0.net

I am trying to authenticate using auth0.net (.NET client for the Auth0 API), however, I'm getting an Auth0.Core.Exceptions.ApiException error with an HTTP status code of NotFound (404).
I'm using the following code:
var client = new AuthenticationApiClient(new Uri(Auth0Url));
var authenticationRequest = new AuthenticationRequest();
authenticationRequest.ClientId = ClientId;
authenticationRequest.Username = username;
authenticationRequest.Password = password;
authenticationRequest.Connection = "Username-Password-Authentication";
AuthenticationResponse response = null;
Task.Run(async () =>
{
response = await client.AuthenticateAsync(authenticationRequest);
}).Wait();
What is wrong here? The Management API works fine and the ClientID is correct.
Just had this problem myself.
Two things.
First make sure you are using the correct API Url.
E.g.
https://<company>.au.auth0.com/api/v2
And not
https://<company>.au.auth0.com
Second Make sure you are using the base API
E.g.
https://<company>.au.auth0.com/api/v2
And not
https://<company>.au.auth0.com/api/v2/users

Retrieve instagram access token on page load

I want to show my user feed on my website and what I intend to do is to authenticate my own user account each time a user visits the page, and in that way buypass that the user have to log in to his instagram account.
My problem is that I'm having a hard time retrieving the instagram access token through a HttpWebRequest..
See the following NON working code sample:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.instagram.com/oauth/authorize?client_id=xxxxxxxxxxxxxxxxxxxxxx&redirect_uri=http://mywebsite.com&response_type=token");
request.Method = "POST";
request.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string redirectUrl = response.ResponseUri.ToString();
HttpContext.Current.Response.Write(redirectUrl);
HttpContext.Current.Response.End();
If I paste the url in my browser I get a redirect to http://mysite.com/#access_token=xxxxxxxxxxxxxx and everything seems fine, but when I try to execute the code above, I can't retrieve the correct uri due to some in between redirects before the final url.
Any help would be much appriciated..
I recommend you to use Instasharp library. InstaSharp is a C# library that wraps the Instagram API and makes it easy to write applications with Instagram data. It has a very easy method to get access token for a user. Check its API.
Unfortunately the documentation for Instasharp currently provided has a few errors. I.e. The documentation says OAuthInfo, when such a class does not exist.
Here is some code that works for me.
Notice you don't seem to need to pass a User Object at all (not sure why you would need to anyway)
Also note, that the authenticated and non authenticated methods allow you pass different params, count being the most important one. I've noticed that regardless of the count you pass, an arbitrary number of results is returned, e.g. 33 for authenticated and 13 for authenticated for the same search term. InstagramResult is my wrapper class for the object and Config holds the InstagramAuthorisationModel and InstagramAuthorisationModel holds the static keys created when signing up for a developer account.
public class InstagramService : IInstagramService
...
public InstagramConfig Config
{
get{return new InstagramConfig("https://api.instagram.com/v1", "https://api.instagram.com/oauth", InstagramAuthorisationModel.ApplicationId, InstagramAuthorisationModel.Secret, InstagramAuthorisationModel.RedirectUri);}
}
private AuthInfo UserAuthInfo()
{
return new AuthInfo()
{
// User =new UserInfo(){},
Access_Token = GetInstagramAccessToken()
};
}
public string GetInstagramAccessToken()
{
return _socialMediaRepository.GetInstagramAccessToken(_userApiKey);
}
public List<InstagramResult> Search(string searchTag, int count)
{
var auth = UserAuthInfo();
var tags = new InstaSharp.Endpoints.Tags.Authenticated(Config, auth);
var searchresult = tags.Recent(searchTag);
return searchresult.Data.Select(media => new InstagramResult()
{
Media = media,
image = media.Images.LowResolution.Url
})
.ToList();
}
..

How to include a basic http authentication in MVC4

I am using the new oAuthWebSecurity functionality in MVC4 to do Facebook authentication for users of the site and it works great.
However, what I would like to do is that for a specific controller only, enable basic HTTP authentication.
I have tried implementing a custom action filter (authenticationFilter) to intercept the call and do the basic authentication with custom code but the code never hits the overloads of the AuthorizationFilter.
Is there an easier way to implement this rather than creating a custom SimpleMembershipProvider?
You can use [Authorize] filter is as below.
public class BooksController : ApiController
{
[Authorize]
public IEnumerable<Book> Get()
{
var result = new List<Book>()
{
new Book()
{
Author = "John Fowles",
Title = "The Magus",
Description = "A major work of mounting tensions " +
"in which the human mind is the guinea-pig."
},
new Book()
{
Author = "Stanislaw Ulam",
Title = "Adventures of a Mathematician",
Description = "The autobiography of mathematician Stanislaw Ulam, " +
"one of the great scientific minds of the twentieth century."
}
};
return result;
}
}
For more information check Basic HTTP authentication
I hope this will help to you.
You can create custom AuthorizeAttribute to handle both authentication and authorization using basic authentication. This attribute works as a filter and will process the request before it gets to your controller action or Web API method. In the overridden OnAuthorize method you can grab the header information to perform authentication.
If you are using ajax to make request to a controller or Web API method use basic authentication to pass the credentials for authorization. This puts the credentials in the header. To do this is pretty straight forward by using the beforeSend event handler of the JQuery ajax function. Use jquery.base64.js to encode the information being sent over. Here is an example of how to do this.
getAuthorizationHeader = function (username, password) {
var authType;
var up = $.base64.encode(username + ":" + password);
authType = "Basic " + up;
};
return authType;
};
$.ajax({
url: _url,
data: _data,
type: _type,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", getAuthorizationHeader(username, password));
},
success: ajaxSuccessHandler,
error: ajaxErrHandler
});
This encodes the username/password that is sent in the header. Note that this is not enough security to rely on just the encoding as it is easy to decode. You still want to use HTTPS/SSL to make sure the information sent over the wire is secure.
On the server side you can make a custom AuthorizeAttribute that gets the credentials from the header, decodes them, and performs your authentication/authorization process. Note that there is a a a separate AuthorizeAttribute used by the Web API as opposed to the controller. Be sure to use System.Web.Http.AuthorizeAttribute as your base class when creating your custom AuthorizeAttribute if you are using Web API. They have different behaviors. The one for the controller will want to redirect to the logon page whereas the one for the Web API returns an HTTP code indicating success or failure. I return an HTTP code of Forbidden if authorization fails to distinguish a failure due to authorization as opposed to authentication so the client can react accordingly.
Here is an example method for getting the credentials from the header that can be used in the custom AuthorizeAttribute.
private bool GetUserNameAndPassword(HttpActionContext actionContext, out string username, out string password)
{
bool gotIt = false;
username = string.Empty;
password = string.Empty;
IEnumerable<string> headerVals;
if (actionContext.Request.Headers.TryGetValues("Authorization", out headerVals))
{
try
{
string authHeader = headerVals.FirstOrDefault();
char[] delims = { ' ' };
string[] authHeaderTokens = authHeader.Split(new char[] { ' ' });
if (authHeaderTokens[0].Contains("Basic"))
{
string decodedStr = SecurityHelper.DecodeFrom64(authHeaderTokens[1]);
string[] unpw = decodedStr.Split(new char[] { ':' });
username = unpw[0];
password = unpw[1];
}
gotIt = true;
}
catch { gotIt = false; }
}
return gotIt;
}
And here is the code for decoding the header data that is used in this method.
public static string DecodeFrom64(string encodedData)
{
byte[] encodedDataAsBytes
= System.Convert.FromBase64String(encodedData);
string returnValue =
System.Text.Encoding.ASCII.GetString(encodedDataAsBytes);
return returnValue;
}
Once you have the username and password you can perform your authentication and authorization using the SimpleMembership provider.

Create a Subscription in instagram with c#

I followed this link OAuth 2.0 In .NET With Instagram API, and it helped me fix my issue with getting my access token.
My code is this:
NameValueCollection parameters = new NameValueCollection
{
{"client_id", ClientId},
{"client_secret", ClientSecretId},
{"object", "user"},
{"aspect", "media"},
{"verify_token", "thisIsANormalSubscription"},
{"callback_url", CallbackURI}
};
WebClient client = new WebClient();
var result = client.UploadValues(SubscriptionURI, parameters);
SubscriptionURI = "https://api.instagram.com/v1/subscriptions".
I'm following the guide from instagram(http://instagram.com/developer/realtime/) including all the parameters for the POST request. But I only get the 400 error when it does the client.UploadValues.
PS:This is my first post, so might not be as appealing for the eye as I would wish
if you have your access token you can use this plugin I found, it gets the most recent photos from a user.
Instagram .NET
If you're using the Instasharp Client API (https://github.com/InstaSharp/InstaSharp) you can do something like this:
public InstagramConfig Config
{
get
{
return new InstagramConfig(InstagramAuthorisationModel.ApplicationId, InstagramAuthorisationModel.Secret);
}
}
public void YourSubscribeMethod(string searchTerm)
{
var result = await new Subscription(Config).CreateTag(searchTerm))
}
where InstagramAuthorisationModel is a class that holds your registered application id and secret
You can create subscriptions for Geography, (CreateGeography), User (CreateUser) and (CreateLocation) methods.

Categories

Resources