コード例 #1
0
ファイル: AuthController.cs プロジェクト: tezjarl/testBotRepo
        public Task <HttpResponseMessage> Get([FromUri] string code)
        {
            var ctx = HttpContext.Current;
            AuthorizationCodeTokenRequest request = new AuthorizationCodeTokenRequest();

            request.Code         = code;
            request.ClientId     = "208591536551-cs18qgtasrdjha3vb7b22j09phblif5v.apps.googleusercontent.com";
            request.ClientSecret = "cDfAZUQ8FaGm3QwstTwsut93";
            request.RedirectUri  = @"http://*****:*****@"https://accounts.google.com/o/oauth2/token",
                                           new CancellationToken(), null).Result;

            return(new Task <HttpResponseMessage>(() =>
            {
                return new HttpResponseMessage();
            }));
        }
コード例 #2
0
        public async Task <TokenResponse> ExchangeCodeForTokenAsync(string userId, string code, string redirectUri,
                                                                    CancellationToken taskCancellationToken)
        {
            var authorizationCodeTokenReq = new AuthorizationCodeTokenRequest
            {
                Scope       = string.Join(" ", Scopes),
                RedirectUri = redirectUri,
                Code        = code,
            };

            var token = await FetchTokenAsync(userId, authorizationCodeTokenReq, taskCancellationToken)
                        .ConfigureAwait(false);

            await StoreTokenAsync(userId, token, taskCancellationToken).ConfigureAwait(false);

            return(token);
        }
コード例 #3
0
        private async Task <TokenResponse> RequestTokenFromAuthCode(string authCode)
        {
            var tokenRequest = new AuthorizationCodeTokenRequest
            {
                Code         = authCode,
                Scope        = YouTubeService.Scope.Youtube,
                ClientId     = _secrets.Secrets.ClientId,
                ClientSecret = _secrets.Secrets.ClientSecret,
                RedirectUri  = "postmessage",
            };

            var tokenResponse = await tokenRequest.ExecuteAsync(new HttpClient(),
                                                                TokenServerUrl,
                                                                CancellationToken.None,
                                                                SystemClock.Default);

            return(tokenResponse);
        }
コード例 #4
0
ファイル: Startup.Auth.cs プロジェクト: LeonGelden/Authies
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification arg)
        {
            var tokenClient     = new HttpClient();
            var authCodeRequest = new AuthorizationCodeTokenRequest
            {
                Address      = string.Concat(authority, "/oauth2/v2.0/token"),
                ClientId     = clientId,
                ClientSecret = clientSecret,
                RedirectUri  = "https://localhost:6002/signin-oidc",
                Code         = arg.Code,
            };

            authCodeRequest.Parameters.Add("Scope", "https://klowdsoft.onmicrosoft.com/ResourceApi1/Authies.ResourceApi1.Read");

            var response = await tokenClient.RequestAuthorizationCodeTokenAsync(authCodeRequest);

            arg.AuthenticationTicket.Identity.AddClaim(new System.Security.Claims.Claim("access_token", response.AccessToken));
        }
コード例 #5
0
 public async void ExchangeCodeForTokensExecute()
 {
     await DirtyJob(async() =>
     {
         var disco   = await GetAddressesAsync(cancellationTokenSource.Token);
         var request = new AuthorizationCodeTokenRequest()
         {
             Address      = disco.TokenEndpoint,
             ClientId     = this.ClientId,
             ClientSecret = this.ClientSecret,
             RedirectUri  = this.RedirectUrl,
             Code         = this.AuthorizationCode,
         };
         var tokens = await httpClient.RequestAuthorizationCodeTokenAsync(request, cancellationTokenSource.Token);
         if (tokens.IsError)
         {
             this.IdToken      = null;
             this.AccessToken  = null;
             this.ExpiresIn    = 0;
             this.TokenType    = null;
             this.RefreshToken = null;
             MessengerInstance.Send(new AlertMessage()
             {
                 Title   = "Error",
                 Message = tokens.ErrorDescription ?? tokens.Error,
                 Type    = AlertMessage.AlertType.Error,
             });
         }
         else
         {
             this.IdToken      = tokens.IdentityToken;
             this.AccessToken  = tokens.AccessToken;
             this.ExpiresIn    = tokens.ExpiresIn;
             this.TokenType    = tokens.TokenType;
             this.RefreshToken = tokens.RefreshToken;
             MessengerInstance.Send(new AlertMessage()
             {
                 Title   = "Information",
                 Message = "Authorization Code exchanged for tokens successfully!",
                 Type    = AlertMessage.AlertType.Information,
             });
         }
     });
 }
