コード例 #1
0
        public IAuthorizationState RequestAccessToken(string refreshToken)
        {
            {
                WebServerClient consumer = new WebServerClient(ServerDescription, ClientID, ClientSecret)
                {
                    AuthorizationTracker = new AuthorizationTracker(Scope)
                };

                IAuthorizationState grantedAccess = PrepareAuthorizationState(refreshToken);

                if (grantedAccess != null)
                {
                    try
                    {
                        consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(ClientSecret);
                        consumer.RefreshAuthorization(grantedAccess, null);

                        return(grantedAccess);
                    }
                    catch (Exception ex)
                    {
                        _log.Error("RefreshAuthorization() Exception:\r\n{0}\r\n", ex.ToString());
                    }
                }

                return(null);
            }
        }
コード例 #2
0
    protected void btnGetToken_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
        {
            return;
        }
        try
        {
            ToSession();
            WebServerClient consumer = new WebServerClient(Description(), CurrentPageState.ClientID, CurrentPageState.ClientSecret);
            consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(CurrentPageState.ClientSecret);
            IAuthorizationState grantedAccess = consumer.ProcessUserAuthorization(new HttpRequestWrapper(Request));

            if (grantedAccess == null)
            {
                throw new MyFlightbook.MyFlightbookValidationException("Null access token returned - invalid authorization passed?");
            }
            lblToken.Text = grantedAccess.AccessToken;
        }
        catch (MyFlightbook.MyFlightbookValidationException ex)
        {
            lblErr.Text = ex.Message;
        }
        catch (DotNetOpenAuth.Messaging.ProtocolException ex)
        {
            lblErr.Text = ex.Message;
        }
    }
コード例 #3
0
ファイル: Authenticator.cs プロジェクト: gospodnetic/FitBit
        //Authentication Method
        public void Authenticate()
        {
            var serverDescription = new AuthorizationServerDescription();

            serverDescription.AuthorizationEndpoint = new Uri(AuthorizationEndpointUrl);
            serverDescription.TokenEndpoint         = new Uri(TokenEndpointUrl);
            serverDescription.ProtocolVersion       = ProtocolVersion.V20;

            var client = new WebServerClient(serverDescription);

            client.ClientIdentifier           = ClientIdentifier;
            client.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(ClientSecret);

            var token = client.GetClientAccessToken();

            //var request = (HttpWebRequest)WebRequest.Create("http://localhost:8080/test/");
            ////System.Diagnostics.Process.Start("http://localhost:8080/test/");

            //request.Method = "GET";
            //client.AuthorizeRequest(request, token);
            //var response = request.GetResponse();

            //var postreqreader = new StreamReader(response.GetResponseStream());
            //var json = postreqreader.ReadToEnd();
        }
コード例 #4
0
        public ExactOnlineConnection(string clientId, string clientSecret, string redirectUri, string endPoint, IDropboxUserToken dropboxUserToken)
        {
            this.dropboxUserToken = dropboxUserToken;

            miscellaneousDocumentType = 55;

            generalCategory = Guid.Parse("3b6d3833-b31b-423d-bc3c-39c62b8f2b12"); //Guid.Parse(clientId);

            this.endPoint = endPoint;

            authorization = new AuthorizationState
            {
                Callback = new Uri(redirectUri)
            };

            var token = dropboxUserToken.TryRetrieveTokenFromDatabase(HardcodedUser.Id);

            authorization.AccessToken = token.ExactAccessToken;

            authorization.AccessTokenExpirationUtc = token.ExactAccessTokenExpiration;

            exactClient = IsAccessTokenValid() ? new ExactOnlineClient(endPoint, GetAccessToken) : exactClient;

            var serverDescription = new AuthorizationServerDescription
            {
                AuthorizationEndpoint = new Uri(string.Format("{0}/api/oauth2/auth", endPoint)),
                TokenEndpoint         = new Uri(string.Format("{0}/api/oauth2/token", endPoint))
            };

            oAuthClient = new UserAgentClient(serverDescription, clientId, clientSecret);
            oAuthClient.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(clientSecret);
        }
