DotNetOpenAuth detect fetch request like google - asp.net-mvc

With google, you can fetch the user's email like this:
var fetch = new FetchRequest();
fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
request.AddExtension(fetch);
and get it back like this:
var fetch = response.GetExtension<FetchResponse>();
string email = "";
if (fetch != null)
{
email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
}
When writing a provider, how can I return the values asked for?

The OpenIdProviderWebForms sample that comes with DotNetOpenAuth includes returning user attributes. Have you checked it out?

Related

Linq to Twitter - Bad Authentication data

I've the the latest version of Linq to Twitter (3.1.2), and I'm receiving the "Bad Authentication data" error with the code below:
var auth = new ApplicationOnlyAuthorizer
{
CredentialStore = new InMemoryCredentialStore
{
ConsumerKey = "xxxx",
ConsumerSecret = "xxxx"
}
};
using (var twitter = new TwitterContext(auth))
{
var users = twitter.User.Where(s => s.Type == UserType.Search && s.Query == "filter:verified").ToList();
}
I thought at first that it could be Twitter taking a while to accept my new credentials, but I used Twitter's OAuth tool with my keys, and they produced tokens without issue. Any ideas what I'm missing here?
I could not find a duplicate, as the code referenced # https://stackoverflow.com/questions/16387037/twitter-api-application-only-authentication-with-linq2twitter#= is no longer valid in the version I am running.
That query doesn't support Application-Only authorization. Here's the Twitter docs to that:
https://dev.twitter.com/rest/reference/get/users/search
Instead, you can use SingleUserAuthorizer, documented here:
https://github.com/JoeMayo/LinqToTwitter/wiki/Single-User-Authorization
Like this:
var auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore
{
ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"],
AccessToken = ConfigurationManager.AppSettings["accessToken"],
AccessTokenSecret = ConfigurationManager.AppSettings["accessTokenSecret"]
}
};
To find out what type of authorization is possible, you can visit the L2T wiki at:
https://github.com/JoeMayo/LinqToTwitter/wiki
and each API query and command has a link at the bottom of the page to the corresponding Twitter API documentation.

SAPUI5 get username/userid from OData request

I am currently focussing a problem which I thought it would be easy to solve. but I didnt. There are controls which allow us to show the username or logged in user, such as the lovely shell-headitems:
var oShell = new sap.ui.ux3.Shell("myShell", {
headerItems: [
new sap.ui.commons.TextView({
text: oController.getUserName() }),
],
});
It looks like this:
In here we define headerItems, which are in my opinion foreseen to show a username / or the currently logged in user. but how can I receive it? my idea is to get it from the odata request, which was made earlier. It requires me to enter username and password -> thus I want to read this username in my controller-method, but how?
getUserName : function() {
// return navigator.userAgent;
var model = sap.ui.getCore().getModel();
return model.getProperty('sUser'); // doesnt work :(
},
I also tried to get it from navigator.userAgent() but this information does not belong to the user.
Anybody knows how to receive it?
And yes: I searched in google and found some threads discussing about users/login but none of these threads solved my issue. Otherwise I thought about transferring sy-uname from SAP to the frontend, but how could you send a single Text? I don't want to build a complete service for this single transaction.
If you do not provide sUser and sPassword during oData-Model-Initialization it will be empty during runtime. You cannot access it from the model, though I realized an own service for this.
The username is in the sap.ui.model.odata.ODataMetadata of ODataModel.
var getUserName = function() {
var model = sap.ui.getCore().getModel();
var sUser = model.oMetadata.sUser;
// Display user logic here.
};
oModel.attachMetadataLoaded(null,getUserName);
Update answer for comment question from zyrex:
var user = new sap.ui.commons.TextView();
var getUserNameCallBack = function(userName) {
user.setText(userName);
}
oController.getUserName(getUserNameCallBack);
Controller method:
getUserName: function(callback) {
var userName = '';
$.getJSON(sServiceUrl).done(function(data) {
userName = data.d.Name;
callback(userName);
});
}

Get Twitter card from API

