Giter VIP home page Giter VIP logo

nemiro.oauth's Introduction

Nemiro.OAuth

Nemiro.OAuth is a class library for authorization via OAuth protocol in .NET Framework.

The library provides mechanisms for implementing OAuth clients, and also contains a ready-to-use clients for popular websites.

Nemiro.OAuth is distributed under Apache License Version 2.0.

To install Nemiro.OAuth, run the following command in the Package Manager Console:

PM> Install-Package Nemiro.OAuth

Online Demo

demo-oauth.nemiro.net

Features

  • Support OAuth 1.0 and 2.0;
  • Obtaining basic information about users: ID, name, sex, date of birth, email address and telephone number;
  • Ready-to-Use OAuth clients for: Amazon, Assembla, CodeProject, Dropbox, Facebook, Foursquare, GitHub, Google, Instagram, LinkedIn, Microsoft Live, Mail.Ru, Odnoklassniki (odnoklassniki.ru), SoundCloud, SourceForge, Tumblr, Twitter, VK (vkontakte, vk.com), Yahoo!, Yandex (yandex.ru);
  • Base classes to create additional clients;
  • Basic principles of operation with API of different providers;
  • Unified mechanisms to facilitate integration with a variety of API.

Less code, more functionality!

System Requirements

  • .NET Framework 3.5, 4.0, 4.5, 4.6 or 4.7

License

Nemiro.OAuth is distributed under Apache License Version 2.0.

How to use

1. Create an application at the OAuth provider site.

2. Use these credentials for registration of an OAuth client in your project.

For example, Facebook:

C#

OAuthManager.RegisterClient
(
  "facebook", 
  "1435890426686808", 
  "c6057dfae399beee9e8dc46a4182e8fd"
);

Visual Basic .NET

OAuthManager.RegisterClient _
(
  "facebook", 
  "1435890426686808", 
  "c6057dfae399beee9e8dc46a4182e8fd"
)

3. Create a page to handle the callback. And add code to obtain user data with external server.

For example:

C#

public partial class ExternalLoginResult : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    var result = OAuthWeb.VerifyAuthorization();
    Response.Write(String.Format("Provider: {0}<br />", result.ProviderName));
    if (result.IsSuccessfully)
    {
      var user = result.UserInfo;
      Response.Write(String.Format("User ID:  {0}<br />", user.UserId));
      Response.Write(String.Format("Name:     {0}<br />", user.DisplayName));
      Response.Write(String.Format("Email:    {0}", user.Email));
    }
    else
    {
      Response.Write(result.ErrorInfo.Message);
    }
  }
}

Visual Basic .NET

Public Class ExternalLoginResult
  Inherits System.Web.UI.Page

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim result As AuthorizationResult = OAuthWeb.VerifyAuthorization()
    Response.Write(String.Format("Provider: {0}<br />", result.ProviderName))
    If result.IsSuccessfully Then
      Dim user As UserInfo = result.UserInfo
      Response.Write(String.Format("User ID:  {0}<br />", user.UserId))
      Response.Write(String.Format("Name:     {0}<br />", user.DisplayName))
      Response.Write(String.Format("Email:    {0}", user.Email))
    Else
      Response.Write(result.ErrorInfo.ToString())
    End If
  End Sub

End Class

4. Get the address for authentication and redirect the user to it.

C#

string returnUrl =  new Uri(Request.Url, "ExternalLoginResult.aspx").AbsoluteUri;
OAuthWeb.RedirectToAuthorization("facebook", returnUrl);

Visual Basic .NET

Dim returnUrl As String = New Uri(Request.Url, "ExternalLoginResult.aspx").AbsoluteUri
OAuthWeb.RedirectToAuthorization("facebook", returnUrl)

5. Enjoy!

See Also

nemiro.oauth's People

Contributors

alekseynemiro avatar israelferrazaraujo 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

Watchers

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

nemiro.oauth's Issues

IdentityServer 4 Integration

