Git Product home page Git Product logo

oauth-dotnetcore's Introduction

OAuth Build Status Build status nuget

Deprecated

I am no longer maintaining this fork of Daniel Crenna's vaulted OAuth library and will not be accepting pull requests.

A public domain OAuth library

Introduction

Working with OAuth 1.0a is hard. You have to get the signature handling just right, or you'll get vague, unhelpful errors from most servers that implement the specification. But OAuth is important because it's an effective way to do useful things with your user's external data without having to ask for or store their important credentials from other sources. This library provides a set of tools, centered around the OAuthRequest class, for making it easy to build applications that talk to OAuth servers.

Features

  • Battle-tested - This code has been used for over two years to make millions of requests
  • Simple API that helps reduce the complexity of making OAuth requests
  • Supports OAuth 1.0a as a standalone library - Use it wherever you need it
  • Public domain - open specifications should be free!

Usage

A Typical Workflow

Making an OAuth request involves a lot more context than other security credentials. You can find all the details of the OAuth spec at the official site, and plenty of tutorials online to determine the "What", and this library will provide the "How". In a typical OAuth workflow you need to accomplish the following things:

  • Obtain a "request token" from the OAuth server using a preset "consumer key" and "consumer secret" provided to you by the application you are consuming (i.e. Twitter, Google, etc.)

  • Use the request token data you retrieved to redirect your user to the OAuth site where they can safely enter their credentials and allow (or deny) your application's access to their data

  • Either the OAuth server then redirects back to your application using a known callback URL, or it presents a "verifier", or PIN number, to the user, that they then enter in to your application to obtain access.

  • Finally, your application uses the verification information provided in the callback or user entry in the previous step, to obtain an "access token". This access token can then be used to make requests to the OAuth provider's API and retrieve user data on your user's behalf

Making Requests

You can either create a new OAuthRequest instance yourself and add the appropriate properties that make up your request, or use the static methods if you need a little help with default settings and what's required for each request type. You always need to provide your consumer key, consumer secret, and set the RequestUrl property that you intend to make the request with. Since this library only prepares credentials, you can send the request using whatever HTTP client you prefer.

// Creating a new instance directly
OAuthRequest client = new OAuthRequest
{
    Method = "GET",
    Type = OAuthRequestType.RequestToken,
    SignatureMethod = OAuthSignatureMethod.HmacSha1,
    ConsumerKey = "CONSUMER_KEY",
    ConsumerSecret = "CONSUMER_SECRET",
    RequestUrl = "http://twitter.com/oauth/request_token",
    Version = "1.0a",
    Realm = "twitter.com"
};

// Creating a new instance with a helper method
OAuthRequest client = OAuthRequest.ForRequestToken("CONSUMER_KEY", "CONSUMER_SECRET");
client.RequestUrl = "http://twitter.com/oauth/request_token";

Once you have an OAuthRequest instance, you can obtain either the appropriate HTTP Authorization header value, or the URI query string value, using one of two methods. Most OAuth providers support both of these authentication style specs.

// For HTTP header authorization
string auth = client.GetAuthorizationHeader();

/// For URL query authorization
string auth = client.GetAuthorizationQuery();

From this point, you just need to pass this information to your HTTP client to send to the endpoint you specified in RequestUrl; remember the HTTP method and endpoint must match exactly, since they are used in the signature generation process.

// Using HTTP header authorization
string auth = client.GetAuthorizationHeader();
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(client.RequestUrl);           

request.Headers.Add("Authorization", auth);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// Using URL query authorization
string auth = client.GetAuthorizationQuery();
var url = client.RequestUrl + "?" + auth;
var request = (HttpWebRequest)WebRequest.Create(url);
var response = (HttpWebResponse)request.GetResponse();

XAuth

This library also supports XAuth, which is a client authenticating form of OAuth that allows you to pass a user and password and obtain an access token in one step; this is useful for mobile applications, or when migrating from basic security to OAuth, and normally requires further steps from the OAuth provider (i.e. applying for access), as this certainly defeats the purpose of OAuth beyond limiting credential input to a single time use.

OAuthRequest client = OAuthRequest.ForClientAuthentication("CONSUMER_KEY", "CONSUMER_SECRET", "USERNAME", "PASSWORD");
client.RequestUrl = "https://api.twitter.com/oauth/access_token";

OAuth Echo

Sometimes applications need to make third-party requests through a security "double hop". For example, an image posting service that posts to Twitter but also has an API, needs a way to authorize that the user of their API has the same credentials as Twitter's API. OAuth Echo is accomplished by using special HTTP headers that point to a specific endpoint at the main provider's site.

// Get an OAuthRequest instance for the main site's echo endpoint
OAuthRequest client = OAuthRequest.ForProtectedResource("GET", "CONSUMER_KEY", "CONSUMER_SECRET", "ACCESS_TOKEN", "ACCESS_TOKEN_SECRET");
client.RequestUrl = "https://api.twitter.com/account/verify_credentials.json";
var auth = client.GetAuthorizationHeader();

// Make the request to the third-party site and provide the correct echo headers
HttpWebRequest echo = (HttpWebRequest) WebRequest.Create("http://api.twitpic.com");
echo.Headers.Add("X-Auth-Service-Provider", client.RequestUrl);
echo.Headers.Add("X-Verify-Credentials-Authorization", auth);

OAuth 1-Legged

If the application needs to make a request without the oauth_token set, but included as an empty token in the request (oauth_token=) you can set accessToken to string.Empty. When accessToken is null, it is not included or signed.