コード例 #5
0
 public FacebookClient()
     : base(Description,
            clientIdentifier: ConfigurationManager.AppSettings["FacebookClientID"],
            credentialApplicator: ClientCredentialApplicator.PostParameter(ConfigurationManager.AppSettings["FacebookSecretKey"]),
            requestScopes: new string[] { "email" }, // We'd like the "email" scope from Facebook in addition to what Facebook defines as "basic"
            dataRequestUri: "https://graph.facebook.com/me",
            identityProvider: Models.IdentityProvider.Facebook)
 {
 }
コード例 #6
0
 /// <summary>
 /// We enforce the provding of a <see cref="ClientCredentialApplicator"/> such that the consumer is forced to choose the method using which
 /// the client secret is sent to the authorization server.
 /// </summary>
 /// <param name="requestScopes">Set of scopes to inquire from the authorization server.</param>
 /// <param name="dataRequestUri">Location at which to inquire the data once the request is authenticated.</param>
 public AuthenticationClient(AuthorizationServerDescription description, string clientIdentifier,
                             ClientCredentialApplicator credentialApplicator, string[] requestScopes, string dataRequestUri,
                             IdentityProvider identityProvider)
     : base(description, clientIdentifier, credentialApplicator)
 {
     _requestScopes    = requestScopes;
     _requestUri       = dataRequestUri;
     _identityProvider = identityProvider;
 }
コード例 #7
0
        /// <summary>
        /// Convert an authorization token for an access token.
        /// </summary>
        /// <param name="Request">The http request</param>
        /// <returns>The granted access token</returns>
        public virtual IAuthorizationState ConvertToken(HttpRequest Request)
        {
            WebServerClient consumer = new WebServerClient(Description(), AppKey, AppSecret)
            {
                ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(AppSecret)
            };

            return(consumer.ProcessUserAuthorization(new HttpRequestWrapper(Request)));
        }
コード例 #8
0
        /// <summary>
        /// Convert an authorization token for an access token.
        /// </summary>
        /// <param name="Request">The http request</param>
        /// <returns>The granted access token</returns>
        public virtual AuthorizationState ConvertToken(HttpRequest Request)
        {
            WebServerClient consumer = new WebServerClient(Description(), AppKey, AppSecret);

            consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(AppSecret);
            IAuthorizationState grantedAccess = consumer.ProcessUserAuthorization(new HttpRequestWrapper(Request));

            // Kindof a hack below, but we convert from IAuthorizationState to AuthorizationState via JSON so that we have a concrete object that we can instantiate.
            return(JsonConvert.DeserializeObject <AuthorizationState>(JsonConvert.SerializeObject(grantedAccess)));
        }
コード例 #9
0
        private UserAgentClient GetClient(Uri url)
        {
            var authServer = new AuthorizationServerDescription
            {
                AuthorizationEndpoint = null,                 // We are not actually using authorization, just authentication.
                TokenEndpoint         = url
            };

            return(new UserAgentClient(authServer, ClientIdentifier, ClientCredentialApplicator.PostParameter(ClientSecret)));
        }
コード例 #10
0
ファイル: GoogleClient.cs プロジェクト: sondaa/Stockwinners
 public GoogleClient()
     : base(Description,
            clientIdentifier: ConfigurationManager.AppSettings["GoogleClientID"],
            // Guys at Google somehow require this to be in POST form. Documenting it in their docs would have been nice.
            credentialApplicator: ClientCredentialApplicator.PostParameter(ConfigurationManager.AppSettings["GoogleSecretKey"]),
            requestScopes: new string[] { "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email" },
            dataRequestUri: "https://www.googleapis.com/oauth2/v2/userinfo",
            identityProvider: IdentityProvider.Google)
 {
 }
コード例 #11
0
ファイル: OAuth.cs プロジェクト: PopMedNet-Team/ADAPTABLE
 public OAuthProvider(string guid, string name, string imageUrl,
                      string tokenEndpoint, string authorizationEndpoint, string clientIdentifier, ClientCredentialApplicator credentialApplicator,
                      bool requireUsername = false)
     : base(guid, name, imageUrl, requireUsername)
 {
     Description = new AuthorizationServerDescription {
         TokenEndpoint = new Uri(tokenEndpoint), AuthorizationEndpoint = new Uri(authorizationEndpoint)
     };
     ClientIdentifier     = clientIdentifier;
     CredentialApplicator = credentialApplicator;
 }