I know you support many public clients.... But I have a STS Server Based on Asp.net Core MVC Application using IdentityServer 4...... we just implement the login page for single sign on.... but now we want all our applications use just that unique Login Page. So the problem is with Asp.net Web Forms and Asp.net MVC targeted in net framework 3.5. Is there way to do this with your library. Is There Any Example of how to implement it?. We want just erase the login page of other applications and just use the login page of the STS Server and then redirect to the Clients requested. Thank You So Much. I hopen you can help me.

ASP.NET Core issuse

NullReferenceException at Nemiro.OAuth.AuthorizationResult.get_AccessTokenValue().

When try to get access token.
OAuthWeb.VerifyAuthorization(returnedFromSocialUrl);
or
OAuthWeb.VerifyAuthorization(requestId, code);

In Full .Net framework working correct.

authentication via popup

Hi Aleksey,
how I should do to perform the authentication operation via a popup. For example, "facebook connect" via foursquare.com.
Thank you.
Nacer.

New dropbox authorisation key

Hello dear alekseynemiro.
I've not yet started using your library and I have question for you.
Is your library supports new Dropbox authorisation method? (After mail & pass input, Dropbox show u a key, that should be used in application). Example of key attached as screenshot.
3

Thank you!

Don't force TLS 1.0

Hi,

In ExecuteRequest nemiro.oauth is forcing the use of TLS 1.0 as security protocol.
This make impossible to connect to web servers that only support TLS 1.1/1.2 failing with "An existing connection was forcibly closed by the remote host".

One quick fix is simply replacing that line with:
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls;
So that it will allow TLS 1.0 while still keeping the other protocols enabled.

But I think that don't enabling TLS 1.0 at all would be the a wiser way to go. I don't think that a library should touch ServicePointManager.SecurityProtocol.

Uploading large files

Implement the ability to upload large files.

Now available only to upload a small file size.

Uploading files is beyond the scope of the project OAuth.

The project is implemented by yourself uploading files :-) No, it's not artificial intelligence. Architecture has shown that can be opened the possibility of sending files.

Implement uploading large files a bit more complicated.

Until it is done, you can use their own methods to upload files. Use HttpWebRequest/HttpWebResponse (see for example: EpxecuteRequest) or WebClient, or HttpClient.

Small example for Dropbox:

var client = new WebClient();

// handlers
client.UploadProgressChanged += (s, ce) =>
{
  // you can create progress here
  Console.WriteLine("Uploading: {0}", ce.ProgressPercentage);
};

