//private void Save(string date)
        //{
        //    Configuration connectionConfiguration = WebConfigurationManager.OpenWebConfiguration("~");
        //    connectionConfiguration.AppSettings.Settings["access_token"].Value = date;
        //    connectionConfiguration.Save(ConfigurationSaveMode.Modified);
        //    ConfigurationManager.RefreshSection("appSettings");
        //}
        private static IAuthorizationState GetAccessToken()
        {
            var authorizationServer = new AuthorizationServerDescription
            {
                TokenEndpoint = new Uri(ConfigurationManager.AppSettings["Link_AccessToken"]),
                ProtocolVersion = ProtocolVersion.V20

            };
            var client = new WebServerClient(authorizationServer, ConfigurationManager.AppSettings["LinkHost"]);
            client.ClientIdentifier = ConfigurationManager.AppSettings["AppId"];
            client.ClientSecret = ConfigurationManager.AppSettings["AppSecret"];

            var state = client.GetClientAccessToken(null);
            return state;
        }
        /// <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,
            AuthorizationState existingState,
            bool requireUserToken,
            string redirectUri,
            IAuthorizeCodeProvider codeProvider)
        {
            AuthorizationServerDescription serverDescription = GetServerDescription(authBaseUri);
            ClientBase client;
            IAuthorizationState 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);
                    Uri uri = userClient.RequestUserAuthorization(scopes, returnTo: returnTo);
                    Uri 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(client.CreateAuthorizingHandler(state), state);
        }
Example #3
0
        //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();
        }
        public ViewResult ClientCredentialsGrant(ClientCredentialsGrantViewModel model)
        {
            if (this.ModelState.IsValid)
            {
                try
                {
                    // Create the client with which we will be connecting to the server.
                    var webServerClient = new WebServerClient(_authServerDescription, clientIdentifier: model.ClientId, clientSecret: model.ClientSecret);

                    // The scope that we request for the client. Note: this can also be null if we don't want to request any specific
                    // scope or more than one scope if we want to request an access token that is valid for several scopes
                    var clientScopes = OAuthUtilities.SplitScopes(model.Scope ?? string.Empty);

                    // Request a new client access token for the specified scopes (http://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-4.4)
                    // This method will use the client identifier and client secret used when constructing the WebServerAgentClient instance
                    this.ViewBag.AccessToken = webServerClient.GetClientAccessToken(clientScopes);
                }
                catch (Exception ex)
                {
                    this.ViewBag.Exception = ex;
                }
            }

            return this.View(model);
        }