コード例 #12
0
        private WebServerClient GetClient(IOAuth2SignInSettings signInSettings)
        {
            AuthorizationServerDescription authorizationServerDescription = _endpointBuilder.Build(signInSettings);
            var client = new WebServerClient(authorizationServerDescription)
            {
                ClientIdentifier           = signInSettings.ClientId,
                ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(signInSettings.ClientSecret)
            };

            return(client);
        }
コード例 #13
0
        /// <summary>
        ///     Create an HTTP Handler that supports OAuth user authentication.
        /// </summary>
        /// <param name="authBaseUri">The base auth URI e.g. https://auth.alitudeangel.com</param>
        /// <param name="clientId">Your client ID</param>
        /// <param name="clientSecret">Your client secret</param>
        /// <param name="scopes">Requested scopes</param>
        /// <param name="existingState">(optional) An existing state object from a previous session. May be null.</param>
        /// <param name="requireUserToken">true to aquire a user token, false to get a client only token.</param>
        /// <param name="redirectUri">The redirect URI to use for user token auth. Must match the registered URI for your client ID.</param>
        /// <param name="codeProvider">Implementation to use to get an authorization code URI from an auth login URI.</param>
        /// <returns>
        ///     A <see cref="ClientHandlerInfo"/> object that contains the auth state and the handler. The auth state may be persisted and passed
        ///     back in on future runs of the application to save login state.
        /// </returns>
        public static ClientHandlerInfo Create(
            string authBaseUri,
            string clientId,
            string clientSecret,
            IEnumerable <string> scopes,
            IAuthorizationState existingState,
            bool requireUserToken,
            string redirectUri,
            IAuthorizeCodeProvider codeProvider)
        {
            var        serverDescription = GetServerDescription(authBaseUri);
            ClientBase client;
            var        state = existingState;

            if (requireUserToken)
            {
                if (codeProvider == null || string.IsNullOrEmpty(redirectUri))
                {
                    throw new ArgumentNullException(nameof(codeProvider),
                                                    $"{nameof(codeProvider)} or {nameof(redirectUri)} cannot be null if {nameof(requireUserToken)} is true.");
                }

                var userClient = new UserAgentClient(serverDescription, clientId, ClientCredentialApplicator.PostParameter(clientSecret));
                if (state == null)
                {
                    // Open browser here
                    var returnTo = new Uri(redirectUri);
                    var uri      = userClient.RequestUserAuthorization(scopes, returnTo: returnTo);
                    var result   = codeProvider.GetCodeUri(uri, returnTo).Result;

                    state = new AuthorizationState {
                        Callback = returnTo
                    };
                    state.Scope.AddRange(scopes);
                    state = userClient.ProcessUserAuthorization(result, state);
                }

                client = userClient;
            }
            else
            {
                client = new WebServerClient(serverDescription, clientId, ClientCredentialApplicator.PostParameter(clientSecret));
                state  = state ?? client.GetClientAccessToken(scopes);
            }

            return(new ClientHandlerInfo(
                       new BearerTokenHttpMessageHandler(
                           client,
                           state,
                           new HttpClientHandler {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            }),
                       state));
        }
コード例 #14
0
        /// <summary>
        /// Convert an authoriztion token for an access token.
        /// </summary>
        /// <param name="Request">The http request</param>
        /// <returns>The granted access token</returns>
        public static IAuthorizationState ConvertToken(HttpRequest Request)
        {
            WebServerClient consumer = new WebServerClient(Description(), MFBFacebook.FACEBOOK_API_KEY, MFBFacebook.FACEBOOK_SECRET);

            consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(MFBFacebook.FACEBOOK_SECRET);
            IAuthorizationState grantedAccess = consumer.ProcessUserAuthorization(new HttpRequestWrapper(Request));

            // Exchange for a longer lived token
            ExchangeToken(grantedAccess);

            return(grantedAccess);
        }