client.UploadFileCompleted += (s, ce) =>
{
  // exception
  if (ce.Error != null)
  {
    MessageBox.Show(ce.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    return;
  }

  // parse result
  var result = UniValue.ParseJson(Encoding.UTF8.GetString(ce.Result));
  if (result["error"].HasValue)
  {
    MessageBox.Show(result["error"].ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  }
  else
  {
    MessageBox.Show(result.ToString(), "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
  }
};

var url = new UriBuilder("https://api-content.dropbox.com/1/files_put/auto/");
url.Query = String.Format("access_token={0}", Properties.Settings.Default.AccessToken) + // your access token here
String.Format("&path=/{0}", Path.GetFileName(openFileDialog1.FileName).Replace("\\", "/")) +
String.Format("&overwrite={0}", "true") +
String.Format("&autorename={0}", "true");

client.UploadFileAsync
(
  url.Uri,
  "PUT",
  openFileDialog1.FileName, 
  null
);

Ayudaaaaaaa

Cunado quiero conectar a Provider: LinkedIn, me da el sigueinte error
Anulada la solicitud: No se puede crear un canal seguro SSL/TLS.

        If OAuthManager.IsRegisteredClient("LinkedIn") = False Then
            OAuthManager.RegisterClient("LinkedIn",
                            "xxxx",
                            "xxxx")
        End If

    Try
        Dim provider As String = "LinkedIn"
        Dim returnUrl As String = New Uri(Request.Url, "login_social.aspx").AbsoluteUri
        OAuthWeb.RedirectToAuthorization(provider, returnUrl)
    Catch ex As Exception
        LiteralError.Text = "<strong>Existen los Siguientes Errores en el Formulario</strong><br>" & ex.Message
        ScriptManager.RegisterStartupScript(Me, Me.GetType(), "msjError", "msjError();", True)

    End Try

Добавить атрибут Serializable на классе OAuthRequest

Реализация провайдера IOAuthRequestsProvider зависит от класса OAuthRequest, и, например, возникает трудность, если требуется для хранения запросов в бинарном виде или xml. Может стоить добавить Serializable атрибут или есть другой способ? На данный момент произвожу маппинг со своими объектами, но это дополнительные трудности.

Custom OAuth2 server

Я хочу реализовать свой сервер авторизации (http://tools.ietf.org/html/rfc6749#section-4.3.2), а в качестве клиента использовать вашу библиотеку.

Вы не могли бы вкратце описать обмен между сервером и клиентом ?

PS Код сервера (рабочий) с меня :-)

preflight request doesn't pass access control

Hi, after register a nemiro.oAuth API in my project, when a try to signing user with FaceBook or Twitter i get the followin mesagges:

api.twitter.com/oauth/authorize?oauth_token=DdapZwAAAAAA4_VyAAABY19RKB0:1 Failed to load resource: the server responded with a status of 400 ()
Home:1 Failed to load https://api.twitter.com/oauth/authorize?oauth_token=DdapZwAAAAAA4_VyAAABY19RKB0: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:44305' is therefore not allowed access. The response had HTTP status code 400.

Home:1 Failed to load https://www.linkedin.com/uas/oauth2/authorization?client_id=8649u8izdndqu5&response_type=code&state=fc48a1908548404caffb0338018ffd7f&scope=r_basicprofile%20r_emailaddress&redirect_uri=https%3A%2F%2Flocalhost%3A44305%2FHome%2FExternalLoginResult: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:44305' is therefore not allowed access.

Home:1 Failed to load https://www.facebook.com/dialog/oauth?client_id=225631291319901&response_type=code&state=a93f3e7389a241489483bd8f4ca5b8ec&scope=public_profile%2Cemail&redirect_uri=https%3A%2F%2Flocalhost%3A44305%2FHome%2FExternalLoginResult: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:44305' is therefore not allowed access.

in mi project i used the nemiro.OAuth like this:

[Route("LoginExterno/{provider}")]
[HttpPost]
[AllowAnonymous]
//[HttpGet]

    public async Task<IHttpActionResult> LoginExterno(string provider = "")
    {
        if (string.IsNullOrWhiteSpace(provider))
        {
            ModelState.AddModelError("", "Se requiere el provedor de autenticación");
            return BadRequest(ModelState);
        }

        //var returnUrl = new Uri("/Home/ExternalLoginResult", UriKind.Relative).AbsoluteUri;  //
        //return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString("/Home/ExternalLoginResult"));
        string returnUrl =  Url.Content("~/") + "Home/ExternalLoginResult";
         OAuthWeb.RedirectToAuthorization(provider, returnUrl);

        return Ok();
    }

could you help me please?, what I do wrong in the implementation.

thenak in advance.

Google client missing info

Hi,
I'm using the Google client but the only informations I retrieve after authentication are Email and Userpic, all the other properties of UserInfo are null.

Strict tls 1.2 authentication is not happening with google.(may be other client as well)

Google authentication(may be other provider as well) is not working on the strict tls 1.2 above servers.

at System.Net.SSPIWrapper.AcquireCredentialsHandle(SSPIInterface SecModule, String package, CredentialUse intent, SecureCredential scc)
at System.Net.Security.SecureChannel.AcquireCredentialsHandle(CredentialUse credUsage, SecureCredential& secureCredential)
at System.Net.Security.SecureChannel.AcquireClientCredentials(Byte[]& thumbPrint)
at System.Net.Security.SecureChannel.GenerateToken(Byte[] input, Int32 offset, Int32 count, Byte[]& output)
at System.Net.Security.SecureChannel.NextMessage(Byte[] incoming, Int32 offset, Int32 count)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.TlsStream.CallProcessAuthentication(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.ConnectStream.WriteHeaders(Boolean async)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetResponse()
at Nemiro.OAuth.OAuthUtility.ExecuteRequest(String method, String endpoint, HttpParameterCollection parameters, HttpAuthorization authorization, NameValueCollection headers, String contentType, AccessToken accessToken, Boolean allowWriteStreamBuffering, Boolean allowSendChunked, Int64 contentLength, HttpWriteRequestStream streamWriteCallback, Int32 writeBufferSize, Int32 readBufferSize, Boolean donotEncodeKeys)
--- End of inner exception stack trace ---
at Nemiro.OAuth.OAuthUtility.ExecuteRequest(String method, String endpoint, HttpParameterCollection parameters, HttpAuthorization authorization, NameValueCollection headers, String contentType, AccessToken accessToken, Boolean allowWriteStreamBuffering, Boolean allowSendChunked, Int64 contentLength, HttpWriteRequestStream streamWriteCallback, Int32 writeBufferSize, Int32 readBufferSize, Boolean donotEncodeKeys)
at Nemiro.OAuth.OAuthUtility.Post(String endpoint, HttpParameterCollection parameters, HttpAuthorization authorization, NameValueCollection headers, String contentType, AccessToken accessToken, Boolean allowWriteStreamBuffering, Boolean allowSendChunked, Int64 contentLength, HttpWriteRequestStream streamWriteCallback, Int32 writeBufferSize, Int32 readBufferSize, Boolean donotEncodeKeys)
at Nemiro.OAuth.OAuth2Client.GetAccessToken()
at Nemiro.OAuth.OAuthBase.get_AccessToken()
at Nemiro.OAuth.OAuthWeb.VerifyAuthorization(String requestId, String code)

[SOLVED] OAuthUtility.Post parameter json body

Hi,
what is the correct way to create a raw body data parameter?
This does not send the parameter correctly:

Dim json As String = Me.TextBox1.Text

Dim result = OAuthUtility.Post("http://192.168.1.35:8000/api/v1/copies/fam",
                                        parameters:=New HttpParameterCollection From {
                                        New HttpRequestBody(json)},
                                        contentLength:=json.Length,
                                        contentType:="application/json",
                                        headers:=New NameValueCollection From {
                                            {"Authorization", String.Format("Token {0}", token)}
                                        })

Like this in postman:
image

Problem with HttpParameterCollection

Hello! I installed your framework and tried to make first application with it. But when I try to use HttpParameterCollection I got this error: http://imgur.com/a/R1b1m. Any idead how to solve it? I use Visual studio 2015 and make windows form application with Net framework 4.0

Close the session and disposing the resources

Hello! Say, I want to login to my site use external service, for example Mail.Ru
The simplest case is supposed the following steps:

  • Register Mail.Ru client by using OAuthManager.RegisterClient(new MailRuClient(...))
  • Receive authorization url by using OAuthWeb.GetAuthorizationUrl("Mail.Ru", ...)
  • Verifying the authorization by using OAuthWeb.VerifyAuthorization();

If all is Ok, user will be logged on to the system. If not, the login page of external service Mail.ru will reject the user.

Questions:

  1. User want to logout and then login to the site under new credentials using the same external service Mail.ru.
    How to correctly sign-out the user from site? How to close the session, related to external service in scenario above?

  2. Common question: I can't find any close() or dispose() methods in library. Is it required to do some special disposing of the resources, related to Nemiro.OAuth?

Thank you

Загрузка и выгрузка папок (Dropbox).

Добрый вечер.
Подскажите,пожалуйста,как можно изменить код в DropboxExample,чтобы стало возможным загружать и выгружать не файлы,а папки? И реально ли вообще это сделать, просто даже в оригинальном Dropbox нет возможности выгрузить целую папку с компьютера, а при загрузке папок они загружаются в виде архивов.
Заранее спасибо.

Two legged OAuth

Does Nemiro support two-legged OAuth, and if so, do you have sample code of how to do that?

Assembly version numbers cause assembly loading failures at runtime

I integrated your framework into an application that I built a few months ago. I had forked earlier because I needed to strong name your assemblies, and I noticed that you are now string naming. I just started upgrading today and ran into an interesting issue. It appears that you put the .NET framework version in the patch version field of the version number. For example, I am seeing 1.2.45.xxx for the .NET 4.5 version of the assembly and 1.2.451 for the .NET 4.5.1 version of the assembly. This is kind of screwy and causes issues.

I have a redistributable SDK assembly that end users can use to create extensions for my app that is compiled against .NET 4.5. However, the main desktop GUI (WinForms/WPF) is built against .NET 4.5.1. If I reference the SDK assembly in my GUI, I'm hitting assembly resolution issues at runtime because the SDK assembly is trying to load the 1.2.45.xxx version of the assembly and it is finding 1.2.451.xxx instead, and this fails with an assembly load error.

If there's no fundamental API differences between the assemblies other than they are compiled for different target versions of the .NET Framework, then the assemblies should have the exact same version number. This will allow for and support in-place upgrades with the CLR. For example, an application compiled against .NET 4.0 will upgrade and run when .NET 4.5 is installed. Likewise, an application or assembly compiled against .NET 4.5 should work when running in a .NET 4.5.1 environment. But because of the version numbering scheme that you are using, this isn't the case.

System.NullReferenceException' occurred in Nemiro.OAuth.LoginForms.dll

Getting error in c# winforms app when trying to get access token from dropbox.

System.NullReferenceException was unhandled
Message: An unhandled exception of type 'System.NullReferenceException' occurred in Nemiro.OAuth.LoginForms.dll
Additional information: Object reference not set to an instance of an object.

Office365 Provider

Hi Dear do you have a new plan to add more providers like the office365 provider
regards.
shady

Google client

I'm trying oAuth for desktop client, it is showing error. I tried following your instruction for "For desktop applications, the user will need to manually enter authorization code." as shown below:

` var login = new GoogleLogin("xxxxxx.apps.googleusercontent.com", "XXXXYYYYfv", loadUserInfo: true);

        login.Owner = this;
        login.ShowDialog();

        // open the login page in browser
        System.Diagnostics.Process.Start(login.AuthorizationUrl);
        
        // waiting of entering the access code 
        string code = "";
        while (String.IsNullOrEmpty(code))
        {
            Console.WriteLine("Enter access code:");
            code = Console.ReadLine();
        }

        Console.WriteLine();
        `

But it shows error.

The property or indexer 'Nemiro.OAuth.LoginForms.Login.AuthorizationUrl' cannot be used in this context because the get accessor is inaccessible

and
Nemiro.OAuth.LoginForms.Login.AuthorizationUrl' is inaccessible due to its protection level

Seems some restriction with "System.Diagnostics.Process.Start(login.AuthorizationUrl);"

Kindly guide me to get this resolved.

Compile issue

I have visual studio 2017 installed. I am sure have .NET 4.7.1 installed but your project still complain .net framework missing. I really like your software, It is better that your software can be compiled to .net 4.0 which will be compatible most of old software. If you target .net 4.7.x, you will be competitor of IdenityServer4.

image
image

Help with Yandex authorization

Добрый вечер, Алексей.
Пытаюсь разобраться с авторизацией на Yandex.
Опыта работы с OAuth, HTTP-запросами(POST, GET) нет. Отсюда и возникают следующие вопросы:

  1. После выполнения запроса System.Diagnostics.Process.Start(yandex.AuthorizationUrl) на странице в браузере отображается "Код подтверждения". Я так понимаю, что после получения кода подтверждения мы автоматически получаем и "токен доступа", с которым в дальнейшем и работаем? Или же нам надо посылать POST-запрос с кодом подтверждения для получения этого токена?
  2. Допустим, мы получили "токен доступа". Теперь мне надо, к примеру, послать запрос на получение информации о моем Yandex.Disk. Этот "токен доступа" я должен передавать в GET-запросе как один из параметров или механизм запросов реализован как-то по-другому?
    Прошу Вас ответить на эти вопросы по мере возможности.
    P.S. Прошу прощения за то, что пишу на русском. Если это критично, то могу попробовать пересоздать issue на английском языке.

Parameter names are not url encoded in OAuthAuthorization.GetSignatureBaseString

Hi,
While I was working with Magento 2, I noticed that Nemiro.OAuth is url encoding the value but not the name of parameters, making it unable to work with software like Magento that mandates things like searchCriteria[pageSize]
Encoding also the name made Magento happy again

Giving a fast look at the OAuth 1.0a specification, seems that it mandates that both names and values must be encoded http://oauth.net/core/1.0a/#encoding_parameters

Обновление маркера доступа

Доброе время суток.
Подскажите как при использовании готового модуля сделать обновление маркера?
Я взял готовый модуль OdnoklassnikiClient или VKontakteClient, они оба поддерживают обновление маркера.
Делаю авторизацию через браузер, получаю все маркеры, в том числе маркер для обновления. Все хорошо.
Но не понятно как сделать обновление маркера без повторного подключения через браузер. Получается, что после каждого пере открытия программы нужно заново производить авторизацию через браузер, либо писать свой метод получения обновления маркера, хотя в классах определен метод RefreshToken().

Facebook Client on windows forms

Hello. Im using ur library for auth on facebook by windows forms. Using example from http://www.codeproject.com/Articles/875991/Users-Authorization-through-OAuth-in-NET-Framework#WindowsForms
but I have the next issue: after trying clicking on button and opening child window - element webbrowser throw exception, that
Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.
What need to do to fix this problem?

Facebook Client - No Email returned

Hi Aleksey!

First of alll, thanks a lot for the library as it is awsome all the work you´ve done on it!
Sorry to bother you but, the facebook Client is not returning me the email.

I´ve followed the documentation of the library, and all the samples provided on the following pages but can not get back the user email for the Facebook provider.

http://www.codeproject.com/Articles/875991/Users-Authorization-through-OAuth-in-NET-Framework#NETVersionRemark
https://oauth4net.codeplex.com/

The samples provided are not returning the email either.

All works fine in you demo site http://demo-oauth.nemiro.net/ but I cannot get same behaviour.

A side note:

I´m using VB.NET and the framework 3.5 and I´ve also tested this in the global.asax

OAuthManager.RegisterClient _
(
"facebook",
"1435890xxxxxx808",
"c6057dfae3xxxxxxxxxa4182e8fd"
)

and

    OAuthManager.RegisterClient _
    (
      New FacebookClient _
      (
        "1056832xxxxxxx7",
        "b724e6822aeb4faxxxxxxxxxxx4fb"
      ) With
      {
        .Scope = "public_profile,email,user_friends"
      }
    )

Do I need to publish the site or all should works on the local host? (Of course I´ve added the local host url and all that stuffs to the facebook developers section)

I´ve uploaded the small test here: https://www.dropbox.com/s/iut9zh8hlg08hun/Ejemplo_05.zip?dl=0

cheers,

Adding Scope in Custom Client Does Not Work

If you create a custom client you cannot set the DefaultScope variable as is done in the built in clients like the FacebookClient.cs file

 public FacebookClient(string clientId, string clientSecret) : base
    (
      "https://www.facebook.com/dialog/oauth",
      "https://graph.facebook.com/oauth/access_token",
      clientId,
      clientSecret
    )
    {
      // scope list
      base.ScopeSeparator = ",";
      base.DefaultScope = "public_profile,email"; //,user_website,user_birthday
    }

This is because it is an internal property and not accessible. The other option, setting the Scope variable, does not work either because of the way the scope is processed in the OAuth2Client.cs file. In the code if the DefaultScope variable is not set then the Scope variable is not used.

        // add default scope
        string scope = this.DefaultScope;

        // add custom scope
        if (!String.IsNullOrEmpty(this.Scope))
        {
          var scopeToAdd = new List<string>();

        /**
         * This is were the problem occurs, 
         * Since we have not set the DefaultScope variable the Scope variable is not used. 
         **/
          if (!String.IsNullOrEmpty(scope))
          {
            var scope1 = scope.Split(this.ScopeSeparator.ToCharArray());
            var scope2 = this.Scope.Split(this.ScopeSeparator.ToCharArray());
            foreach (var s in scope2)
            {
              if (!scope1.Any(itm => itm.Equals(s, StringComparison.OrdinalIgnoreCase)))
              {
                scopeToAdd.Add(s);
              }
            }
            if (scopeToAdd.Count > 0) { scope += this.ScopeSeparator; }
          }
          scope += String.Join(this.ScopeSeparator, scopeToAdd.ToArray());
        }

        // add scope to url
        if (!String.IsNullOrEmpty(scope))
        {
          result += String.Format("&scope={0}", OAuthUtility.UrlEncode(scope));
        }

By adding an else to the if statement that is checking if the scope variable is empty would fix this issue.

       // add default scope
        string scope = this.DefaultScope;

        // add custom scope
        if (!String.IsNullOrEmpty(this.Scope))
        {
          var scopeToAdd = new List<string>();
          if (!String.IsNullOrEmpty(scope))
          {
            var scope1 = scope.Split(this.ScopeSeparator.ToCharArray());
            var scope2 = this.Scope.Split(this.ScopeSeparator.ToCharArray());
            foreach (var s in scope2)
            {
              if (!scope1.Any(itm => itm.Equals(s, StringComparison.OrdinalIgnoreCase)))
              {
                scopeToAdd.Add(s);
              }
            }
            if (scopeToAdd.Count > 0) { scope += this.ScopeSeparator; }
          }
          else // This is the fix
          {
            scope = Scope;
          }
          scope += String.Join(this.ScopeSeparator, scopeToAdd.ToArray());
        }

        // add scope to url
        if (!String.IsNullOrEmpty(scope))
        {
          result += String.Format("&scope={0}", OAuthUtility.UrlEncode(scope));
        }

Logout for Shared Computers (Revoke the Token)

I apologize because I'm not entirely sure if this is an issue with nemiro.oauth, oauth in general or if I'm just missing something important.

In addition to the existing table-based login for my site, I'm adding some social logins. Thanks to nemiro.oauth, that's going pretty quickly and working just fine for me.

Unfortunately, many of my users are going to be using a shared computer. I was planning to add some code to my existing Logout button to disconnect the user's social logins as well but I can't find a method to do that. From what I've read elsewhere, I think I need to revoke the token for each. But the token is abstracted away from me so I'm not sure how to do that. Even if it is possible (and I suspect you will tell me it is :)), I wonder if you might consider making a method (in OAuthWeb?) for it to keep it simple, or at least add it to Problems and Solutions.

Keep up the good work!

Error found!

These errors found when i building the app...

I have installed nemiro.OAuth.LoginForms package... but for the first time if i am going to building the app these bugs raised!

1 The type or namespace name 'DropboxLogin' could not be found (are you missing a using directive or an assembly reference?) C:\Users\Sony\Documents\Visual Studio 2010\Projects\Dropbox\Dropbox\Form1.cs

2 The type or namespace name 'Nemiro' could not be found (are you missing a using directive or an assembly reference?) C:\Users\Sony\Documents\Visual Studio 2010\Projects\Dropbox\Dropbox\Form1.cs

3 The type or namespace name 'Nemiro' could not be found (are you missing a using directive or an assembly reference?) C:\Users\Sony\Documents\Visual Studio 2010\Projects\Dropbox\Dropbox\Form1.cs

UAP possibility?

I was wondering if it would be possible to use this in a windows Universal App?

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.