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(this.AuthorizationServerDescription, 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));
        }
Esempio n. 2
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();
        }
Esempio n. 3
0
        // GET: ClientCredential
        public async Task <ActionResult> Index()
        {
            ViewBag.ApiResult   = "";
            ViewBag.AccessToken = "";

            if (Request.HttpMethod == "POST")
            {
                var authServer = new AuthorizationServerDescription
                {
                    AuthorizationEndpoint = new Uri(Paths.AuthorizationServerBaseAddress + Paths.AuthorizePath),
                    TokenEndpoint         = new Uri(Paths.AuthorizationServerBaseAddress + Paths.TokenPath)
                };
                var webServerClient = new WebServerClient(authServer, Clients.Client1.Id, Clients.Client1.Secret);

                var state = webServerClient.GetClientAccessToken(new[] { "test1", "test2", "test3" });
                var token = state.AccessToken;
                ViewBag.AccessToken = token;

                var client    = new HttpClient(webServerClient.CreateAuthorizingHandler(token));
                var apiResult = await client.GetStringAsync(Paths.ResourceUserApiPath);

                ViewBag.ApiResult = apiResult;
            }

            return(View());
        }
Esempio n. 4
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));
        }
Esempio n. 5
0
        public static string Token()
        {
            var authorizationServerUri = new Uri(helper.sWebServer);
            var authorizationServer    = new AuthorizationServerDescription
            {
                AuthorizationEndpoint = new Uri(authorizationServerUri, "/RevQA/Ver.Identity.Service/ClientOAuth/Authorize"), TokenEndpoint = new Uri(authorizationServerUri, "/RevQA/Ver.Identity.Service/ClientOAuth/Token")
            };
            WebServerClient _webServerClient = new WebServerClient(authorizationServer, "RevPlus_QA1", "f5c12007d5437abc584997852365247a5450e01f85e5f7f0");
            var             state            = _webServerClient.GetClientAccessToken(new[] { "/api/OAuth/UserInfo" });
            string          _accessToken     = "Bearer " + state.AccessToken;

            return(_accessToken);
        }
Esempio n. 6
0
        private void PrepareAccessToken()
        {
            if (AuthState != null && AuthState.AccessTokenExpirationUtc > DateTimeOffset.UtcNow.AddSeconds(1))
            {
                return;
            }

            var serverDescription = new AuthorizationServerDescription
            {
                TokenEndpoint = new Uri(TokenEndpoint)
            };

            var client = new WebServerClient(serverDescription, OAuth2ClientId, OAuth2ClientSecret);

            var scopes = "bets players transactions".Split(' ');

            AuthState = client.GetClientAccessToken(scopes);
        }
Esempio n. 7
0
        private async Task <string> MakeRequest(string endpoint)
        {
            var AuthEndpoint = new AuthorizationServerDescription
            {
                TokenEndpoint   = new Uri("https://anilist.co/api/auth/access_token"),
                ProtocolVersion = ProtocolVersion.V20
            };

            var clientid     = _config["anilist:clientId"];
            var clientsecret = _config["anilist:clientSecret"];

            WebServerClient client = new WebServerClient(AuthEndpoint, clientid, clientsecret);

            // - Get access token
            var token = client.GetClientAccessToken();

            // - Request
            RestRequest request = new RestRequest()
            {
                Method = Method.GET
            };

            request.AddHeader("Authorization", "Bearer " + token.AccessToken);
            request.AddHeader("Content-Type", "application/json");

            // - Rest request setting
            var restclient = new RestClient("https://anilist.co/api/" + endpoint);

            restclient.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(token.AccessToken);

            // - Send request
            var response = await restclient.ExecuteTaskAsync(request);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return(null);
            }

            return(Regex.Unescape(response.Content));
        }
Esempio n. 8
0
 public ActionResult Index(bool flag)
 {
     if (Authorization == null)
     {
         Authorization = _client.GetClientAccessToken();
     }
     else if (Authorization.AccessTokenExpirationUtc < DateTime.UtcNow)
     {
         return(View());
     }
     else
     {
         var request = new HttpRequestMessage(new HttpMethod("GET"), "http://demo.openapi.cn/bookcates");
         using (var httpClient = new HttpClient(_client.CreateAuthorizingHandler(Authorization)))
         {
             using (var resourceResponse = httpClient.SendAsync(request))
             {
                 ViewBag.Result = resourceResponse.Result.Content.ReadAsStringAsync().Result;
             }
         }
     }
     return(View(Authorization));
 }
Esempio n. 9
0
        private static void RequestToken()
        {
            var state = _webServerClient.GetClientAccessToken(new[] { "bio", "notes" });

            _accessToken = state.AccessToken;
        }
Esempio n. 10
0
        private static void RequestToken()
        {
            var state = _webServerClient.GetClientAccessToken();

            _accessToken = state.AccessToken;
        }
Esempio n. 11
0
        private static void RequestToken()
        {
            var state = _webServerClient.GetClientAccessToken(scopes: new string[] { "notas", "administrador" });

            _accessToken = state.AccessToken;
        }