コード例 #15
0
        public ActionResult oauth2callback()
        {
            WebServerClient consumer = new WebServerClient(server, clientID, clientSecret);

            consumer.ClientCredentialApplicator =
                ClientCredentialApplicator.PostParameter(clientSecret);
            IAuthorizationState grantedAccess = consumer.ProcessUserAuthorization(null);

            string accessToken = grantedAccess.AccessToken;

            return(Content(accessToken));
        }
コード例 #16
0
    private IAuthorizationState Authenticate(NativeApplicationClient client)
    {
        IAuthorizationState state = new AuthorizationState(new string[] { })
        {
            RefreshToken = this.refreshToken
        };

        // IMPORTANT - does not work without:
        client.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(this.clientSecret);

        client.RefreshAuthorization(state);
        return(state);
    }
コード例 #17
0
        public static WebServerClient CreateClient()
        {
            //pleasea contact hellopaisa for the credentials

            var desc = GetAuthServerDescription();
            //client ID provided
            var client = new WebServerClient(desc, clientIdentifier: "ID");

            //client secret/password provided
            client.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter("SECRET");

            return(client);
        }
コード例 #18
0
 public OAuthMethod(string title, string logoClass,
                    LoginService srv, string authEndpoint, string tokenEndpoint, string clientId, string clientSecret,
                    string emailScope, string requestUrl, Func <JToken, string> uniqueIDFromPerson)
 {
     _client = new WebServerClient(new AuthorizationServerDescription {
         AuthorizationEndpoint = new Uri(authEndpoint),
         TokenEndpoint         = new Uri(tokenEndpoint)
     }, clientId, ClientCredentialApplicator.PostParameter(clientSecret));
     Id                  = title;
     _srv                = srv;
     _requestUrl         = requestUrl;
     _emailScope         = emailScope;
     _uniqueIDFromPerson = uniqueIDFromPerson;
     Title               = title;
     LogoClass           = logoClass;
 }
コード例 #19
0
ファイル: OAuth2Coordinator.cs プロジェクト: terry2012/DSV
        internal OAuth2Coordinator(
            AuthorizationServerDescription serverDescription,
            IAuthorizationServerHost authServerHost,
            TClient client,
            Action <TClient> clientAction,
            Action <AuthorizationServer> authServerAction)
            : base(clientAction, authServerAction)
        {
            Requires.NotNull(serverDescription, "serverDescription");
            Requires.NotNull(authServerHost, "authServerHost");
            Requires.NotNull(client, "client");

            this.serverDescription = serverDescription;
            this.authServerHost    = authServerHost;
            this.client            = client;

            this.client.ClientIdentifier           = OAuth2TestBase.ClientId;
            this.client.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(OAuth2TestBase.ClientSecret);
        }
コード例 #20
0
        public static WebServerClient CreateClient()
        {
            if (string.IsNullOrEmpty(AppSettings.OAuth2ClientIdentifier))
            {
                Log.For(typeof(AccountController)).Error("OAuth2ClientIdentifier is not specified in configuration!");
                throw new Exception("Authentication is incorrectly configured");
            }

            if (string.IsNullOrEmpty(AppSettings.OAuth2ClientSecret))
            {
                Log.For(typeof(AccountController)).Error("OAuth2ClientSecret is not specified in configuration!");
                throw new Exception("Authentication is incorrectly configured");
            }

            var desc   = GetAuthServerDescription();
            var client = new WebServerClient(desc, clientIdentifier: AppSettings.OAuth2ClientIdentifier);

            client.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(AppSettings.OAuth2ClientSecret);
            return(client);
        }
コード例 #21
0
        private IAuthorizationState GetAccessTokenFromOwnAuthSvr()
        {
            var server = new AuthorizationServerDescription
            {
                TokenEndpoint   = new Uri(Config.ApiUrl + "/oauth/token"),
                ProtocolVersion = ProtocolVersion.V20
            };

            var client = new UserAgentClient(server)
            {
                //Those are the credentials for Downlords-FAF-Client
                ClientIdentifier           = Config.ClientIdentifier,
                ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(Config.ClientCredentialApplicator)
            };

            var token = client.ExchangeUserCredentialForToken(
                UsernameInputField.text, PasswordInputField.text);

            return(token);
        }
