LinkedIn API 403(Forbidden) on any request url including v2 - api

in ASP.NET MVC app I'm trying to use LinkedIn for user Authentication and get the user's full profile.
I'm usin OpenAuth (DotNetOpenAuth and Microsoft.AspNet.Membership.OpenAuth)
Request for User Data
private const string UserInfoEndpoint = "https://api.linkedin.com/v1/people/~" + Fields;
var uri = BuildUri(UserInfoEndpoint, new NameValueCollection { { "oauth2_access_token", accessToken } });
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
using (var webResponse = webRequest.GetResponse())
using (var stream = webResponse.GetResponseStream())
{
if (stream == null)
return null;
using (var textReader = new StreamReader(stream))
{
var xml = textReader.ReadToEnd();
var extraData = XElement.Parse(xml)
.Elements()
.ToDictionary(
el => el.Name.LocalName,
el => el.Value
);
extraData.Add("accesstoken", accessToken);
return extraData;
}
}
This making a successful get of user basic data. but when I change the url like below then it returning 403 Forbidden
private const string UserInfoEndpoint = "https://api.linkedin.com/v2/people/~" + Fields;
or
private const string UserInfoEndpoint = "https://api.linkedin.com/v2/me/?";
I noticed about partnership program, Is that what I need to access these url's? or what is really wrong here?
This docs about the v2 API but nothing about partnership program

if you are using V1 ( till 1st march ) then this is valid :
https://api.linkedin.com/v1/people/~
This url is related to r_basicprofile
if you are moving to V2 then you can't use this url because in V2 you have to take permission from linked to use r_basicprofile
in V2 you can use : r_liteprofile for firstName,lastName,profilePicture,id
r_emailaddress for getting emailAddress
Check this : https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/migration-faq?context=linkedin/consumer/context

Related

Error in ASP.NET Core MVC and Web API project

I have an ASP.NET Core MVC and also Web API project.
This error occurs when I try to send project information to the API (of course API works fine and I do not think there is a problem):
UnsupportedMediaTypeException: No MediaTypeFormatter is available to read a "TokenModel" object of "text / plain" media content.
My code is:
public class TokenModel
{
public string Token { get; set; }
}
and in AuthController I have:
var _Client = _httpClientFactory.CreateClient("MyApiClient");
var jsonBody = JsonConvert.SerializeObject(login);
var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
var response = _Client.PostAsync("/Api/Authentication", content).Result;
if (response.IsSuccessStatusCode)
{
var token = response.Content.ReadAsAsync<TokenModel>().Result;
}
The error occurs on this line:
var token = response.Content.ReadAsAsync<TokenModel>().Result;
HomeController:
public IActionResult Index()
{
var token = User.FindFirst("AccessToken").Value;
return View(_user.GetAllUsers(token));
}
UserRepository:
public List<UserViewModel> GetAllUsers(string token)
{
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
var res = _client.GetStringAsync(UrlMyApi).Result;
List<UserViewModel> users = JsonConvert.DeserializeObject<List<UserViewModel>>(res);
return users;
}
Your API is returning content-type of text/plain and none of the default media type formatters(MediaTypeFormatter) which ReadAsAsync<string>() will try to use support parsing it as is. They work with JSON/XML. You can go a couple of ways but maybe the easiest is to read the content as string and deserialize it after:
var tokenJSON = response.Content.ReadAsStringAsync().Result;
var token = JsonConvert.DeserializeObject<TokenModel>(tokenJSON);
Also, as you're using the Async methods, you should be returning Task from your actions and await the result instead of using .Result as you're just creating overhead currently.
var tokenJSON = await response.Content.ReadAsStringAsync();
var token = JsonConvert.DeserializeObject<TokenModel>(tokenJSON);

PostAsync request with Array parameter on MVC Web API