var client = OAuthRequest.ForProtectedResource("GET", "CONSUMER_KEY",
    "CONSUMER_SECRET", string.Empty, null, OAuth.OAuthSignatureMethod.RsaSha1);
var requestUrl = 
    $"https://SOME_BASE_URL/jira/rest/api/2/search?jql=assignee=SOME_USER_ID&user_id=SOME_USER_ID";
client.RequestUrl = requestUrl;
var authorizationHeader = client.GetAuthorizationHeader();
using (var httpClient = new HttpClient())
{
    httpClient.DefaultRequestHeaders.Authorization = 
        new AuthenticationHeaderValue("OAuth", authorizationHeader.Remove(0,6)); // Remove "OAuth "
    string result = await httpClient.GetStringAsync(requestUrl);
}

oauth-dotnetcore's People

Contributors

akalcik avatar mano-cz avatar rhargreaves avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

oauth-dotnetcore's Issues

Custom parameters added to GetRequestString() are stripped off, resulting in wrong request

Hello,

Every time I add my own set of parameters to OAuthRequest.GetAuthorizationQuery() they are stripped off the resulting query string. However, the signature is being calculated taking them into consideration. This results in wrong authorization query being returned.

I believe the issue exists since 2.X. The issue lies in line 214 of OauthRequest.cs as my parameters do not begin with oauth_ and I the official standard says nothing about such a restriction

Oauth Access Token

Hello,
This is not really an issue. I'm having problems getting access token from https://api.twitter.com/oauth/access_token, it returns a 401 authorization required.

This is my Oauth Request
var oauthClient = new OAuthRequest
{
Method = "POST",
Type = OAuthRequestType.AccessToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret,
RequestUrl = "https://api.twitter.com/oauth/access_token",
Token = request_token,
Version = "1.0a",
Realm = "twitter.com"
};

I would appreciate if you could help.

OAuthRequest.ForProtectedResource

Hello, thank you for providing this useful nuget!! However, I'm having a problem fetching user data from the twitter API. This is my code snippet:

              var client = OAuthRequest.ForProtectedResource("GET", _apiKey, _apiKeySecret, oauthToken, oauthTokenSecret);            
              client.RequestUrl = requestUrl;
              var auth = client.GetAuthorizationHeader();

Method GetAuthorizationHeader on an OAuthRequest instance throws an exception with a message: "Failed to compare two elements in the array." InnerException message: "Object reference not set to an instance of an object." and StackTrace "at OAuth.OAuthTools.<>c.b__19_1(WebParameter x, WebParameter y)\r\n at System.Collections.Generic.ArraySortHelper1.InsertionSort(T[] keys, Int32 lo, Int32 hi, Comparison1 comparer)\r\n at System.Collections.Generic.ArraySortHelper1.IntroSort(T[] keys, Int32 lo, Int32 hi, Int32 depthLimit, Comparison1 comparer)\r\n at System.Collections.Generic.ArraySortHelper1.IntrospectiveSort(T[] keys, Int32 left, Int32 length, Comparison1 comparer)\r\n at System.Collections.Generic.ArraySortHelper1.Sort(T[] keys, Int32 index, Int32 length, Comparison1 comparer)"

When I use different approach:

        var client = new OAuthRequest
        {
            Method = "GET",
            Type = OAuthRequestType.ProtectedResource,
            SignatureMethod = OAuthSignatureMethod.HmacSha1,
            ConsumerKey = _apiKey,
            ConsumerSecret = _apiKeySecret,
            Token = oauthToken,
            TokenSecret = oauthTokenSecret,
            RequestUrl = requestUrl,
            Version = "1.0a"
        };
        var auth = client.GetAuthorizationHeader();

I get the same error. I cannot identify the cause of this issue because fetching request and access token works just fine. Hope anyone can help me with this :)

Query string parsing is wrong

OAuthRequest client = OAuthRequest.ForProtectedResource(OAuthSignatureMethod.RsaSha1.ToString(),
consumerKey, privateKeyAsXml, string.Empty, null);
client.RequestUrl = $"https://www.url.com/search?jql=assignee=ZZAVAKAA&user_id=ZZAVAKAA";
string authorizationHeader = client.GetAuthorizationHeader();

When I call the code above I get the exception Uri does not have valid query string which is wrong as the query above is a valid query string.

See the output when I parse the query with the help of HttpUtility.ParseQueryString

var queryValues = HttpUtility.ParseQueryString("https://www.url.com/search?jql=assignee=ZZAVAKAA&user_id=ZZAVAKAA");
queryValues.Dump();
Key Value
https://www.url.com/search?jql assignee=ZZAVAKAA
user_id ZZAVAKAA

Add possibility to set signature type in the helper methods

It would be nice to have a possibility to have ability to set the signature type in the helper methods.

OAuthRequest.ForProtectedResource("GET", "consumerKey", "privateKey", "oauthToken", "accessSecret", OAuth.OAuthSignatureMethod.RsaSha1);

Invalid OAuth signature when using DELETE

Hello

I get an error "Invalid OAuth signature" when using this package to make a DELETE request.
I am using the helper method "ForProtectedResource" and I am pretty sure all my parameters are correct.

Note: I am using this package to make other requests as well and all of them work. These other request use the following helper methods: "ForRequestToken", "ForAccessToken". I also use the "ForProtectedResource" when performing a GET and this does work.

Could this be a package problem or is this something else?

HMAC SHA256 Support

For us to continue using this library we need to have HMAC SHA256 support for the signature method.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.