OAuth2 - authorization protocol, a logical development of OAuth 1.0. Read more about it here .Wandering around the Internet looking for a normal OAuth client library for .net, I didn’t find anything suitable and decided to write it myself, since there’s nothing complicated about it. The library is required to perform three actions: issue a link to the authorization code request, after returning from the authorizer, redirect the application to the token request page and then make requests using the received token.
For the first two actions, the abstract class OAuthAuthorizer and the classes inherited from it for specific social networks are responsible. Currently Facebook and Vkontakte are supported, but there is nothing difficult in adding a class for any other provider - you just need to redefine AuthorizeUri and TokenUri, and, for example, for classmates, add the parameter “response_type = code”.
Initialization of the authorizer looks like this:
public RedirectResult LogOn()
{
var fbAuth = new FacebookAuthorizer();
fbAuth.ClientId = "2128506";
fbAuth.Scope = "user_work_history,friends_work_history,publish_stream,read_friendlists";
fbAuth.RedirectUri = "http://backtothefuture.com/Account/Return";
return Redirect(fbAuth.CodeRequestUri);
}
')
The client is redirected to the address from fbAuth.CodeRequestUri, there he decides whether he needs to use our application or not, after which facebook will redirect him back to our website, carefully placing the authorization code in the GET request parameters.
public ActionResult Return(string code)
{
var fbAuth = new FacebookAuthorizer();
fbAuth.ClientId = "2128506";
fbAuth.ClientSecret = "top_secret";
fbAuth.RedirectUri = "http://backtothefuture.com/Account/Return";
var response = auth.GetAuthorizationResponse(code);
The response variable now contains the response from the facebook authorization page, which, if we did everything correctly and the authorization code is correct, contains a token that gives unlimited power (within the limits of what is permitted) over the user's account. Now you can proceed to the third, most important part of the authorization - the requests for user data from facebook. To do this, use the classes inherited from the IOAuthClient interface, for example, FacebookClient
var client = new FacebookClient();
client.Response = response;
Dictionary<string,object> me = OAuthClientUtils.JsonToDictionary(client.Me());
return Json(me);
}
The user will be returned a Json object with its data, which is returned by facebook.
The source code of the library is available
on github . I would be grateful for any suggestions for improvement.