I would be able to retrieve HTML markup of what is stored in Twitter Card (https://dev.twitter.com/docs/cards).
Up until now I used TweetSharp library to retrieve tweets from some user's timeline. But, what is not surprising, because cards are new thing, it is not included.
Does anyone know, if it is possible to access card (data cached by Twitter crawler) with API?
The Twitter cards themselves are not exposed through the Twitter API.
What you'll need to do is make a request to the URL mentioned and examine the <head> element to see if they have the Twitter Card info in there.
Twitter apis do not provide the twitter-card info out of the box. You can extract the card info for a url by looking it up in its html. Below code in csharp gets card image src from the url-
public static TweetMedia[] GetTwitterCardDetails(string url)
{
string HTML;
using (var wc = new WebClient())
{
HTML = wc.DownloadString(url);
}
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(HTML);
HtmlNode element = doc.DocumentNode.SelectSingleNode("//meta[#name='twitter:image:src']");
if (element != null)
{
return new TweetMedia[] { new TweetMedia { url=url, media_url_https = element.Attributes["content"].Value, type = TweetTypes.TweetType.Photo.ToString() } };
}
return null;
}

logging in with different user / resource owner

i am trying to write a tool that creates entries in the google calendar.
after following the google docs and creating an client-identifier/secret in the api console, i managed to put together a client that authenticates correctly and shows my registered google calendars. right now for me it looks like my google-account is somehow tied to my client-identifier/secret. what i want to know is: how can i change the auth process so that it is possible for an other user of this tool to enter his google-id and get access to his calendars?
EDIT: in other words (used in the RFC): I want make the resource owner-part editable while leaving the client-part unchanged. but my example, although working, ties together client and resource owner.
here is my app that works fine so far:
public void Connect()
{
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = "123456123456.apps.googleusercontent.com";
provider.ClientSecret = "nASdjKlhnaxEkasDhhdfLklr";
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
var service = new CalendarService(auth);
//Events instances = service.Events.Instances("primary", "recurringEventId").Fetch();
var list = service.CalendarList.List().Fetch();
foreach (var itm in list.Items)
Console.WriteLine(itm.Summary);
}
private static readonly byte[] AditionalEntropy = { 1, 2, 3, 4, 5 };
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
var state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
var refreshToken = LoadRefreshToken();
if (!String.IsNullOrWhiteSpace(refreshToken))
{
state.RefreshToken = refreshToken;
if (arg.RefreshToken(state))
return state;
}
var authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
var frm = new FormAuthCodeInput();
frm.ShowDialog();
// Retrieve the access token by using the authorization code:
var auth = arg.ProcessUserAuthorization(frm.txtAuthCode.Text, state);
StoreRefreshToken(state);
return auth;
}
private static string LoadRefreshToken()
{
try
{
return Encoding.Unicode.GetString(ProtectedData.Unprotect(Convert.FromBase64String(Properties.Settings.Default.RefreshToken), AditionalEntropy, DataProtectionScope.CurrentUser));
}
catch
{
return null;
}
}
private static void StoreRefreshToken(IAuthorizationState state)
{
Properties.Settings.Default.RefreshToken = Convert.ToBase64String(ProtectedData.Protect(Encoding.Unicode.GetBytes(state.RefreshToken), AditionalEntropy, DataProtectionScope.CurrentUser));
Properties.Settings.Default.Save();
}
Prompt the user to enter their ClientIdentifier and ClientSecret, then pass these values to your Connect method.
i solved the problem myself.
the problem was, that i'm usually always connected to google and because i did't log out from google before my app redirected to google to get the access-token, google automatically generated the access-token for my account - skipping the part where an input-form appears where anyone could enter his/her user-credentials to let google generate an access-token for his/her account.

How to change the default values of start and count parameters when picking the companies followed by a user in linkedin?

I am making a web-application in ASP.NET. I have used oauth to get profile fields of a user. I need the names of the companies followed by the user, but the problem is that the default value is set to 20. so, if the user is following more than 20 companies i am not able to get it. Please tell me how can i modify the start and count values. Iv used this url to make the call http://api.linkedin.com/v1/people/~:(following:(people,companies,industries,news-sources),educations).. Please help asap..
var requestHeader = GetUserProfileAuthorizationHeader();
var queryString = CreateQueryString();
var request = WebRequest.Create(RequestProfileUrl + queryString);
request.Headers.Add("Authorization", requestHeader.ToString());
request.Method = HttpMethod.Get;
try
{
var response = request.GetResponse();
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
var responseText = reader.ReadToEnd();
reader.Close();
return responseText;
}
}
Here public static string RequestProfileUrl = "http://api.linkedin.com/v1/people/~:(following:(companies:(id,name,size,industry),industries))"; And the method CreateQueryString() does this queryString = "?format=xml"; whenever i try to add something like queryString = "?format=xml&start=0&count=40"; it gives error dispite the number of companies followed being more than 60.. maybe i need to pass the query parameters in between the RequestProfileUrl i.e near the company somehow..
Did you tried adding ?start=x&count=y to the url?
Probably if you're getting an error when you add query parameters to the URL, you're not adding those parameters in the way that your OAuth library expects them to be added. You need to figure out how to add the parameters so they're added to the signature generation process or your signature will be invalid and you'll get a 401 error back from the server.

Resources