コード例 #6
0
        /// <summary>
        /// Request an Access Token using the Authorization Code Grant flow.
        /// </summary>
        /// <param name="request">The <see cref="AuthorizationCodeTokenRequest"/> containing the information of the request.</param>
        /// <returns>An <see cref="AccessTokenResponse"/> containing the token information</returns>
        public async Task <AccessTokenResponse> GetTokenAsync(AuthorizationCodeTokenRequest request)
        {
            var response = await Connection.PostAsync <AccessTokenResponse>("oauth/token", null, new Dictionary <string, object>
            {
                { "grant_type", "authorization_code" },
                { "client_id", request.ClientId },
                { "client_secret", request.ClientSecret },
                { "code", request.Code },
                { "redirect_uri", request.RedirectUri },
            },
                                                                            null,
                                                                            null,
                                                                            null,
                                                                            null).ConfigureAwait(false);

            await AssertIdTokenValid(response.IdToken, request.ClientId);

            return(response);
        }
コード例 #7
0
        /// <summary>
        /// Request an Access Token using the Authorization Code Grant flow.
        /// </summary>
        /// <param name="request">The <see cref="AuthorizationCodeTokenRequest"/> containing the information of the request.</param>
        /// <returns>An <see cref="AccessTokenResponse"/> containing the token information</returns>
        public async Task <AccessTokenResponse> GetTokenAsync(AuthorizationCodeTokenRequest request)
        {
            var response = await Connection.PostAsync <AccessTokenResponse>("oauth/token", null, new Dictionary <string, object>
            {
                { "grant_type", "authorization_code" },
                { "client_id", request.ClientId },
                { "client_secret", request.ClientSecret },
                { "code", request.Code },
                { "redirect_uri", request.RedirectUri },
            },
                                                                            null,
                                                                            null,
                                                                            null,
                                                                            null);

            IdentityTokenValidator validator = new IdentityTokenValidator();
            await validator.ValidateAsync(response.IdToken, _baseUri.AbsoluteUri, request.ClientId);

            return(response);
        }
コード例 #8
0
        public async Task Auth(string code, string scope, string state)
        {
            var client = new HttpClient();

            var tokenRequest = new AuthorizationCodeTokenRequest
            {
                ClientId     = "cf.client",
                ClientSecret = "secret",
                Address      = $"{authserverurl}/connect/token",
                Code         = code,
                RedirectUri  = "http://localhost:5002/home/auth",
                GrantType    = "authorization_code"
            };

            var credentialsResponse = client.RequestAuthorizationCodeTokenAsync(tokenRequest);

            if (credentialsResponse.Result.IsError)
            {
                Console.WriteLine(credentialsResponse.Result.Error);
                return;
            }

            client.SetBearerToken(credentialsResponse.Result.AccessToken);

            var response = await client.GetAsync("http://localhost:5003/api/values");

            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.StatusCode);
            }
            else
            {
                var content = await response.Content.ReadAsStringAsync();

                Console.WriteLine(content);
            }

            GetUserInfo(credentialsResponse.Result.AccessToken);

            return;
        }
コード例 #9
0
        static void Main(string[] args)
        {
            var authCode = "YOUR_FRESH_SERVER_AUTH_CODE";

            var path   = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"client_secret.json");
            var config = File.ReadAllText(path, Encoding.UTF8);

            GoogleClientSecrets clientSecrets = GoogleClientSecrets.Load(new FileStream(path, FileMode.Open));

            var request = new AuthorizationCodeTokenRequest()
            {
                ClientId     = clientSecrets.Secrets.ClientId,
                ClientSecret = clientSecrets.Secrets.ClientSecret,
                RedirectUri  = "",
                Code         = authCode,
                GrantType    = "authorization_code"
            };

            var tokenResponse = request.ExecuteAsync(new System.Net.Http.HttpClient(), "https://www.googleapis.com/oauth2/v4/token", new System.Threading.CancellationToken(), Google.Apis.Util.SystemClock.Default).GetAwaiter().GetResult();

            Console.ReadLine();
        }
コード例 #10
0
 internal static Tokenizer RequestAuthorizationCodeToken(this IRestClient client, AuthorizationCodeTokenRequest tokenRequest)
 {
     return(Execute(client, tokenRequest, GrantType.AuthorizationCode));
 }