コード例 #22
0
    protected void btnGetToken_Click(object sender, EventArgs e)
    {
        Validate("vgAuthorize");
        if (!Page.IsValid)
        {
            return;
        }
        try
        {
            ToSession();
            WebServerClient consumer = new WebServerClient(Description(), CurrentPageState.ClientID, CurrentPageState.ClientSecret);
            consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(CurrentPageState.ClientSecret);
            IAuthorizationState grantedAccess = consumer.ProcessUserAuthorization(new HttpRequestWrapper(Request));

            lblToken.Text = grantedAccess.AccessToken;
        }
        catch (DotNetOpenAuth.Messaging.ProtocolException ex)
        {
            lblErr.Text = ex.Message;
        }
    }
コード例 #23
0
ファイル: ExactConnector.cs プロジェクト: top501/exactdropbox
        public Uri GetAuthorizationUri()
        {
            _endPoint = "https://start.exactonline.com";


            _authorization = new AuthorizationState
            {
                Callback = new Uri("http://localhost:19648/home/exoauth2")
            };


            var serverDescription = new AuthorizationServerDescription
            {
                AuthorizationEndpoint = new Uri(string.Format("{0}/api/oauth2/auth", _endPoint)),
                TokenEndpoint         = new Uri(string.Format("{0}/api/oauth2/token", _endPoint))
            };

            _oAuthClient = new UserAgentClient(serverDescription, "eb93389b-9532-46ca-9b24-898a38e91c22", "jYzWXVFiE87C");
            _oAuthClient.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter("jYzWXVFiE87C");

            return(_oAuthClient.RequestUserAuthorization(_authorization));
        }