I have Xamarin application that has POST request with array list of parameter and on my MVC WEB API we used code first Entity framework. Both was separated project solutions (.sln).
On my Xamarin project, I have PostAsync request which supplies List of array values.
using (var client = new HttpClient())
{
Parameter = string.Format("type={0}&param={1}",type, param[]);
var data = JsonConvert.SerializeObject(parameters);
var content = new StringContent(data, Encoding.UTF8, "application/json");
using (var response = await client.PostAsync(url, content))
{
using (var responseContent = response.Content)
{
result = await responseContent.ReadAsStringAsync();
}
}
}
Then In my Web API controller I have same parameter with my client side also.
[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Http.HttpPost]
[Route("type={type}&param={param}")]
public BasicResponse applog([FromUri] ProfilingType type , List<string> param)
{
if (ModelState.IsValid == false)
{
throw new ModelValidationException("Model state is invalid.");
}
try
{
if(type == ProfilingType.Login)
{
var command = new SendDataProfilingCommand(param);
CommandHandler.Execute(command);
}
else
{
var command = new UpdateDataProfilingCommand(type,param);
CommandHandler.Execute(command);
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
return new BasicResponse
{
Status = true,
Message = Ok().ToString()
};
}
Since I'm not with the API, I want to test it first on Postman or even in the URL. but my problem was when i Try to test it using this url below
http://localhost:59828/api/users/applog?type=1&param=[1,Caloocan,Metro Manila,Philippines,0,0]
I received this message : No HTTP resource was found that matches the request URI ......
My Question is, How can I test my Web API with List Parameter on URL or in the Postman ? and What Format I can use when sending a post request into my Xamarin PostAsync request?
You don't need to send as Content.
using (var client = new HttpClient())
{
Parameter = string.Format("type={0}&param={1}",type, param[]);
url = url + "?" + Parameter;
using (var response = await client.PostAsync(url))
{
using (var responseContent = response.Content)
{
result = await responseContent.ReadAsStringAsync();
}
}
}

How do I authenticate OneDrive for Business with Service to Service oauth2 authentication?

The tutorial for OneDrive for Business (here: https://dev.onedrive.com/auth/aad_oauth.htm)
However, I don't want the user to have to login as I'm building a web API - I want the app to login. So, I have followed the tutorial for service to service authentication (here: https://msdn.microsoft.com/en-us/library/azure/dn645543.aspx) which gets me an access token.
However, when I try to authenticate with the service I get an error saying "unsupported app only token". The code I'm using is below (btw, I'm using RestSharp):
public string GetAccessToken()
{
var client = new RestClient("https://login.microsoftonline.com/<tenant>/oauth2");
var request = new RestRequest("token", Method.POST);
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("client_id", <client_id>);
request.AddParameter("client_secret", <client_secert);
request.AddParameter("resource", "https://<tenant>-my.sharepoint.com/");
var response = client.Execute(request);
var content = response.Content;
var authModel = JsonConvert.DeserializeObject<AuthResponseModel>(content);
return authModel.AccessToken;
}
this gets me the access token
This is how I try to access my drive:
public string GetDrive()
{
var accessToken = GetAccessToken();
var client = new RestClient("https://<tenant>-my.sharepoint.com/_api/v2.0/");
var request = new RestRequest("drive", Method.GET);
request.AddHeader("Authorization: Bearer", accessToken);
var response = client.Execute(request);
var content = response.Content;
return content;
}
Does anyone have any tips? This is getting slightly maddening.

Web api token based authentication:- Failed to decode token from base64 string to get user name and password

I am using Web Api Token Based Authentication using OWIN Middleware; the token is generated successfully but i can't decode it; e.g. i cannot extract user name and password from it;
Here is my configuration
my start up code
var oAuthAuthorizationServerOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/api/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(oAuthAuthorizationServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
my code that is ued to send the token is
static async Task RunAsync(JObject token)
{
using (var client = new HttpClient())
{
client.Timeout = new TimeSpan(1000000000000);
client.BaseAddress = new Uri("http://localhost/SampleApp/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token["token_type"].ToString(),
token["access_token"].ToString());
}}
my authetication code
var authenticationSchema = httpContext.Request.Headers["Authorization"];
if (!String.IsNullOrWhiteSpace(authenticationSchema))
authentication = AuthenticationHeaderValue.Parse(authenticationSchema);
if (authentication != null)
{
var unencoded = Convert.FromBase64String(authentication.Parameter);
var userpw = Encoding.GetEncoding("iso-8859- 1").GetString(unencoded);
var creds = userpw.Split(':');
return new Tuple<string, string>(creds[0], creds[1]);
}
and the code failed when trying to decode the code from base64 string
note:- my sample token is
3K8vHKHA2ZsKfKbvzUbo4a2sat2JLzvvyxCZ0KSD6s1wUS3t3oDPXuQ89aTmGpsG4ZL8O0cr8M9EUeZGtdM6FBwR7gLFcLZkTaimFGKyyZMNce9trQavVTzs6gam6qach1rPTLv_gIYGgPmM-401PZsr89BIXw4acTpJL3KbXs8y7PQ-o-eTV2IA8euCVkqC02iEnAzmS0SwhBouISCC-HvcNpE2aNixg4JXEt8EslU
you can see the attached for the exception
As far as I can see from the code, access token is sent plain to server; but you need to encode the access token on the client side like:
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(token["token_type"].ToString(),
Convert.ToBase64String(Encoding.GetEncoding("iso-8859-1").GetBytes(token["access_token"].ToString())));
Then you can convert access token from base64 string on the server side. The access token string value you provided is not a valid Base64 string, so as expressed in the exception message.

Fastlink OAuth Process

Are there any .net sample apps that demonstrate a FastLink integration?
If not, is it possible for your to document the best way to authenticate using OAuth via .net/C# and output the correct iframe urls?
Can you please document this process without pointing me to:
This: https://developer.yodlee.com/Indy_FinApp/Aggregation_Services_Guide/Yodlee_FastLink_and_LAW_Guide/Yodlee_FastLink_Integration_Guide
Or this: https://developer.yodlee.com/Indy_FinApp/Aggregation_Services_Guide/Yodlee_FastLink_and_LAW_Guide/Yodlee_FastLink_Product_Guide
I've managed to get the 'Add Account' FastLink working successfully in the developer portal using C#.
Code is pasted below, I can add more detail if you need it.
public static string GetAddAccountFastLinkUrl()
{
var oauthAccessToken = (JObject)JsonConvert.DeserializeObject(GetYodleeRestResult("jsonsdk/OAuthAccessTokenManagementService/getOAuthAccessToken", new Dictionary<string, object>()
{
{"cobSessionToken", cobSessionToken},
{"userSessionToken", userSessionToken},
{"bridgetAppId", "10003200"}
}));
var oauth = new OAuth.OAuthBase();
var nonce = string.Empty;
var ts = oauth.GenerateTimeStamp();
var urlParams = "?access_type=oauthdeeplink&displayMode=desktop";
var baseUrl = "https://fastlink.yodlee.com/appscenter/fastlinksb/linkAccount.fastlinksb.action";
var url = new Uri(baseUrl + urlParams);
var consumerKey = "a458bdf184d34c0cab7ef7ffbb5f016b";
var consumerSecret = "1ece74e1ca9e4befbb1b64daba7c4a24";
var token = oauthAccessToken["token"].ToString();
var tokenSecret = oauthAccessToken["tokenSecret"].ToString();
var httpMethod = "GET";
var normalizedUrl = "";
var normalizedRequestParameters = "";
var sig = string.Empty;
while (true)
{
nonce = oauth.GenerateNonce();
sig = oauth.GenerateSignature(url
, consumerKey
, consumerSecret
, token
, tokenSecret
, httpMethod
, ts
, nonce
, OAuth.OAuthBase.SignatureTypes.HMACSHA1
, out normalizedUrl
, out normalizedRequestParameters);
if (!sig.Contains('+'))
{
break;
}
}
var fastLinkUrl = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + sig;
return fastLinkUrl;
}
For the error you are receiving:
I keep getting this error after attempting OAuth and browsing to the
fastlink page
?oauth_token=e9784744d0ff4ce09a47a3c88e15097e&oauth_error_problem=system_error&o‌​auth_error_code=415&gws_rd=ssl
If you are already a customer then,I would suggest you to file a Service Request using Yodlee Customer Care tool.
Apart from that here are few suggestions:
Please look out for any extra space or characters while creating OAUTH signature if there would be something unwanted characters or white spaces even then it will not work.