コード例 #11
0
        public async Task <TokenResponse?> GetTokenAsync(CancellationToken ct = default)
        {
            if (token == null || DateTime.Now >= tokenExpiry)
            {
                var discovery = await discoveryCache.GetAsync().ConfigureAwait(false);

                if (discovery.IsError)
                {
                    OnTrace?.Invoke($"{nameof(discovery)} response has errors: {discovery.Error}");
                    return(token);
                }

                if (token == null)
                {
                    switch (oidcSettings.GrantType)
                    {
                    case OidcConstants.GrantTypes.Password:
                        using (var tokenRequest = new PasswordTokenRequest
                        {
                            Address = discovery.TokenEndpoint,
                            ClientId = oidcSettings.ClientId,
                            ClientSecret = oidcSettings.ClientSecret,
                            Scope = oidcSettings.Scope,
                            UserName = oidcSettings.Username,
                            Password = oidcSettings.Password
                        })
                        {
                            token = await httpClient.RequestPasswordTokenAsync(tokenRequest, ct).ConfigureAwait(false);

                            break;
                        }

                    case OidcConstants.GrantTypes.ClientCredentials:
                        using (var tokenRequest = new ClientCredentialsTokenRequest
                        {
                            Address = discovery.TokenEndpoint,
                            ClientId = oidcSettings.ClientId,
                            ClientSecret = oidcSettings.ClientSecret,
                            Scope = oidcSettings.Scope
                        })
                        {
                            token = await httpClient.RequestClientCredentialsTokenAsync(tokenRequest, ct).ConfigureAwait(false);

                            break;
                        }

                    case OidcConstants.GrantTypes.AuthorizationCode:
                        using (var tokenRequest = new AuthorizationCodeTokenRequest
                        {
                            Address = discovery.TokenEndpoint,
                            ClientId = oidcSettings.ClientId,
                            ClientSecret = oidcSettings.ClientSecret,
                            Code = oidcSettings.Code,
                            RedirectUri = oidcSettings.RedirectUri?.ToString(),
                            CodeVerifier = oidcSettings.CodeVerifier
                        })
                        {
                            token = await httpClient.RequestAuthorizationCodeTokenAsync(tokenRequest, ct).ConfigureAwait(false);

                            break;
                        }

                    default:
                        throw new NotSupportedException($"Grant type '{oidcSettings.GrantType}' is not supported");
                    }
                }
                else
                {
                    using var request = new RefreshTokenRequest
                          {
                              Address      = discovery.TokenEndpoint,
                              ClientId     = oidcSettings.ClientId,
                              ClientSecret = oidcSettings.ClientSecret,
                              Scope        = oidcSettings.Scope,
                              RefreshToken = token.RefreshToken
                          };
                    token = await httpClient.RequestRefreshTokenAsync(request, ct).ConfigureAwait(false);
                }

                if (token.IsError)
                {
                    OnTrace?.Invoke($"{nameof(token)} response has errors: {token.Error}");
                    return(token);
                }

                tokenExpiry = DateTime.Now.AddSeconds(token.ExpiresIn - 10);
            }

            return(token);
        }
コード例 #12
0
 public AdfsAuthorizationCodeFlow(Uri serviceUri, AuthorizationCodeTokenRequest tokenRequest)
     : base(serviceUri, tokenRequest)
 {
 }
コード例 #13
0
 public Task <AccessTokenResponse> GetTokenAsync(AuthorizationCodeTokenRequest request, CancellationToken cancellationToken = default)
 {
     return(_getToken(request, cancellationToken));
 }
コード例 #14
0
 public AuthorizationCodeFlowTests()
 {
     _tokenRequest = new AuthorizationCodeTokenRequest("myClient", "mySecret", "myScope", new Uri("https://www.myapplication.net"));
     _serviceUri   = new Uri("https://adfs.example.com");
 }
コード例 #15
0
 public Task <AccessTokenResponse> GetTokenAsync(AuthorizationCodeTokenRequest request)
 {
     return(_getToken(request));
 }
コード例 #16
0
    /// <summary>
    /// Sends a token request using the authorization_code grant type.
    /// </summary>
    /// <param name="client">The client.</param>
    /// <param name="request">The request.</param>
    /// <param name="cancellationToken">The cancellation token.</param>
    /// <returns></returns>
    public static async Task <TokenResponse> RequestAuthorizationCodeTokenAsync(this HttpMessageInvoker client, AuthorizationCodeTokenRequest request, CancellationToken cancellationToken = default)
    {
        var clone = request.Clone();

        clone.Parameters.AddRequired(OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.AuthorizationCode);
        clone.Parameters.AddRequired(OidcConstants.TokenRequest.Code, request.Code);
        clone.Parameters.AddRequired(OidcConstants.TokenRequest.RedirectUri, request.RedirectUri);
        clone.Parameters.AddOptional(OidcConstants.TokenRequest.CodeVerifier, request.CodeVerifier);

        foreach (var resource in request.Resource)
        {
            clone.Parameters.AddRequired(OidcConstants.TokenRequest.Resource, resource, allowDuplicates: true);
        }

        return(await client.RequestTokenAsync(clone, cancellationToken).ConfigureAwait());
    }
コード例 #17
0
        public async Task <ActionResult> Code(AuthorizationCodeTokenRequest request)
        {
            var result = await _sessionHandleService.GetAccessToken(request);

            return(FromResponse(result));
        }
コード例 #18
0
 internal static Task<Tokenizer> RequestAuthorizationCodeTokenAsync(this IRestClient client, AuthorizationCodeTokenRequest tokenRequest, CancellationToken cancellationToken = default)
 {
     return ExecuteAsync(client, tokenRequest, GrantType.AuthorizationCode, cancellationToken);
 }
コード例 #19
0
 private string _getKey(AuthorizationCodeTokenRequest r)
 {
     return($"AuthorizationCodeTokenRequest{r.ClientId}{r.Code}"); // code should be enough, but being on safe side
 }
コード例 #20
0
 public AcsAuthorizationCodeFlow(Uri serviceUri, AuthorizationCodeTokenRequest tokenRequest, IHttpClient httpAdapter)
     : base(serviceUri, tokenRequest, httpAdapter)
 {
 }