コード例 #24
0
        public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request)
        {
            var tokens = this.Init(authService, ref session, request);

            var authServer = new AuthorizationServerDescription {
                AuthorizationEndpoint = new Uri(this.AuthorizeUrl), TokenEndpoint = new Uri(this.AccessTokenUrl)
            };
            var authClient = new WebServerClient(authServer, this.ConsumerKey)
            {
                ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(this.ConsumerSecret),
            };

            var authState = authClient.ProcessUserAuthorization();

            if (authState == null)
            {
                try
                {
                    var authReq         = authClient.PrepareRequestUserAuthorization(this.Scopes, new Uri(this.CallbackUrl));
                    var authContentType = authReq.Headers[HttpHeaders.ContentType];
                    var httpResult      = new HttpResult(authReq.ResponseStream, authContentType)
                    {
                        StatusCode = authReq.Status, StatusDescription = "Moved Temporarily"
                    };
                    foreach (string header in authReq.Headers)
                    {
                        httpResult.Headers[header] = authReq.Headers[header];
                    }

                    foreach (string name in authReq.Cookies)
                    {
                        var cookie = authReq.Cookies[name];

                        if (cookie != null)
                        {
                            httpResult.SetSessionCookie(name, cookie.Value, cookie.Path);
                        }
                    }

                    authService.SaveSession(session, this.SessionExpiry);
                    return(httpResult);
                }
                catch (ProtocolException ex)
                {
                    Log.Error("Failed to login to {0}".Fmt(this.Provider), ex);
                    return(authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown")));
                }
            }

            var accessToken = authState.AccessToken;

            if (accessToken != null)
            {
                try
                {
                    tokens.AccessToken        = accessToken;
                    tokens.RefreshToken       = authState.RefreshToken;
                    tokens.RefreshTokenExpiry = authState.AccessTokenExpirationUtc;
                    session.IsAuthenticated   = true;
                    var authInfo = this.CreateAuthInfo(accessToken);
                    this.OnAuthenticated(authService, session, tokens, authInfo);
                    return(authService.Redirect(session.ReferrerUrl.AddHashParam("s", "1")));
                }
                catch (WebException we)
                {
                    var statusCode = ((HttpWebResponse)we.Response).StatusCode;
                    if (statusCode == HttpStatusCode.BadRequest)
                    {
                        return(authService.Redirect(session.ReferrerUrl.AddHashParam("f", "AccessTokenFailed")));
                    }
                }
            }

            return(authService.Redirect(session.ReferrerUrl.AddHashParam("f", "RequestTokenFailed")));
        }
コード例 #25
0
        private bool getAccessToken(string authCode)
        {
            bool   getSuccess  = false;
            string accessToken = "";

            if (RefreshKey_saved == "")
            {
                consumer.ClientCredentialApplicator =
                    ClientCredentialApplicator.PostParameter(clientSecret);

                IAuthorizationState grantedAccess1 = consumer.ProcessUserAuthorization(authCode);

                accessToken     = grantedAccess1.AccessToken;
                RefreshKey_real = grantedAccess1.RefreshToken;

                // save key
                iniParser parser = new iniParser();

                parser.IniParser(iniPath);
                parser.AddSetting("Setup", "refreshkey", grantedAccess1.AccessToken);
                parser.AddSetting("Setup", "refreshkey_real", grantedAccess1.RefreshToken);
                parser.SaveSettings();
                myTabControl.SelectedIndex = 0;
            }
            else
            {
                accessToken = RefreshKey_saved;
                myTabControl.SelectedIndex = 0;
            }
            try
            {
                GoogleApi api = new GoogleApi(accessToken);

                // string user = "******"; // api.GetEmail();
                // GoogleApi api = new GoogleApi(accessToken);

                XmlDocument         contacts = api.GetContacts();
                XmlNamespaceManager nsmgr    = new XmlNamespaceManager(contacts.NameTable);
                //

                XmlNodeList _title = contacts.GetElementsByTagName("title");
                string      temp   = _title.Item(0).InnerText;
                temp        = temp.Replace("'s Contacts", "");
                sender_name = temp;
                if (textbox_name.Text == "")
                {
                    textbox_name.Text = temp;
                }

                nsmgr.AddNamespace("gd", "http://schemas.google.com/g/2005");
                nsmgr.AddNamespace("a", "http://www.w3.org/2005/Atom");
                emailCount = 0;

                foreach (XmlNode contact in contacts.GetElementsByTagName("entry"))
                {
                    XmlNode title = contact.SelectSingleNode("a:title", nsmgr);
                    XmlNode email = contact.SelectSingleNode("gd:email", nsmgr);

                    // Console.WriteLine("{0}: {1}",title.InnerText, email.Attributes["address"].Value);
                    if (email != null)
                    {
                        title_arr.Add(title.InnerText);
                        gmail_arr.Add(email.Attributes["address"].Value);
                        emailCount++;
                    }
                }
                getSuccess = true;
                button_import.Visibility   = Visibility.Collapsed;
                image_gmail.Visibility     = System.Windows.Visibility.Visible;
                connected_gmail.Visibility = image_gmail.Visibility;
                myTabControl.SelectedIndex = 0;
            }
            catch (Exception err)
            {
                Console.WriteLine("Error: " + err.Message);
                getSuccess = false;
                return(getSuccess);
            }
            // everything is good, goto input : autocomplete
            contactData.inc(emailCount);
            int i = 0;

            foreach (string emailAddress in gmail_arr)
            {
                contactData.States.SetValue(emailAddress, i);
                i++;
            }
            int where = contactData.States.Length;
            //
            AutoCompleteBox.ItemsSource = contactData.States;
            //email_list.Items.Clear();
            label_invalid.Visibility = Visibility.Collapsed;
            // myTabControl.SelectedIndex = 0;
            return(getSuccess);
        }
コード例 #26
0
ファイル: OAuth2Provider.cs プロジェクト: msnetc/ServiceStack
        public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
        {
            var tokens = this.Init(authService, ref session, request);

            //Transferring AccessToken/Secret from Mobile/Desktop App to Server
            if (request?.AccessToken != null)
            {
                if (VerifyAccessToken == null)
                {
                    throw new NotImplementedException($"VerifyAccessToken is not implemented by {Provider}");
                }

                if (!VerifyAccessToken(request.AccessToken))
                {
                    return(HttpError.Unauthorized($"AccessToken is not for the configured {Provider} App"));
                }

                var failedResult = AuthenticateWithAccessToken(authService, session, tokens, request.AccessToken);
                var isHtml       = authService.Request.IsHtml();
                if (failedResult != null)
                {
                    return(ConvertToClientError(failedResult, isHtml));
                }

                return(isHtml
                    ? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))
                    : null); //return default AuthenticateResponse
            }

            var authServer = new AuthorizationServerDescription {
                AuthorizationEndpoint = new Uri(this.AuthorizeUrl), TokenEndpoint = new Uri(this.AccessTokenUrl)
            };

            AuthServerFilter?.Invoke(authServer);

            var authClient = new WebServerClient(authServer, this.ConsumerKey)
            {
                ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(this.ConsumerSecret),
            };

            AuthClientFilter?.Invoke(authClient);

            var authState = ProcessUserAuthorization(authClient, authServer, authService);

            if (authState == null)
            {
                try
                {
                    var authReq         = authClient.PrepareRequestUserAuthorization(this.Scopes, new Uri(this.CallbackUrl));
                    var authContentType = authReq.Headers[HttpHeaders.ContentType];
                    var httpResult      = new HttpResult(authReq.ResponseStream, authContentType)
                    {
                        StatusCode = authReq.Status, StatusDescription = "Moved Temporarily"
                    };
                    foreach (string header in authReq.Headers)
                    {
                        httpResult.Headers[header] = authReq.Headers[header];
                    }

                    foreach (string name in authReq.Cookies)
                    {
                        var cookie = authReq.Cookies[name];
                        if (cookie != null)
                        {
                            httpResult.Cookies.Add(cookie.ToCookie());
                        }
                    }

                    this.SaveSession(authService, session, SessionExpiry);
                    return(httpResult);
                }
                catch (ProtocolException ex)
                {
                    Log.Error("Failed to login to {0}".Fmt(this.Provider), ex);
                    return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "Unknown"))));
                }
            }

            var accessToken = authState.AccessToken;

            if (accessToken != null)
            {
                tokens.RefreshToken       = authState.RefreshToken;
                tokens.RefreshTokenExpiry = authState.AccessTokenExpirationUtc;
            }

            if (accessToken != null)
            {
                try
                {
                    return(AuthenticateWithAccessToken(authService, session, tokens, accessToken)
                           ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1"))));
                }
                catch (WebException we)
                {
                    var statusCode = ((HttpWebResponse)we.Response).StatusCode;
                    if (statusCode == HttpStatusCode.BadRequest)
                    {
                        return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))));
                    }
                }
            }

            return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "RequestTokenFailed"))));
        }
