コード例 #1
0
        private static void ClientCredentialFlow()
        {
            Console.WriteLine("Processing client credential flow" + Environment.NewLine);

            var client = new OAuth2Client(new Uri(Endpoint + "/issue/oidc/token"), ClientId, ClientSecret);

            var taks = client.RequestClientCredentialsAsync(Scope);
            taks.Wait();
            var tokenResponse = taks.Result;

            Console.WriteLine("Access token received .. " + Environment.NewLine);

            Console.WriteLine(tokenResponse.AccessToken + Environment.NewLine);

            Console.WriteLine("Calling refresh token endpoint" + Environment.NewLine);

            Task<TokenResponse> refreshTokenResponse = client.RequestRefreshTokenAsync(tokenResponse.RefreshToken);
            refreshTokenResponse.Wait();
            tokenResponse = refreshTokenResponse.Result;

            Console.WriteLine("Access token received using refresh token .. " + Environment.NewLine);

            Console.WriteLine(tokenResponse.AccessToken + Environment.NewLine);

            RevokeToken(tokenResponse.AccessToken, "access_token");
        }
コード例 #2
0
        private static TokenResponse RequestToken()
        {
            "Requesting token.".ConsoleYellow();

            var client = new OAuth2Client(
                new Uri(Constants.AS.OAuth2TokenEndpoint),
                Constants.Clients.ResourceOwnerClient,
                Constants.Clients.ResourceOwnerClientSecret);
            TokenResponse response = null;
            try
            {
                response =
                    client.RequestResourceOwnerPasswordAsync("pibline.authorization", "letmein","read").Result;
                client.RequestClientCredentialsAsync();

                Console.WriteLine(" access token");
                response.AccessToken.ConsoleGreen();

                Console.WriteLine("\n refresh token");
                response.RefreshToken.ConsoleGreen();
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            return response;
        }
コード例 #3
0
        static TokenResponse GetClientToken()
        {
            var client = new OAuth2Client(
                new Uri("https://localhost:44333/connect/token"),
                "silicon",
                "F621F470-9731-4A25-80EF-67A6F7C5F4B8");

            return client.RequestClientCredentialsAsync("api1").Result;
        }
コード例 #4
0
        static TokenResponse RequestToken()
        {
            var client = new OAuth2Client(
                new Uri(Constants.TokenEndpoint),
                "client",
                "secret");

            return client.RequestClientCredentialsAsync("read write").Result;
        }
コード例 #5
0
        private async Task<TokenResponse> GetTokenAsync()
        {
            var client = new OAuth2Client(
                new Uri("https://localhost:44319/identity/connect/token"),
                "mvc_service",
                "secret");

            return await client.RequestClientCredentialsAsync("sampleApi");
        }
コード例 #6
0
        /// <summary>
        /// Get a token using Thinktecture OAuth2Client
        /// </summary>
        /// <returns></returns>
        public static string GetToken()
        {
            var client = new OAuth2Client(
                new Uri(ConfigurationManager.AppSettings["Authority"] + "/connect/token"),
                _clientId,
                _clientSecret);

            var response = client.RequestClientCredentialsAsync("bimtoolkitapi").Result;

            return response.AccessToken;
        }
コード例 #7
0
        private static TokenResponse RequestToken()
        {
            "Requesting token.".ConsoleYellow();

            var client = new OAuth2Client(
                new Uri(Constants.AS.OAuth2TokenEndpoint),
                Constants.Clients.Client,
                Constants.Clients.ClientSecret);

            var response = client.RequestClientCredentialsAsync("read").Result;

            Console.WriteLine(" access token");
            response.AccessToken.ConsoleGreen();
            
            Console.WriteLine();
            return response;
        }
コード例 #8
0
        async Task <TokenResponse> GetGFSTokenAsync()
        {
            var uri = new Uri(@"https://identity.justshoutgfs.com/connect/token");

            var client = new Thinktecture.IdentityModel.Client.OAuth2Client(
                uri, P4MConsts.GfsClientId, P4MConsts.GfsClientSecret);

            var tokenResponse = await client.RequestClientCredentialsAsync("read checkout-api");

            if (tokenResponse == null || tokenResponse.AccessToken == null)
            {
                throw new Exception("Request for client credentials denied");
            }
            //Response.Cookies["gfsCheckoutToken"].Value = token;
            //Response.Cookies["gfsCheckoutToken"].Expires = DateTime.UtcNow.AddSeconds(tokenResponse.ExpiresIn);
            return(tokenResponse);
        }
コード例 #9
0
        private async static Task ClientCredentialFlow()
        {
            try
            {
                var oauthClient = new OAuth2Client(new Uri("http://localhost:1642/token"), "angular", "secret");
                var tokenResponse = oauthClient.RequestClientCredentialsAsync("read").Result;

                var client = new HttpClient();
                client.SetBearerToken(tokenResponse.AccessToken);

                var response = await client.GetStringAsync(new Uri("http://localhost:1642/api/secure/data"));
                Console.WriteLine(response);
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
コード例 #10
0
        private void buttonGetOAuthToken_Click(object sender, EventArgs e)
        {
            textBoxToken.Text = string.Empty;
            try
            {
                // Getting a Token
                string uri = textBoxTokenEndpoint.Text;
                string clientid = textBoxClientId.Text;
                string secret = textBoxSecret.Text;
                string theToken = string.Empty;
                long HowLongTillExpires = long.MinValue;

                if(radioButtonThinkTecture.Checked)
                {
                    // Using the Thinktecture.IdentityModel.Client
                    var client = new OAuth2Client(
                        new Uri(uri),
                        clientid,
                        secret);

                    // For Thinktecture the "scope" request is passed in.
                    var response = client.RequestClientCredentialsAsync("read write").Result;

                    // At this point we now have the AccessToken in the response
                    theToken = response.AccessToken;
                    HowLongTillExpires = response.ExpiresIn;
                }
                else if(radioButtonStandardHttpClient.Checked)
                {
                    // Using standard http, we can make the call with Basic Authorization header
                    // We need to encode the "scope" as formUrlEncoded body
                    // First prepare the Base64Encode string for Basic Auth
                    string data = string.Format("{0}:{1}", clientid, secret);
                    byte[] binaryData = System.Text.Encoding.UTF8.GetBytes(data);
                    string authorizationString = System.Convert.ToBase64String(binaryData, 0, binaryData.Length);

                    using (var client = new HttpClient())
                    {
                        //Add Basic Authorization header for call to get OAuth token.
                        client.SetToken("Basic", authorizationString);

                        //Create specific request to send
                        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);

                        //Pass in oAuth "grant_type" as "client credentials" and "scope" as "read write"
                        //These must be application-form-url-encoded
                        List<KeyValuePair<string, string>> bodyContentList = new List<KeyValuePair<string, string>>();
                        bodyContentList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
                        bodyContentList.Add(new KeyValuePair<string, string>("scope", "read write"));
                        request.Content = new FormUrlEncodedContent(bodyContentList);

                        //Send request
                        HttpResponseMessage response = client.SendAsync(request).Result;
                        if (response.IsSuccessStatusCode)
                        {
                            string oAuthResponseString = response.Content.ReadAsStringAsync().Result;

                            //An example of using dynamic keyword and accessing properties ("access_token" and "expires_in") at runtime.
                            dynamic oAuthToken = JsonConvert.DeserializeObject(oAuthResponseString);
                            theToken = oAuthToken.access_token;
                            HowLongTillExpires = oAuthToken.expires_in;
                        }
                        else
                        {
                            throw new System.Exception("Unable to acquire token.");
                        }
                    }

                }
                else
                {
                    throw new Exception("Invalid Client selected");
                }

                textBoxToken.Text = theToken;
                textBoxExpiresInSeconds.Text = HowLongTillExpires.ToString();

            }
            catch(System.Exception exp)
            {
                textBoxToken.Text = string.Format("Unable to get token.{0}{1}", System.Environment.NewLine, exp.ToString());
            }
        }
コード例 #11
0
ファイル: Startup.cs プロジェクト: bkcrux/WebAPIDemo
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            AntiForgeryConfig.UniqueClaimTypeIdentifier = "unique_user_key";

            app.UseResourceAuthorization(new AuthorizationManager());

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = "mvc",
                Authority = ExpenseTrackerConstants.IdSrv,
                RedirectUri = ExpenseTrackerConstants.ExpenseTrackerClient,
                SignInAsAuthenticationType = "Cookies",
                
                ResponseType = "code id_token token",
                Scope = "openid profile roles",

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {

                    MessageReceived = async n =>
                    {
                        EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.IdToken);
                        EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.AccessToken);

                        //var userInfo = await EndpointAndTokenHelper.CallUserInfoEndpoint(n.ProtocolMessage.AccessToken);    

                    },

                    SecurityTokenValidated = async n =>
                    {                         
                        var userInfo = await EndpointAndTokenHelper.CallUserInfoEndpoint(n.ProtocolMessage.AccessToken);


                        var givenNameClaim = new Claim(
                            Thinktecture.IdentityModel.Client.JwtClaimTypes.GivenName,
                            userInfo.Value<string>("given_name"));

                        var familyNameClaim = new Claim(
                            Thinktecture.IdentityModel.Client.JwtClaimTypes.FamilyName,
                            userInfo.Value<string>("family_name"));

                        var roles = userInfo.Value<JArray>("role").ToList();
 
                        var newIdentity = new ClaimsIdentity(
                           n.AuthenticationTicket.Identity.AuthenticationType,
                           Thinktecture.IdentityModel.Client.JwtClaimTypes.GivenName,
                           Thinktecture.IdentityModel.Client.JwtClaimTypes.Role);

                        newIdentity.AddClaim(givenNameClaim);
                        newIdentity.AddClaim(familyNameClaim);

                        foreach (var role in roles)
                        {
                            newIdentity.AddClaim(new Claim(
                            Thinktecture.IdentityModel.Client.JwtClaimTypes.Role,
                            role.ToString()));
                        }

                        var issuerClaim = n.AuthenticationTicket.Identity
                            .FindFirst(Thinktecture.IdentityModel.Client.JwtClaimTypes.Issuer);
                        var subjectClaim = n.AuthenticationTicket.Identity
                            .FindFirst(Thinktecture.IdentityModel.Client.JwtClaimTypes.Subject);

                        newIdentity.AddClaim(new Claim("unique_user_key",
                            issuerClaim.Value + "_" + subjectClaim.Value));


                        var oAuth2Client = new OAuth2Client(
                         new Uri(ExpenseTrackerConstants.IdSrvToken),
                         "mvc_api",
                         "secret");

                        var response = oAuth2Client.RequestClientCredentialsAsync("expensetrackerapi").Result;

                        // add the token                        
                        newIdentity.AddClaim(new Claim("access_token",
                      response.AccessToken));


                        n.AuthenticationTicket = new AuthenticationTicket(
                            newIdentity,
                            n.AuthenticationTicket.Properties);

                    },


                }

                                 
              
                });

            
        }
コード例 #12
0
 public async Task<Authenticator> GetClientCredentialsAuthenticatorAsync()
 {
     var client = new OAuth2Client(authorizationEndpoint, options.ClientId, options.ClientSecret, OAuth2Client.ClientAuthenticationStyle.BasicAuthentication);
     TokenResponse tokenResponse = await client.RequestClientCredentialsAsync(options.Scope).ConfigureAwait(false);
     return new Authenticator(this, tokenResponse);
 }