I am creating a web app for a project. I want to allow my users to post there blogs onto twitter using the twitter API. they will generate a blog inside my website and if they would like to share their blog via twitter. No so much testing if the Twitter API works, more as if it works inside of my website, as in if my syntax is appropriate, and if how i am incorporating it is correct. Its for a class project.
Assuming you are using C# / ASP.NET, you would be writing a class to make your API calls which can be tested independently. I would suggest downloading the open source Twitterizer DLL and plugging that into your web project, mostly for the OAuth implementation.
So, if you were posting a Tweet, you could write a static method as follows:
public static bool CreateTweet(Twitterizer.OAuthTokens tokens, string tweetText)
{
var response = Twitterizer.TwitterStatus.Update(tokens, text);
return response.Result == Twitterizer.RequestResult.Success;
}
And your test code would look like this:
void Test()
{
var tokens = new Tw.OAuthTokens
{
_accessToken,
_accessTokenSecret,
_consumerKey,
_consumerSecret,
};
var testTweet = "test tweet text";
CreateTweet(tokens, testTweet);
}
You would need to obtain the tokens either via Twitter's login process or have them stored if you don't expect users to log in.
And then basically the test code above would be moved into the appropriate piece of code-behind in your ASP.NET application and it should just work!
Related
I am trying to migrate OAuth server code written for .Net Framework 4.5 to .Net Core 3.1. The original code pretty much looks like this. It implements the IAuthorizationServerHost interface. It makes sense to me that it has some functions that the server should implement (like CreateAccessToken that generates and returns a token).
But for .Net Core 3.1, DotNetOpenAuth is not available. So I searched around and found apparently the best solution IdentityServer4 along with many other tutorials (Tut1 Tut2 etc.). But all those looked to me as if they have just implemented the Identity Server (basically just login, logout and register). I don't see how is the token been issued.
My controller class in .Net Framework 4.5 looks like this. A successful login is usually followed by oauth/authorize route that provisions the token and redirects back to the third party.
public class OAuthController : Controller
{
// OAuth2AuthorizationServer is an implementation if IAuthorizationServerHost
private readonly AuthorizationServer authorizationServer = new AuthorizationServer(new OAuth2AuthorizationServer());
public ActionResult Token()
{
var result = this.authorizationServer.HandleTokenRequest(this.Request).AsActionResult();
return result;
}
[Authorize, AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult Authorize()
{
var request = this.authorizationServer.ReadAuthorizationRequest(this.Request);
if (request == null)
{
throw new HttpException((int)HttpStatusCode.BadRequest, "Bad request");
}
var response = authorizationServer.PrepareApproveAuthorizationRequest(request, User.Identity.Name);
return authorizationServer.Channel.PrepareResponse(response).AsActionResult();
}
}
I am new to this authentication stuff - have a quite hollow understanding of the concepts. I am struggling to understand the OAuth server related code flow in these tutorials.
So how can I use those packages to create an OAuth server in .Net Core 3.1?
I currently have a MVC site, in .NET Core, backed by a public API. My users must log in (there are no [Anonymous] controllers), and authentication is already successfully being done using the DotNetCore.Authentication provider. All that is well and good.
What I'm now trying to do (by user request) is implement functionality for a user to read and view their Outlook 365 calendar on a page within my site. It doesn't seem too hard on the surface... all I have to do is have them authenticate through microsoftonline with my registered app, and then -- once they have given approval -- redirect back to my app to view their calendar events that I am now able to pull (probably using Graph).
In principle that seems really easy and straightforward. My confusion comes from not being able to implement authentication for a single controller, and not for the entire site. All of the OAuth2 (or OpenID, or OWIN, or whatever your flavor) examples I can find online -- of which there are countless dozens -- all want to use the authorization to control the User.Identity for the whole site. I don't want to change my sitewide authentication protocol; I don't want to add anything to Startup.cs; I don't want anything to scope outside of the one single controller.
tldr; Is there a way to just call https://login.microsoftonline.com/common/oauth2/v2.0/authorize (or facebook, or google, or whatever), and get back a code or token that I can use for that user on that area of the site, and not have it take over the authentication that is already in place for the rest of the site?
For anybody else who is looking for this answer, I've figured out (after much trial and error) how to authenticate for a single user just for a short time, without using middleware that authenticates for the entire application.
public async Task<IActionResult> OfficeRedirectMethod()
{
Uri loginRedirectUri = new Uri(Url.Action(nameof(OfficeAuthorize), "MyApp", null, Request.Scheme));
var azureADAuthority = #"https://login.microsoftonline.com/common";
// Generate the parameterized URL for Azure login.
var authContext = GetProviderContext();
Uri authUri = await authContext.GetAuthorizationRequestUrlAsync(_scopes, loginRedirectUri.ToString(), null, null, null, azureADAuthority);
// Redirect the browser to the login page, then come back to the Authorize method below.
return Redirect(authUri.ToString());
}
public async Task<IActionResult> OfficeAuthorize()
{
var code = Request.Query["code"].ToString();
try
{
// Trade the code for a token.
var authContext = GetProviderContext();
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(code, _scopes);
// do whatever with the authResult, here
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex.ToString());
}
return View();
}
public ConfidentialClientApplication GetContext()
{
var clientId = "OfficeClientId;
var clientSecret = "OfficeClientSecret";
var loginRedirectUri = new Uri(#"MyRedirectUri");
TokenCache tokenCache = new MSALSessionCache().GetMsalCacheInstance();
return new ConfidentialClientApplication(
clientId,
loginRedirectUri.ToString(),
new ClientCredential(clientSecret),
tokenCache,
null);
}
I don't know if that will ever be helpful to anybody but me; I just know that it's a problem that doesn't seem to be easily solved by a quick search.
I wrote a web application using ASP .NET MVC and authorization system by default. I configured IdentityRole and input through external providers. Using the current database I have created my data context. Now I want to write a Xamarin.Android app and connect to my database, I want a simple API. But the feature that you want to access this API was only available to user with a certain role. The API is really very simple and therefore do not want to add to the draft WCF or WebAPI project. How to do it best?
First, you don't need a separate project to use Web Api; you can use both MVC and Web Api in the same project. For one off endpoints for things like in-site AJAX requests, just creating MVC actions that return JSON or XML would be fine, but if you're talking about a true API, even if it's fairly simplistic, I'd say go Web Api.
You'd protect your Web Api actions much the same as you would your MVC actions, using the [Authorize] attribute. If you need to restrict by role, you just pass a role(s) to that. However, the big difference here, especially if you're serving a mobile app, is that you'll need pass the authorization along with the request. That's generally accomplished using the Authorization header along with a bearer token. Basically, you would need to set up an endpoint that signs a user in and returns a token. Then, each subsequent request that needs authorization includes that token in the header.
I want to finish and to fully answer this question and close this topic. I've been searching for how to add the ability for a mobile client to connect to an existing site on ASP.NET MVC. In my search, I came across a great article Justin Hyland on March 2, 2014
In principle, everything in this article is well and clearly written, but I want to make a tiny contribution for clarity.
Under Setup WebAPIConfig stated that the need
added in the following code to the WebApiConfig Register method
But if we consider the case ASP.NET MVC we don't have such file. It's all very simple, you just need such a file to create the folder App_Start. The contents of the file can be left exactly as it is in the article.
To get rid of the bugs which will inevitably appear we need to install two nuget package: Microsoft.AspNet.WebApi and Microsoft.AspNet.WebApi.Owin.
Excellent! Now we can turn to the method to obtain the token and then adding the token to the query we can get the needed data closed by the attribute [Authorize].
A small remark. If You need to access a method which is closed for a specific role that to the Authenticate method from the article should add a few lines of code. Immediately after the line:
identity.AddClaim(new Claim(ClaimTypes.Name, user));
add the line:
identity.AddClaim(new Claim(ClaimTypes.Role, role));
where role you can get the following, for example:
var userIdentity = UserManager.FindAsync(user, password).Result;
var role = RoleManager.FindById(userIdentity.Roles.First().RoleId).Name;
User and password you have to send a request.
I also want to give an example of code which will send request and receive response. To not have to look for and immediately start coding.
async Task<string> GetToken(string userName, string password)
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>( "user", userName ),
new KeyValuePair<string, string> ( "password", password )
}
);
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsync(APP_PATH + "/Authenticate", content);
var result = await response.Content.ReadAsStringAsync();
return result;
}
}
async Task<string> GetUserInfo(string token)
{
using (var client = CreateClient(token))
{
var response = await client.GetAsync(APP_PATH + "/ValidateToken");
return await response.Content.ReadAsStringAsync();
}
}
HttpClient CreateClient(string accessToken = "")
{
var client = new HttpClient();
if (!string.IsNullOrWhiteSpace(accessToken))
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}
return client;
}
All have only to call the appropriate methods in the correct order. I hope that is useful to someone.
P.S.
If You create a new project in Visual Studio to get this functionality you just need to tick:
We are currently working on the finishing touches of an application which uses Phonegap and have hit some issues with the Blackberry port.
So far, we've been reviewing the content available online and can't find a really finale answer to this. Seems like the "right" way to make and oauth authentication process for either Twitter, Facebook or Foursquare would be to use the ChildBrowser plugin, instantiate a window and then use that to handle the process.
Rightly so, there seems to be a lack of a ChildBrowser plugin for Blackberry. We've been looking so far at a couple of private projects on Github that look like they build/use that capability but we are not sure on how to control the created window.
Most (or all?) of those plugins refer to invoking the native Blackberry browser to handle the URLS, but then how would be manage to work on the callbacks, get the tokens and close the windows since it's another process.
For example, we have this concept code:
function openWindow() {
if (typeof blackberry !== 'undefined') {
app_id = SOMETHING_HERE;
redirect = 'http://www.facebook.com/connect/login_success.html';
url = 'https://graph.facebook.com/oauth/authorizeclient_id='+app_id+'&redirect_uri='+redirect+'&display=touch&scope=publish_stream';
var args = new blackberry.invoke.BrowserArguments(url);
blackberry.invoke.invoke(blackberry.invoke.APP_BROWSER, args);
}
}
Which works for opening the URL, but that's it. Is there a way to get a handle on the window and inject some listener to events? What should be our correct approach?
Thanks!
I am not PhoneGap user, but we did have to handle a very similar scenario - native app invokes the mobile browser to prompt the oAuth flow and then be able to handle a callback to the aative app.
This is possible on the BlackBerry using the BrowserContentProviderRegistry API. You can register your app to be invoked whenever a particular MIME type is returned to the browser. Sounds complicated but its fairly straightforward when all the pieces are in play.
Here is the rough flow -
Native app invokes browser to the oAuth page. This is part is easy and seems like you got this part.
The oAuth redirect needs to go to a URL that you can control. Something like http://mycompany.com/oAuthRedirectHandler.asp.
The oAuthRedirectorHandler.asp has simple code like this (we chose classic ASP but this can be done in PHP or any language, you can also ignore the Android block below) -
<html><body>
<h1>Redirect page</h1>
If you are not re-directed, please open the application manually.
<% strUA = Request.ServerVariables("HTTP_USER_AGENT")
if (InStr(strUA, "BlackBerry")) then
Response.Write("Opening appplication on BlackBerry")
Response.ContentType="application/x-MyCustomApp"
elseif (InStr(strUA, "Android")) then
Response.Write("Opening appplication on Android")
Response.Redirect("MyCustomApp://mycompany.com")
end if %>
</body> </html>
In your BlackBerry code you want a new BrowserContentProvider like this -
final class CustomBrowserProvider extends BrowserContentProvider{
String[] ACCEPT = new String[]{"application/x-MyCustomApp};
String appName;
CustomBrowserProvider(String appName){
this.appName = ApplicationDescriptor.currentApplicationDescriptor().getModuleName();
//cache this appName from the constructor in the invocation code below.
}
public String[] getSupportedMimeTypes() { return ACCEPT;}
public String[] getAccept(RenderingOptions context){return ACCEPT;}
public BrowserContent getBrowserContent( BrowserContentProviderContext context) throws RenderingException {
//this is where the callback happens
//this is happening in a separate process, raise your main app here using the appName that got passed in
//I dont have a sanitized ready to go sample to post here on how to do this, but not too complicated
//as a hint use the ApplicationDescriptor and CodeModuleManager classes
return null;
}
}
Now, in your application initialization, register this new BrowserPlugin like this -
BrowserContentProviderRegistry converterRegistry = BrowserContentProviderRegistry.getInstance();
converterRegistry.register(new CustomBrowserProvider());
Hope this helps. This has worked pretty well for us. The one downside we've had here is that when the user returns to the browser app, they are left with an empty page and there is no good way to close that in the BB.
I am trying to do a seemingly simple thing, but having trouble accomplishing it. I am trying to automate the posting on my Facebook wall. Basically I have a ASP.NET MVC website that I post updates on, and I want to automatically submit the post to my wall.
I see a lot of stuff on FB Connect and getting data, I just want to post.
Thanks for any help or guidance.
UPDATE: Just trying to resurrect and be a little more clear in my description as I am not getting anywhere.
I have a page that I want with a text box and a button. When I submit the form I want the message to post to my Facebook wall. I thought it was Facebook Connect, but I am getting no where as to how to automatically authenticate myself and post to my wall.
I would like to use C# rather than JavaScript.
private const string ApplicationKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
private const string SecretKey = "XXXXXXXXXXXXXXXXXXXXXXXXXX";
private Facebook.Rest.Api _facebookAPI;
private Facebook.Session.ConnectSession _connectSession;
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection form)
{
_connectSession = new Facebook.Session.ConnectSession(ApplicationKey, SecretKey);
if (_connectSession.IsConnected())
{
_facebookAPI = new Facebook.Rest.Api(_connectSession);
string response = _facebookAPI.Stream.Publish("This is a generated test");
}
return View();
}
}
The IsConnected() is returning false.
Any help is appreciated.
This code was right, the problem was that I had not added my application to my profile. Dumb miss, but my thought is that the whole thing is poorly documented. I have another issue with offline access, but that is for a different post.
string apiKey = "XXXXXXXXX";
string apiSecret = "XXXXXXXXXXXX";
Facebook.Session.ConnectSession._connectSession = new Facebook.Session.ConnectSession(apiKey, apiSecret);
if (_connectSession.IsConnected)
{
Facebook.Rest.Api api = new Facebook.Rest.Api(_connectSession);
string response = api.Stream.Publish("Test", null, null, null, api.Users.Session.UserId);
}
It could be that you tested your Website on your localhost. The Facebook Cookie is not written out, when you test your Website on localhost. See this link http://forum.developers.facebook.net/viewtopic.php?pid=247332
This might solve your problem:
Add "127.0.0.1 localhost.local" to your file
Update your FB application Connect settings to use "http://localhost.local/" URL and "localhost.local" domain.
Create an IIS Web site on port 80 with the name "localhost.local". I had to stop my default web site, which is also on port 80
Update my Visual Studio 2010 web application to use IIS with the "http://localhost.local/" url.
To see cookies, make sure to install FireCookies, along with FireBug.