コード例 #27
0
ファイル: FBClient.cs プロジェクト: tjsas1/RHP
 public FBClient()
     : base(FacebookDescription)
 {
     ClientIdentifier           = facebookAppID;
     ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(facebookAppSecret);
 }
コード例 #28
0
ファイル: OAuth.cs プロジェクト: PopMedNet-Team/ADAPTABLE
 public static IAuthProviderDefinition Facebook(string appId, string appSecret)
 {
     return(new OAuthProvider("{D8AEC9E8-9146-4789-86B4-8CC1AFFF3024}", "Facebook", "facebook.jpg",
                              "https://graph.facebook.com/oauth/access_token", "https://graph.facebook.com/oauth/authorize",
                              appId, ClientCredentialApplicator.PostParameter(appSecret)));
 }
コード例 #29
0
 public OAuthClient(AuthorizationServerDescription serverDescription, string clientId, string clientSecret, Uri redirectUri)
     : base(serverDescription, clientId, clientSecret)
 {
     _redirectUri = redirectUri;
     ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(clientSecret);
 }
コード例 #30
0
 public WeiboClient(AuthorizationServerDescription authorizationServer, string clientIdentifier, ClientCredentialApplicator clientCredentialApplicator) : base(authorizationServer, clientIdentifier, clientCredentialApplicator)
 {
 }