コード例 #1
0
 public TokenClient CreateTokenClient(bool reset)
 {
     if (tokenClient == null || reset)
     {
         tokenClient = new AndroidTokenClient();
     }
     return tokenClient;
 }
コード例 #2
0
ファイル: Default.aspx.cs プロジェクト: papyr/IntuitExamples
        /// <summary>
        /// Start code exchange to get the Access Token and Refresh Token
        /// </summary>
        /// <returns></returns>
        public async System.Threading.Tasks.Task performCodeExchange()
        {
            output("Exchanging code for tokens.");

            string id_token            = "";
            string refresh_token       = "";
            string access_token        = "";
            bool   isTokenValid        = false;
            string sub                 = "";
            string email               = "";
            string emailVerified       = "";
            string givenName           = "";
            string familyName          = "";
            string phoneNumber         = "";
            string phoneNumberVerified = "";
            string streetAddress       = "";
            string locality            = "";
            string region              = "";
            string postalCode          = "";
            string country             = "";



            //Request Oauth2 tokens
            var tokenClient = new TokenClient(tokenEndpoint, clientID, clientSecret);

            TokenResponse accesstokenCallResponse = await tokenClient.RequestTokenFromCodeAsync(code, redirectURI);

            if (accesstokenCallResponse.HttpStatusCode == HttpStatusCode.OK)
            {
                //save the refresh token in persistent store so that it can be used to refresh short lived access tokens
                refresh_token = accesstokenCallResponse.RefreshToken;
                if (!dictionary.ContainsKey("refreshToken"))
                {
                    dictionary.Add("refreshToken", refresh_token);
                }


                output("Refresh token obtained.");

                //access token
                access_token = accesstokenCallResponse.AccessToken;
                output("Access token obtained.");

                if (!dictionary.ContainsKey("accessToken"))
                {
                    dictionary.Add("accessToken", access_token);
                }

                //Identity Token (returned only for OpenId scope)
                id_token = accesstokenCallResponse.IdentityToken;
                output("Id token obtained.");

                //validate idToken
                isTokenValid = await isIdTokenValid(id_token);

                output("Validating Id Token.");

                output("Calling UserInfo");
                //get userinfo
                //This will work only for SIWI and Get App Now(OpenId) flows
                //Since C2QB flow does not has the required scopes, you will get exception.
                //Here we will handle the exeception and then finally make Payments api call
                //In your code, based on your workflows/scope, you can choose to not make this call
                UserInfoResponse userInfoResponse = await getUserInfo(access_token, refresh_token);

                if (userInfoResponse.HttpStatusCode == HttpStatusCode.OK)
                {
                    //Read UserInfo Details
                    IEnumerable <System.Security.Claims.Claim> userData = userInfoResponse.Json.ToClaims();

                    foreach (System.Security.Claims.Claim item in userData)
                    {
                        if (item.Type == "sub" && item.Value != null)
                        {
                            sub = item.Value;
                        }
                        if (item.Type == "email" && item.Value != null)
                        {
                            email = item.Value;
                        }
                        if (item.Type == "emailVerified" && item.Value != null)
                        {
                            emailVerified = item.Value;
                        }
                        if (item.Type == "givenName" && item.Value != null)
                        {
                            givenName = item.Value;
                        }
                        if (item.Type == "familyName" && item.Value != null)
                        {
                            familyName = item.Value;
                        }
                        if (item.Type == "phoneNumber" && item.Value != null)
                        {
                            phoneNumber = item.Value;
                        }
                        if (item.Type == "phoneNumberVerified" && item.Value != null)
                        {
                            phoneNumberVerified = item.Value;
                        }

                        if (item.Type == "address" && item.Value != null)
                        {
                            Address jsonObject = JsonConvert.DeserializeObject <Address>(item.Value);

                            if (jsonObject.StreetAddress != null)
                            {
                                streetAddress = jsonObject.StreetAddress;
                            }
                            if (jsonObject.Locality != null)
                            {
                                locality = jsonObject.Locality;
                            }
                            if (jsonObject.Region != null)
                            {
                                region = jsonObject.Region;
                            }
                            if (jsonObject.PostalCode != null)
                            {
                                postalCode = jsonObject.PostalCode;
                            }
                            if (jsonObject.Country != null)
                            {
                                country = jsonObject.Country;
                            }
                        }
                    }
                }
            }
            else if (accesstokenCallResponse.HttpStatusCode == HttpStatusCode.Unauthorized && Session["RefreshToken"] != null)
            {
                //Validate if refresh token was already saved in session and use that to regenerate the access token.

                output("Exchanging refresh token for access token.");
                //Handle exception 401 and then make this call
                // Call RefreshToken endpoint to get new access token when you recieve a 401 Status code
                TokenResponse refereshtokenCallResponse = await performRefreshToken(refresh_token);

                if (accesstokenCallResponse.HttpStatusCode == HttpStatusCode.OK)
                {
                    //save the refresh token in persistent store so that it can be used to refresh short lived access tokens
                    refresh_token = accesstokenCallResponse.RefreshToken;
                    if (!dictionary.ContainsKey("refreshToken"))
                    {
                        dictionary.Add("refreshToken", refresh_token);
                    }
                    else
                    {
                        dictionary["refreshToken"] = refresh_token;
                    }

                    output("Refresh token obtained.");


                    //access token
                    access_token = accesstokenCallResponse.AccessToken;

                    output("Access token obtained.");
                    if (!dictionary.ContainsKey("accessToken"))
                    {
                        dictionary.Add("accessToken", access_token);
                    }
                    else
                    {
                        dictionary["accessToken"] = access_token;
                    }


                    //Identity Token (returned only for OpenId scope)
                    id_token = accesstokenCallResponse.IdentityToken;
                    output("Id token obtained.");

                    //validate idToken
                    isTokenValid = await isIdTokenValid(id_token);

                    output("Validating Id Token.");


                    output("Calling UserInfo");
                    //get userinfo
                    //This will work only for SIWI and Get App Now(OpenId) flows
                    //Since C2QB flow does not has the required scopes, you will get exception.
                    //Here we will handle the exeception and then finally make Payments api call
                    //In your code, based on your workflows/scope, you can choose to not make this call
                    UserInfoResponse userInfoResponse = await getUserInfo(access_token, refresh_token);

                    if (userInfoResponse.HttpStatusCode == HttpStatusCode.OK)
                    {
                        //Read UserInfo Details
                        IEnumerable <System.Security.Claims.Claim> userData = userInfoResponse.Json.ToClaims();

                        foreach (System.Security.Claims.Claim item in userData)
                        {
                            if (item.Type == "sub" && item.Value != null)
                            {
                                sub = item.Value;
                            }
                            if (item.Type == "email" && item.Value != null)
                            {
                                email = item.Value;
                            }
                            if (item.Type == "emailVerified" && item.Value != null)
                            {
                                emailVerified = item.Value;
                            }
                            if (item.Type == "givenName" && item.Value != null)
                            {
                                givenName = item.Value;
                            }
                            if (item.Type == "familyName" && item.Value != null)
                            {
                                familyName = item.Value;
                            }
                            if (item.Type == "phoneNumber" && item.Value != null)
                            {
                                phoneNumber = item.Value;
                            }
                            if (item.Type == "phoneNumberVerified" && item.Value != null)
                            {
                                phoneNumberVerified = item.Value;
                            }

                            if (item.Type == "address" && item.Value != null)
                            {
                                Address jsonObject = JsonConvert.DeserializeObject <Address>(item.Value);

                                if (jsonObject.StreetAddress != null)
                                {
                                    streetAddress = jsonObject.StreetAddress;
                                }
                                if (jsonObject.Locality != null)
                                {
                                    locality = jsonObject.Locality;
                                }
                                if (jsonObject.Region != null)
                                {
                                    region = jsonObject.Region;
                                }
                                if (jsonObject.PostalCode != null)
                                {
                                    postalCode = jsonObject.PostalCode;
                                }
                                if (jsonObject.Country != null)
                                {
                                    country = jsonObject.Country;
                                }
                            }
                        }
                    }
                }
            }


            //Redirect to pop-up window for C2QB and SIWI flows

            if (dictionary["callMadeBy"] == "OpenId")
            {
                if (Request.Url.Query == "")
                {
                    Response.Redirect(Request.RawUrl);
                }
                else
                {
                    Response.Redirect(Request.RawUrl.Replace(Request.Url.Query, ""));
                }
            }
        }
コード例 #3
0
        public virtual TokenClient BuildTokenClient(string clientId, string secret = "secret")
        {
            TokenClient tokenClient = new TokenClient($@"{Uri}core/connect/token", clientId, secret, innerHttpMessageHandler: GetHttpMessageHandler());

            return(tokenClient);
        }
コード例 #4
0
        private static void Main(string[] args)
        {
            //using (var sha256 = SHA256.Create())
            //{
            //    // Send a sample text to hash.
            //    var hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes("hello world"));

            //    // Get the hashed string.
            //    var hash = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();

            //    // Print the string.
            //    Console.WriteLine(hash);

            //}

            //string a = "12345678";
            //string a1 = SecurityService.GenerateHashedPassword(a);
            //Console.WriteLine(string.Format("{0}|{1}", a, a1));
            //Console.WriteLine(SecurityService.CompareHashedPassword(a, a1));

            //a = "12345678";
            //a1 = SecurityService.GenerateHashedPassword(a);
            //Console.WriteLine(string.Format("{0}|{1}", a, a1));
            //Console.WriteLine(SecurityService.CompareHashedPassword(a, a1));

            //a = "1234sdfsdsdfsdf5678";
            //a1 = SecurityService.GenerateHashedPassword(a);
            //Console.WriteLine(string.Format("{0}|{1}", a, a1));
            //Console.WriteLine(SecurityService.CompareHashedPassword(a, a1));

            //a = "123434SDSA5678";
            //a1 = SecurityService.GenerateHashedPassword(a);
            //Console.WriteLine(string.Format("{0}|{1}", a, a1));
            //Console.WriteLine(SecurityService.CompareHashedPassword(a, a1));

            //a = "2%^532gjasdhjgsa12343A_sd&@*$#(XNSJD_+5678";
            //a1 = SecurityService.GenerateHashedPassword(a);
            //Console.WriteLine(string.Format("{0}|{1}", a, a1));
            //Console.WriteLine(SecurityService.CompareHashedPassword(a, a1));
            try
            {
                var disco = DiscoveryClient.GetAsync("http://*****:*****@glowny-shop.com", "P@ssw0rd", "api1").Result;

                if (tokenResponse.IsError)
                {
                    Console.WriteLine(tokenResponse.Error);
                    Console.Read();
                    return;
                }

                Console.WriteLine(tokenResponse.Json);

                // call api
                client = new HttpClient();
                client.SetBearerToken(tokenResponse.AccessToken);

                response = client.GetAsync("http://localhost:5555/identity").Result;
                if (!response.IsSuccessStatusCode)
                {
                    Console.WriteLine(response.StatusCode);
                }
                else
                {
                    var content = response.Content.ReadAsStringAsync().Result;
                    Console.WriteLine(JArray.Parse(content));
                }

                Console.WriteLine("\n\n");
            }
            catch { }

            Console.Read();
        }
        public async Task Mint_multi_arbitrary_resource_owner_and_refresh_and_revoke()
        {
            var tokenClient = new TokenClient(
                _fixture.TestServer.BaseAddress + "connect/token",
                ClientId,
                _fixture.MessageHandler);

            Dictionary <string, string> paramaters = new Dictionary <string, string>()
            {
                { OidcConstants.TokenRequest.ClientId, ClientId },
                { OidcConstants.TokenRequest.ClientSecret, ClientSecret },
                { OidcConstants.TokenRequest.GrantType, ArbitraryResourceOwnerExtensionGrant.Constants.ArbitraryResourceOwner },
                {
                    OidcConstants.TokenRequest.Scope,
                    $"{IdentityServerConstants.StandardScopes.OfflineAccess} nitro metal"
                },
                {
                    ArbitraryNoSubjectExtensionGrant.Constants.ArbitraryClaims,
                    "{'role': ['application', 'limited'],'query': ['dashboard', 'licensing'],'seatId': ['8c59ec41-54f3-460b-a04e-520fc5b9973d'],'piid': ['2368d213-d06c-4c2a-a099-11c34adc3579']}"
                },
                {
                    ArbitraryResourceOwnerExtensionGrant.Constants.Subject,
                    "Ratt"
                },
                { ArbitraryNoSubjectExtensionGrant.Constants.AccessTokenLifetime, "3600" }
            };
            var result = await tokenClient.RequestAsync(paramaters);

            result.AccessToken.ShouldNotBeNullOrEmpty();
            result.RefreshToken.ShouldNotBeNull();
            result.ExpiresIn.ShouldNotBeNull();

            // mint a duplicate, this should be 2 refresh tokens.
            var result2 = await tokenClient.RequestAsync(paramaters);

            result.AccessToken.ShouldNotBeNullOrEmpty();
            result.RefreshToken.ShouldNotBeNull();
            result.ExpiresIn.ShouldNotBeNull();

            // first refresh
            paramaters = new Dictionary <string, string>()
            {
                { OidcConstants.TokenRequest.ClientId, ClientId },
                { OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.RefreshToken },
                { OidcConstants.TokenRequest.RefreshToken, result.RefreshToken }
            };
            result = await tokenClient.RequestAsync(paramaters);

            result.AccessToken.ShouldNotBeNullOrEmpty();
            result.RefreshToken.ShouldNotBeNull();
            result.ExpiresIn.ShouldNotBeNull();

            paramaters = new Dictionary <string, string>()
            {
                { OidcConstants.TokenRequest.ClientId, ClientId },
                { OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.RefreshToken },
                { OidcConstants.TokenRequest.RefreshToken, result2.RefreshToken }
            };
            result2 = await tokenClient.RequestAsync(paramaters);

            result2.AccessToken.ShouldNotBeNullOrEmpty();
            result2.RefreshToken.ShouldNotBeNull();
            result2.ExpiresIn.ShouldNotBeNull();

            var revocationTokenClient = new TokenClient(
                _fixture.TestServer.BaseAddress + "connect/revocation",
                ClientId,
                ClientSecret,
                _fixture.MessageHandler);

            paramaters = new Dictionary <string, string>()
            {
                { IdentityServer4Extras.Constants.RevocationArguments.TokenTypeHint, OidcConstants.TokenTypes.RefreshToken },
                { IdentityServer4Extras.Constants.RevocationArguments.Token, result.RefreshToken },
                { IdentityServer4Extras.Constants.RevocationArguments.RevokeAllSubjects, "true" }
            };
            await revocationTokenClient.RequestAsync(paramaters);

            // try refreshing, these should now fail the refresh.
            paramaters = new Dictionary <string, string>()
            {
                { OidcConstants.TokenRequest.ClientId, ClientId },
                { OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.RefreshToken },
                { OidcConstants.TokenRequest.RefreshToken, result.RefreshToken }
            };
            result = await tokenClient.RequestAsync(paramaters);

            result.Error.ShouldNotBeNullOrEmpty();
            result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant);

            paramaters = new Dictionary <string, string>()
            {
                { OidcConstants.TokenRequest.ClientId, ClientId },
                { OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.RefreshToken },
                { OidcConstants.TokenRequest.RefreshToken, result2.RefreshToken }
            };
            result2 = await tokenClient.RequestAsync(paramaters);

            result2.Error.ShouldNotBeNullOrEmpty();
            result2.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant);
        }
コード例 #6
0
        public void SuccessfulTicketAuthentication()
        {
            GrantedTokenResponse   umaToken            = null !;
            AddResourceSetResponse resourceSetResponse = null !;
            UmaClient            umaClient             = null !;
            TokenClient          client = null !;
            GrantedTokenResponse result = null !;
            string ticketId             = null !;

            "and a properly configured token client".x(
                () => client = new TokenClient(
                    TokenCredentials.FromClientCredentials("post_client", "post_client"),
                    _fixture.Client,
                    new Uri(WellKnownOpenidConfiguration)));

            "when requesting token".x(
                async() =>
            {
                var response = await client
                               .GetToken(TokenRequest.FromPassword("user", "password", new[] { "uma_protection", "offline" }))
                               .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;
                result = response.Item;
            });

            "then has valid access token".x(
                () =>
            {
                var tokenHandler         = new JwtSecurityTokenHandler();
                var validationParameters = new TokenValidationParameters
                {
                    IssuerSigningKeys = _jwks.GetSigningKeys(),
                    ValidAudience     = "post_client",
                    ValidIssuer       = "https://localhost"
                };
                tokenHandler.ValidateToken(result.AccessToken, validationParameters, out var token);

                Assert.NotEmpty(((JwtSecurityToken)token).Claims);
            });

            "given a uma client".x(
                () =>
            {
                umaClient = new UmaClient(
                    _fixture.Client,
                    new Uri("https://localhost/.well-known/uma2-configuration"));
            });

            "when creating resource set".x(
                async() =>
            {
                var resourceSet = new ResourceSet {
                    Name = "Local", Scopes = new[] { "api1" }, Type = "url",
                };

                var resourceResponse =
                    await umaClient.AddResource(resourceSet, result.AccessToken).ConfigureAwait(false) as
                    Option <AddResourceSetResponse> .Result;
                resourceSetResponse = resourceResponse.Item;

                Assert.NotNull(resourceResponse);
            });

            "and setting access policy".x(
                async() =>
            {
                var resourceSet = new ResourceSet
                {
                    Id     = resourceSetResponse.Id,
                    Name   = "Local",
                    Scopes = new[] { "api1" },
                    Type   = "url",
                    AuthorizationPolicies = new[]
                    {
                        new PolicyRule
                        {
                            Scopes = new[] { "api1" },
                            Claims = new[]
                            {
                                new ClaimData {
                                    Type = ClaimTypes.NameIdentifier, Value = "user"
                                }
                            },
                            ClientIdsAllowed             = new[] { "post_client" },
                            IsResourceOwnerConsentNeeded = false
                        }
                    }
                };
                var resourceResponse =
                    await umaClient.UpdateResource(resourceSet, result.AccessToken).ConfigureAwait(false) as
                    Option <UpdateResourceSetResponse> .Result;

                Assert.NotNull(resourceResponse);
            });

            "then can get redirection".x(
                async() =>
            {
                var request = new HttpRequestMessage
                {
                    Method     = HttpMethod.Get,
                    RequestUri = new Uri("http://localhost/data/" + resourceSetResponse.Id)
                };
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

                var response = await _fixture.Client().SendAsync(request).ConfigureAwait(false);

                Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
                var httpHeaderValueCollection = response.Headers.WwwAuthenticate;
                Assert.True(httpHeaderValueCollection != null);

                var match = Regex.Match(
                    httpHeaderValueCollection.First().Parameter,
                    ".+ticket=\"(.+)\".*",
                    RegexOptions.Compiled);
                ticketId = match.Groups[1].Value;
            });

            "when requesting token".x(
                async() =>
            {
                var response = await client.GetToken(TokenRequest.FromTicketId(ticketId, result.IdToken))
                               .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;
                umaToken = response.Item;

                Assert.NotNull(umaToken.AccessToken);
            });

            "then can get resource with token".x(
                async() =>
            {
                var request = new HttpRequestMessage
                {
                    Method     = HttpMethod.Get,
                    RequestUri = new Uri("http://localhost/data/" + resourceSetResponse.Id)
                };
                request.Headers.Authorization = new AuthenticationHeaderValue(
                    umaToken.TokenType,
                    umaToken.AccessToken);
                var response = await _fixture.Client().SendAsync(request).ConfigureAwait(false);
                var content  = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                Assert.Equal("\"Hello\"", content);
            });
        }
コード例 #7
0
        public void DefaultPolicyTicketAuthentication()
        {
            AddResourceSetResponse resourceSetResponse = null !;
            UmaClient            umaClient             = null !;
            TokenClient          client = null !;
            GrantedTokenResponse result = null !;
            string ticketId             = null !;

            "and a properly configured token client".x(
                () => client = new TokenClient(
                    TokenCredentials.FromClientCredentials("post_client", "post_client"),
                    _fixture.Client,
                    new Uri(WellKnownOpenidConfiguration)));

            "when requesting token".x(
                async() =>
            {
                var response = await client
                               .GetToken(TokenRequest.FromPassword("user", "password", new[] { "uma_protection" }))
                               .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;
                result = response.Item;
            });

            "then has valid access token".x(
                () =>
            {
                var tokenHandler         = new JwtSecurityTokenHandler();
                var validationParameters = new TokenValidationParameters
                {
                    IssuerSigningKeys = _jwks.GetSigningKeys(),
                    ValidAudience     = "post_client",
                    ValidIssuer       = "https://localhost"
                };
                tokenHandler.ValidateToken(result.AccessToken, validationParameters, out var token);

                Assert.NotEmpty(((JwtSecurityToken)token).Claims);
            });

            "given a uma client".x(
                () => { umaClient = new UmaClient(_fixture.Client, new Uri("https://localhost/")); });

            "when creating resource set without a policy".x(
                async() =>
            {
                var resourceSet = new ResourceSet
                {
                    Name = "Local", Scopes = new[] { "api1" }, Type = "url", AuthorizationPolicies = null
                };

                var resourceResponse =
                    await umaClient.AddResource(resourceSet, result.AccessToken).ConfigureAwait(false) as
                    Option <AddResourceSetResponse> .Result;
                resourceSetResponse = resourceResponse.Item;

                Assert.NotNull(resourceResponse);
            });

            "then can get redirection".x(
                async() =>
            {
                var request = new HttpRequestMessage
                {
                    Method     = HttpMethod.Get,
                    RequestUri = new Uri("http://localhost/data/" + resourceSetResponse.Id)
                };
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

                var response = await _fixture.Client().SendAsync(request).ConfigureAwait(false);

                Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
                var httpHeaderValueCollection = response.Headers.WwwAuthenticate;
                Assert.True(httpHeaderValueCollection != null);

                var match = Regex.Match(
                    httpHeaderValueCollection.First().Parameter,
                    ".+ticket=\"(.+)\".*",
                    RegexOptions.Compiled);
                ticketId = match.Groups[1].Value;
            });

            "when requesting token".x(
                async() =>
            {
                var response = await client.GetToken(TokenRequest.FromTicketId(ticketId, result.IdToken))
                               .ConfigureAwait(false);

                Assert.IsType <Option <GrantedTokenResponse> .Error>(response);
            });
        }
コード例 #8
0
ファイル: UnifiBrowserForm.cs プロジェクト: rfellers/pwiz
        void connect()
        {
            string url = serverLocationTextBox.Text;

            if (!url.Any())
            {
                return;
            }

            // add default unifi port if no port given
            var url2 = new Uri(!url.StartsWith("http") ? "http://" + url : url);

            if (url2.IsDefaultPort)
            {
                url = url.Replace(url2.Host, url2.Host + DefaultUnifiPort);
            }

            // guess scheme if no scheme given
            try
            {
                if (!url.StartsWith("http"))
                {
                    url = (UrlSupportsSSL(url) ? "https://" : "http://") + url;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(this, e.Message, "Error");
                return;
            }

            // add API path if missing
            if (!url.EndsWith(BasePath))
            {
                url += BasePath;
            }

            string host = url2.Host;

            while (true)
            {
                try
                {
                    if (SelectedCredentials != null && SelectedCredentials.Username?.Any() == true && SelectedCredentials.Password?.Any() == true)
                    {
                        TokenClient   client   = new TokenClient(TokenEndpoint, "resourceownerclient", SelectedCredentials.ClientSecret, null, AuthenticationStyle.BasicAuthentication);
                        TokenResponse response = client.RequestResourceOwnerPasswordAsync(SelectedCredentials.Username, SelectedCredentials.Password, SelectedCredentials.ClientScope).Result;
                        if (response.IsError)
                        {
                            if (response.ErrorDescription?.Contains("InvalidLogin") == true)
                            {
                                using (new CenterWinDialog(this))
                                {
                                    if (MessageBox.Show(this, "Username or password are not correct!", "Error", MessageBoxButtons.RetryCancel) == DialogResult.Cancel)
                                    {
                                        return;
                                    }
                                }
                            }
                            else if (response.Exception != null)
                            {
                                throw response.Exception;
                            }
                            else
                            {
                                throw new InvalidOperationException(response.Error + ": " + response.ErrorDescription);
                            }
                        }
                        else
                        {
                            _accessToken = response.AccessToken;
                            _httpClient.SetBearerToken(_accessToken);
                            _httpClient.DefaultRequestHeaders.Remove("Accept");
                            _httpClient.DefaultRequestHeaders.Add("Accept", "application/json;odata.metadata=minimal");
                            break;
                        }
                    }

                    var loginForm = new LoginForm()
                    {
                        StartPosition = FormStartPosition.CenterParent
                    };
                    if (SelectedCredentials != null && SelectedCredentials.Username?.Any() == true && SelectedCredentials.Password?.Any() == true)
                    {
                        loginForm.usernameTextBox.Text       = SelectedCredentials.Username;
                        loginForm.passwordTextBox.Text       = SelectedCredentials.Password;
                        loginForm.identityServerTextBox.Text = SelectedCredentials.IdentityServer.Replace(host, "<HostURL>");
                        loginForm.clientScopeTextBox.Text    = SelectedCredentials.ClientScope;
                        loginForm.clientSecretTextBox.Text   = SelectedCredentials.ClientSecret;
                    }
                    if (loginForm.ShowDialog(this) == DialogResult.Cancel)
                    {
                        return;
                    }

                    SelectedCredentials = new Credentials
                    {
                        Username       = loginForm.usernameTextBox.Text,
                        Password       = loginForm.passwordTextBox.Text,
                        IdentityServer = loginForm.identityServerTextBox.Text.Replace("<HostURL>", host),
                        ClientScope    = loginForm.clientScopeTextBox.Text,
                        ClientSecret   = loginForm.clientSecretTextBox.Text
                    };
                    if (!SelectedCredentials.IdentityServer.StartsWith("http"))
                    {
                        SelectedCredentials.IdentityServer = (url.StartsWith("http://") ? "http://" : "https://") + SelectedCredentials.IdentityServer;
                    }
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null)
                    {
                        ex = ex.InnerException; // bypass AggregateException
                    }
                    if (MessageBox.Show(this, "Failed to connect to identity server (" + SelectedCredentials.IdentityServer + "):\r\n" + ex.Message, "Error", MessageBoxButtons.RetryCancel) == DialogResult.Cancel)
                    {
                        return;
                    }
                    SelectedCredentials = null;
                }
            }

            serverLocationTextBox.Text = url;

            FileTree.Nodes.Clear();
            FileTree.Nodes.Add("host", host, 0);
            GetFolders();
            serverLocationTextBox.Text     = url;
            serverLocationTextBox.ReadOnly = true;
            connectButton.Text             = "Disconnect";
        }
コード例 #9
0
        private static async Task MainAsync()
        {
            // discover endpoints from metadata
            //var disco = await DiscoveryClient.GetAsync("http://*****:*****@163.com", "123456").Result;

            //var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");
            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }
            Console.WriteLine(tokenResponse.Json);
            Console.WriteLine("\n\n");
            // call api
            var client = new HttpClient();

            client.SetBearerToken(tokenResponse.AccessToken);
            //api地址
            //var response = await client.GetAsync("http://localhost:1624/identity");
            var response = await client.GetAsync("http://DOcelot.APIGateway.com/api/productservice/values");

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

                Console.WriteLine(JArray.Parse(content));
            }

            Console.WriteLine("\n\n");
            var response2 = await client.GetAsync("http://DOcelot.APIGateway.com/api/orderservice/values");

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

                Console.WriteLine(JArray.Parse(content2));
            }

            Console.ReadLine();
        }
コード例 #10
0
ファイル: Startup.cs プロジェクト: duncancave/IdentityServer3
        public void Configuration(IAppBuilder app)
        {
            // The UniqueClaimTypeIdentifier setting requires that all claims-based identities must return a unique value for that claim type.
            // This adjusts the anti-CSRF protection to use the sub claim and is necessary as a result of setting our inbound claim type map like we have.
            AntiForgeryConfig.UniqueClaimTypeIdentifier = "sub";

            // By setting this to a new dictionary of string and string we are essentially clearing the mapper, allowing the JWT middleware to use the claim types
            // that are sent by Identity Server, instead of it mapping them to the Microsoft XML schema types(for example we'll get name instead of
            // http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name).
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

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

            // The Katana middleware is in charge of detecting when the user needs to be redirected to the OpenID Connect Provider and handling the subsequent interactions.
            // This middleware will then log us in to our application as a result.
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId  = "hybridclient",
                Authority = IdServBaseUri,
                //RedirectUri = ClientUri,
                //PostLogoutRedirectUri = ClientUri,
                ResponseType = "code id_token token",
                Scope        = "openid profile email roles offline_access",
                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role"
                },
                SignInAsAuthenticationType = "Cookies",
                Notifications =
                    new OpenIdConnectAuthenticationNotifications
                {
                    // Use the Authorisation Code Flow - it's more secure than Implicit flow and allows us to request refresh tokens
                    AuthorizationCodeReceived = async n =>
                    {
                        // Check the uri and get the tenant
                        var uri    = $"{n.Request.Scheme}://{n.Request.Host}/";
                        var tenant = string.Empty;

                        if (this.ValidateUri(uri))
                        {
                            tenant = this.Between(uri, "//", ".");
                        }
                        else
                        {
                            // TODO: Some kind of error here?
                        }

                        // Here we are using the UserInfoClient helper from the IdentityModel library to retrieve the user's claims and then
                        // creating a new ClaimsIdentity, keeping the AuthenticationType the same. We are then populating this identity with
                        // any claims we want both from the existing ClaimsIdentity and then any claims we received from the userinfo endpoint.
                        // We can then store these claims in our authentication cookie.
                        var userInfoClient   = new UserInfoClient(new Uri(UserInfoEndpoint), n.ProtocolMessage.AccessToken);
                        var userInfoResponse = await userInfoClient.GetAsync();

                        var identity = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType);
                        identity.AddClaims(userInfoResponse.GetClaimsIdentity().Claims);

                        // To add support for long lived logins, we'll need get a refresh token from our authorization server.
                        // This refresh token can then be used to obtain fresh access tokens when the current one becomes invalid or expires.
                        // Here we are using another helper class from the IdentityModel library, this time TokenClient.
                        // This is used for simple handling of OAuth requests and is internally a wrapper around HttpClient.
                        // By trading in our Authorization Code like this we receive a new access token and a refresh token along with it.
                        var tokenClient = new TokenClient(TokenEndpoint, "hybridclient", "idsrv3test");
                        var response    = await tokenClient.RequestAuthorizationCodeAsync(n.Code, uri);

                        identity.AddClaim(new Claim("access_token", response.AccessToken));
                        identity.AddClaim(
                            new Claim("expires_at", DateTime.UtcNow.AddSeconds(response.ExpiresIn).ToLocalTime().ToString(CultureInfo.InvariantCulture)));

                        // We can only get the refresh token because we request the offline access scope in the client
                        identity.AddClaim(new Claim("refresh_token", response.RefreshToken));

                        // To use the post logout redirect(also logs us out of Identity Server) we should also supply the previously issued ID token in order to give the
                        // OpenID Connect Provider some sort of idea about the current authenticated session.
                        identity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

                        // This ticket is used to set up our claims principal
                        n.AuthenticationTicket = new AuthenticationTicket(
                            identity,
                            n.AuthenticationTicket.Properties);
                    },
                    RedirectToIdentityProvider = n =>
                    {
                        var uri = $"{n.Request.Scheme}://{n.Request.Host}/";

                        if (this.ValidateUri(uri))
                        {
                            n.ProtocolMessage.RedirectUri           = uri;
                            n.ProtocolMessage.PostLogoutRedirectUri = uri;
                        }
                        else
                        {
                            // TODO: Some kind of error here?
                        }

                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.AuthenticationRequest)
                        {
                            var tenant = this.Between(uri, "//", ".");
                            n.ProtocolMessage.AcrValues = $"tenant:{tenant}";
                        }

                        // This allows us to redirect back to our site on logout of IdentityServer (but not automatically)
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token").Value;
                            n.ProtocolMessage.IdTokenHint = idTokenHint;
                        }

                        return(Task.FromResult(0));
                    }
                }
            });
        }
コード例 #11
0
        //[HttpGet]
        public async Task <string> LoginAsync(AppUser testUser)
        {
            string finalToken = "";

            //AppUser testUser = new AppUser();

            var validUser = new AppUser();

            ////user requsted from ui
            //testUser.UserName = "******";
            //testUser.Password = "******";

            //user saved in database
            validUser.UserName = "******";
            validUser.Password = "******";

            if (testUser.UserName == validUser.UserName && testUser.Password == validUser.Password)
            {
                //// discover endpoints from the metadata by calling Auth server hosted on 5000 port
                var discover = await DiscoveryClient.GetAsync("http://localhost:5000");

                if (discover.IsError)
                {
                    Console.WriteLine(discover.Error);
                }

                // request token
                var tokenClient   = new TokenClient(discover.TokenEndpoint, "client", "secret");
                var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");

                if (tokenResponse.IsError)
                {
                    Console.WriteLine(tokenResponse.Error);
                }

                Console.WriteLine(tokenResponse.Json);

                finalToken = tokenResponse.Json.ToString();

                Console.WriteLine("\n\n");

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

                var response = await client.GetAsync("http://localhost:5001/api/identity/GetFromApi2");

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

                    Console.WriteLine(JArray.Parse(content));

                    finalToken += JArray.Parse(content).ToString();

                    /*return Ok(JArray.Parse(content));*/
                }
            }

            return(finalToken);
        }
コード例 #12
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

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

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId              = "mvc.owin.hybrid",
                Authority             = Constants.BaseAddress,
                RedirectUri           = "https://localhost:44300/",
                PostLogoutRedirectUri = "https://localhost:44300/",
                ResponseType          = "code id_token",
                Scope = "openid profile read write offline_access",

                SignInAsAuthenticationType = "Cookies",

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async n =>
                    {
                        // use the code to get the access and refresh token
                        var tokenClient = new TokenClient(
                            Constants.TokenEndpoint,
                            "mvc.owin.hybrid",
                            "secret");

                        var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(
                            n.Code, n.RedirectUri);

                        // use the access token to retrieve claims from userinfo
                        var userInfoClient = new UserInfoClient(
                            new Uri(Constants.UserInfoEndpoint),
                            tokenResponse.AccessToken);

                        var userInfoResponse = await userInfoClient.GetAsync();

                        // create new identity
                        var id = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType);
                        id.AddClaims(userInfoResponse.GetClaimsIdentity().Claims);

                        id.AddClaim(new Claim("access_token", tokenResponse.AccessToken));
                        id.AddClaim(new Claim("expires_at", DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToLocalTime().ToString()));
                        id.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken));
                        id.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                        id.AddClaim(new Claim("sid", n.AuthenticationTicket.Identity.FindFirst("sid").Value));

                        n.AuthenticationTicket = new AuthenticationTicket(
                            new ClaimsIdentity(id.Claims, n.AuthenticationTicket.Identity.AuthenticationType),
                            n.AuthenticationTicket.Properties);
                    },

                    RedirectToIdentityProvider = n =>
                    {
                        // if signing out, add the id_token_hint
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (idTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                            }
                        }

                        return(Task.FromResult(0));
                    }
                }
            });
        }
コード例 #13
0
        private async Task <string> RenewTokens()
        {
            // get the current HttpContext to access the tokens
            var currentContext = _httpContextAccessor.HttpContext;

            // get the metadata
            var discoveryClient  = new DiscoveryClient(configuration.AuthorityEndpoint);
            var metaDataResponse = await discoveryClient.GetAsync();

            // create a new token client to get new tokens
            var tokenClient = new TokenClient(metaDataResponse.TokenEndpoint,
                                              "blogclient", "secret");

            // get the saved refresh token
            var currentRefreshToken = await currentContext
                                      .GetTokenAsync(OpenIdConnectParameterNames.RefreshToken);

            // refresh the tokens
            var tokenResult = await tokenClient.RequestRefreshTokenAsync(currentRefreshToken);

            if (!tokenResult.IsError)
            {
                // update the tokens & exipration value
                var updatedTokens = new List <AuthenticationToken>();
                updatedTokens.Add(new AuthenticationToken
                {
                    Name  = OpenIdConnectParameterNames.IdToken,
                    Value = tokenResult.IdentityToken
                });
                updatedTokens.Add(new AuthenticationToken
                {
                    Name  = OpenIdConnectParameterNames.AccessToken,
                    Value = tokenResult.AccessToken
                });
                updatedTokens.Add(new AuthenticationToken
                {
                    Name  = OpenIdConnectParameterNames.RefreshToken,
                    Value = tokenResult.RefreshToken
                });

                var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn);
                updatedTokens.Add(new AuthenticationToken
                {
                    Name  = "expires_at",
                    Value = expiresAt.ToString("o", CultureInfo.InvariantCulture)
                });

                // get authenticate result, containing the current principal &
                // properties
                var currentAuthenticateResult = await currentContext.AuthenticateAsync("Cookies");

                // store the updated tokens
                currentAuthenticateResult.Properties.StoreTokens(updatedTokens);

                // sign in
                await currentContext.SignInAsync("Cookies",
                                                 currentAuthenticateResult.Principal,
                                                 currentAuthenticateResult.Properties);

                // return the new access token
                return(tokenResult.AccessToken);
            }
            else
            {
                throw new Exception("Problem encountered while refreshing tokens.",
                                    tokenResult.Exception);
            }
        }
コード例 #14
0
        public void SuccessfulResourceOwnerClaimsUpdate()
        {
            TokenClient          client         = null !;
            GrantedTokenResponse tokenResponse  = null !;
            HttpResponseMessage  updateResponse = null !;

            "and a properly configured token client".x(
                () => client = new TokenClient(
                    TokenCredentials.FromBasicAuthentication("client", "client"),
                    _fixture.Client,
                    new Uri(WellKnownOpenidConfiguration)));

            "when requesting token".x(
                async() =>
            {
                var response = await client
                               .GetToken(TokenRequest.FromPassword("user", "password", new[] { "openid", "offline" }))
                               .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;
                tokenResponse = response.Item;
            });

            "and valid access token is received".x(
                () =>
            {
                var tokenHandler         = new JwtSecurityTokenHandler();
                var validationParameters = new TokenValidationParameters
                {
                    IssuerSigningKeys = _jwks.GetSigningKeys(),
                    ValidAudience     = "client",
                    ValidIssuer       = "https://localhost"
                };
                tokenHandler.ValidateToken(tokenResponse.AccessToken, validationParameters, out var token);

                Assert.NotEmpty(((JwtSecurityToken)token).Claims);
            });

            "and updating own claims".x(
                async() =>
            {
                var updateRequest = new UpdateResourceOwnerClaimsRequest
                {
                    Subject = "user", Claims = new[] { new ClaimData {
                                                           Type = "test", Value = "something"
                                                       } }
                };

                var json = JsonConvert.SerializeObject(updateRequest);

                var request = new HttpRequestMessage
                {
                    Content    = new StringContent(json, Encoding.UTF8, "application/json"),
                    Method     = HttpMethod.Post,
                    RequestUri = new Uri(_fixture.Server.BaseAddress + "resource_owners/claims")
                };
                request.Headers.Authorization = new AuthenticationHeaderValue(
                    JwtBearerDefaults.AuthenticationScheme,
                    tokenResponse.AccessToken);
                updateResponse = await _fixture.Client().SendAsync(request).ConfigureAwait(false);
            });

            "then update is successful".x(() => { Assert.Equal(HttpStatusCode.OK, updateResponse.StatusCode); });
        }
コード例 #15
0
        private void InitializeGameServices()
        {
            lock (GameServicesLock)
            {
                if (mServices != null)
                {
                    return;
                }

                using (var builder = GameServicesBuilder.Create())
                {
                    using (var config = clientImpl.CreatePlatformConfiguration())
                    {
                        // We need to make sure that the invitation delegate is registered before the
                        // services object is initialized - otherwise we might miss a callback if
                        // the game was opened because of a user accepting an invitation through
                        // a system notification.
                        RegisterInvitationDelegate(mConfiguration.InvitationDelegate);
                        builder.SetOnAuthFinishedCallback(HandleAuthTransition);
                        builder.SetOnTurnBasedMatchEventCallback((eventType, matchId, match) => mTurnBasedClient.HandleMatchEvent(eventType, matchId, match));
                        builder.SetOnMultiplayerInvitationEventCallback(HandleInvitation);
                        if (mConfiguration.EnableSavedGames)
                        {
                            builder.EnableSnapshots();
                        }
                        if (mConfiguration.RequireGooglePlus)
                        {
                            builder.RequireGooglePlus();
                        }
                        Debug.Log("Building GPG services, implicitly attempts silent auth");
                        mAuthState       = AuthState.SilentPending;
                        mServices        = builder.Build(config);
                        mEventsClient    = new NativeEventClient(new EventManager(mServices));
                        mQuestsClient    = new NativeQuestClient(new QuestManager(mServices));
                        mTurnBasedClient =
                            new NativeTurnBasedMultiplayerClient(this, new TurnBasedManager(mServices));

                        mTurnBasedClient.RegisterMatchDelegate(mConfiguration.MatchDelegate);

                        mRealTimeClient =
                            new NativeRealtimeMultiplayerClient(this, new RealtimeManager(mServices));

                        if (mConfiguration.EnableSavedGames)
                        {
                            mSavedGameClient =
                                new NativeSavedGameClient(new SnapshotManager(mServices));
                        }
                        else
                        {
                            mSavedGameClient = new UnsupportedSavedGamesClient(
                                "You must enable saved games before it can be used. " +
                                "See PlayGamesClientConfiguration.Builder.EnableSavedGames.");
                        }

                        mAuthState   = AuthState.SilentPending;
                        mTokenClient = clientImpl.CreateTokenClient(
                            (mUser == null) ? null : mUser.id, false);
                    }
                }
            }
        }
コード例 #16
0
        public void ExecuteDeviceAuthorizationFlowWithUserApproval()
        {
            const string clientId    = "device";
            ITokenClient tokenClient = null !;
            DeviceAuthorizationResponse           response    = null !;
            GrantedTokenResponse                  token       = null !;
            Task <Option <GrantedTokenResponse> > pollingTask = null !;

            "Given a token client".x(
                () =>
            {
                tokenClient = new TokenClient(
                    TokenCredentials.AsDevice(),
                    _fixture.Client,
                    new Uri(WellKnownOpenidConfiguration));

                Assert.NotNull(tokenClient);
            });

            "and an access token".x(
                async() =>
            {
                var authClient = new TokenClient(
                    TokenCredentials.FromClientCredentials(clientId, "client"),
                    _fixture.Client,
                    new Uri(WellKnownOpenidConfiguration));
                var tokenResponse = await authClient.GetToken(
                    TokenRequest.FromPassword("user", "password", new[] { "openid" }))
                                    .ConfigureAwait(false);

                Assert.IsType <Option <GrantedTokenResponse> .Result>(tokenResponse);

                token = (tokenResponse as Option <GrantedTokenResponse> .Result).Item;
            });

            "When a device requests authorization".x(
                async() =>
            {
                var genericResponse = await tokenClient.GetAuthorization(new DeviceAuthorizationRequest(clientId))
                                      .ConfigureAwait(false);

                Assert.IsType <Option <DeviceAuthorizationResponse> .Result>(genericResponse);

                response = (genericResponse as Option <DeviceAuthorizationResponse> .Result).Item;
            });

            "and the device polls the token server".x(
                async() =>
            {
                pollingTask = tokenClient.GetToken(
                    TokenRequest.FromDeviceCode(clientId, response.DeviceCode, response.Interval));

                Assert.False(pollingTask.IsCompleted);
            });

            "and user successfully posts user code".x(
                async() =>
            {
                var client = _fixture.Client();
                var msg    = new HttpRequestMessage
                {
                    Method     = HttpMethod.Post,
                    RequestUri = new Uri(response.VerificationUri),
                    Content    = new FormUrlEncodedContent(
                        new[] { new KeyValuePair <string, string>("code", response.UserCode) })
                };
                msg.Headers.Authorization = new AuthenticationHeaderValue(token.TokenType, token.AccessToken);

                var approval = await client.SendAsync(msg).ConfigureAwait(false);

                Assert.Equal(HttpStatusCode.OK, approval.StatusCode);
            });

            "then token is returned from polling".x(
                async() =>
            {
                var tokenResponse = await pollingTask.ConfigureAwait(false);

                Assert.IsType <Option <GrantedTokenResponse> .Result>(tokenResponse);
            });
        }
コード例 #17
0
        private async static Task <LoginResult> ValidateResponseAsync(AuthorizeResponse response, OidcSettings settings, OpenIdConnectConfiguration config, string expectedNonce, string verifier)
        {
            var tokenClaims = ValidateIdentityToken(response.IdentityToken, settings, config);

            if (tokenClaims == null)
            {
                return(new LoginResult {
                    ErrorMessage = "Invalid identity token."
                });
            }

            var nonce = tokenClaims.FirstOrDefault(c => c.Type == JwtClaimTypes.Nonce);

            if (nonce == null || !string.Equals(nonce.Value, expectedNonce, StringComparison.Ordinal))
            {
                return(new LoginResult {
                    ErrorMessage = "Inalid nonce."
                });
            }

            var codeHash = tokenClaims.FirstOrDefault(c => c.Type == JwtClaimTypes.AuthorizationCodeHash);

            if (codeHash == null || ValidateCodeHash(codeHash.Value, response.Code) == false)
            {
                return(new LoginResult {
                    ErrorMessage = "Invalid code."
                });
            }

            var provider = JwkNetExtensions.CreateProvider();
            var jwk      = provider.ToJsonWebKey();

            var tokenClient = new TokenClient(
                config.TokenEndpoint,
                settings.ClientId,
                settings.ClientSecret);

            var tokenResponse = await tokenClient.RequestAuthorizationCodePopAsync(
                code : response.Code,
                redirectUri : settings.RedirectUri,
                codeVerifier : settings.UsePkce?verifier : null,
                algorithm : jwk.Alg,
                key : jwk.ToJwkString());

            if (tokenResponse.IsError)
            {
                return(new LoginResult {
                    ErrorMessage = tokenResponse.Error
                });
            }

            var profileClaims = new List <Claim>();

            if (settings.LoadUserProfile)
            {
                var userInfoClient = new UserInfoClient(
                    new Uri(config.UserInfoEndpoint),
                    tokenResponse.AccessToken);

                var userInfoResponse = await userInfoClient.GetAsync();

                profileClaims = userInfoResponse.GetClaimsIdentity().Claims.ToList();
            }

            var principal = CreatePrincipal(tokenClaims, profileClaims, settings);

            return(new LoginResult
            {
                Success = true,
                User = principal,
                IdentityToken = response.IdentityToken,
                AccessToken = tokenResponse.AccessToken,
                RefreshToken = tokenResponse.RefreshToken,
                AccessTokenExpiration = DateTime.Now.AddSeconds(tokenResponse.ExpiresIn)
            });
        }
コード例 #18
0
        private async Task <TokenResponse> GetToken(User user, string clientid)
        {
            var client = new TokenClient(Constants.TokenEndpoint, clientid, SecretApi);

            return(client.RequestResourceOwnerPasswordAsync(user.UserName, user.Password, "WebAPI").Result);
        }
 /// <summary>
 /// Retrieves a token request.
 /// </summary>
 /// <param name="tokenClient">tokenIO instance to use</param>
 /// <param name="requestId">id of request to retrieve</param>
 /// <returns>token request that was stored with the request id</returns>
 public static TokenRequest RetrieveTokenRequest(TokenClient tokenClient, string requestId)
 {
     return(tokenClient.RetrieveTokenRequestBlocking(requestId));
 }
コード例 #20
0
        public void UnsuccessfulTicketAuthentication()
        {
            Option <GrantedTokenResponse> ticketResponse      = null !;
            AddResourceSetResponse        resourceSetResponse = null !;
            UmaClient            umaClient = null !;
            TokenClient          client    = null !;
            GrantedTokenResponse result    = null !;
            string ticketId = null !;

            "and a properly configured token client".x(
                () => client = new TokenClient(
                    TokenCredentials.FromClientCredentials("post_client", "post_client"),
                    _fixture.Client,
                    new Uri(WellKnownOpenidConfiguration)));

            "when requesting token".x(
                async() =>
            {
                var response = await client
                               .GetToken(TokenRequest.FromPassword("user", "password", new[] { "uma_protection" }))
                               .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;
                result = response.Item;
            });

            "then has valid access token".x(
                () =>
            {
                var tokenHandler         = new JwtSecurityTokenHandler();
                var validationParameters = new TokenValidationParameters
                {
                    IssuerSigningKeys = _jwks.GetSigningKeys(),
                    ValidAudience     = "post_client",
                    ValidIssuer       = "https://localhost"
                };
                tokenHandler.ValidateToken(result.AccessToken, validationParameters, out var token);

                Assert.NotEmpty(((JwtSecurityToken)token).Claims);
            });

            "given a uma client".x(
                () =>
            {
                umaClient = new UmaClient(
                    _fixture.Client,
                    new Uri("https://localhost/.well-known/uma2-configuration"));
            });

            "when creating resource set with deviating scopes".x(
                async() =>
            {
                var resourceSet = new ResourceSet
                {
                    Name   = "Local",
                    Scopes = new[] { "api1" },
                    Type   = "url",
                    AuthorizationPolicies = new[]
                    {
                        new PolicyRule
                        {
                            Scopes = new[] { "anotherApi" },
                            Claims = new[] { new ClaimData {
                                                 Type = "sub", Value = "user"
                                             } },
                            ClientIdsAllowed             = new[] { "post_client" },
                            IsResourceOwnerConsentNeeded = false
                        }
                    }
                };

                var resourceResponse =
                    await umaClient.AddResource(resourceSet, result.AccessToken).ConfigureAwait(false) as
                    Option <AddResourceSetResponse> .Result;

                Assert.NotNull(resourceResponse);

                resourceSetResponse = resourceResponse.Item;
            });

            "and requesting permission ticket".x(
                async() =>
            {
                var permission =
                    new PermissionRequest {
                    ResourceSetId = resourceSetResponse.Id, Scopes = new[] { "api1" }
                };
                var permissionResponse = await umaClient.RequestPermission(result.AccessToken, requests: permission)
                                         .ConfigureAwait(false) as Option <TicketResponse> .Result;

                Assert.NotNull(permissionResponse);

                ticketId = permissionResponse.Item.TicketId;
            });

            "and requesting token from ticket".x(
                async() =>
            {
                ticketResponse = await client.GetToken(TokenRequest.FromTicketId(ticketId, result.IdToken))
                                 .ConfigureAwait(false);
            });

            "then has error".x(() => { Assert.IsType <Option <GrantedTokenResponse> .Error>(ticketResponse); });
        }
コード例 #21
0
        public void Configuration(IAppBuilder app)
        {
            // Show PII information in log entries (in real app this setting should come from your app configuration source)
            // when you set this to true, you will see more details about an exception, like if the signature validation fails
            // you will see the information what key identifier was used to validate the signature of a token (otherwise you see message about PII info removed)
            // PII means: personally identifiable information
            Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;

            // clear the default mappings so that framework doesn't try to automatically map claims for us using its defaults
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            // Antiforgery requires this mapping/information or otherwise we will get the following error for example when trying to access visitor groups
            // A claim of type 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' or 'http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider' was not present on the provided ClaimsIdentity.
            // We could add those claim(s) to the user or directly configure the AntiForgeryConfig.UniqueClaimTypeIdentifier
            // here we set that antiforgery should use the 'CustomClaimNames.EpiUsername' claim value which is unique for each user in this demo
            AntiForgeryConfig.UniqueClaimTypeIdentifier = CustomClaimNames.EpiUsername; // this could be also JwtClaimTypes.Subject but then you need to remember to add that claim to the claimsidentity

            // this is not required but if you have issues with cookies then add Nuget package: Kentor.OwinCookieSaver
            // to see if that sorts out your cookie issue
            // NuGet : https://www.nuget.org/packages/Kentor.OwinCookieSaver/
            // GitHub : https://github.com/Sustainsys/owin-cookie-saver
            //app.UseKentorOwinCookieSaver();

            // set the default authentication type to 'Cookies'
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            // set the cookie auth options
            // the cookies is valid for 'configuration value here' minutes and uses sliding expiration, meaning framework will extend the validty automatically
            // see: https://docs.microsoft.com/en-us/dotnet/api/system.web.security.formsauthentication.slidingexpiration?view=netframework-4.7.2
            // the OpenIdConnectAuthenticationOptions.UseTokenLifetime has to be false for this to work, if the value is true then the token lifetime will be used which is usually very short time
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                ExpireTimeSpan    = TimeSpan.FromMinutes(OIDCInMemoryConfiguration.AuthCookieValidMinutes),
                SlidingExpiration = true
            });

            // Configure the OIDC auth options
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId              = OIDCInMemoryConfiguration.ClientId,
                ClientSecret          = OIDCInMemoryConfiguration.ClientSecret,
                Authority             = OIDCInMemoryConfiguration.Authority,             // this should be set so that the middleware will use OIDC discovery to automatically setup endpoint configurations
                RedirectUri           = OIDCInMemoryConfiguration.WebAppOidcEndpoint,    // allowed URL to return tokens or authorization codes to, must match what has been defined for client in identity provider
                PostLogoutRedirectUri = OIDCInMemoryConfiguration.PostLogoutRedirectUrl, // allowed URL where client is allowed to be redirected after IdP logout
                Scope                     = $"openid profile email",                     // TODO: add "offline_access" scope if you need refreshtoken {CustomScopeNames.ProfileWithPermissions} {CustomScopeNames.MembershipStatus}
                ResponseType              = "code id_token",                             // hybrid flow
                RequireHttpsMetadata      = OIDCInMemoryConfiguration.RequireHttpsMetadata,
                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType       = JwtClaimTypes.Name,          // change name claim name to match our demo IdP returned claim name
                    RoleClaimType       = CustomClaimNames.Permission, // change role claim name to match our demo IdP returned claim name
                    ValidateTokenReplay = true
                },
                SignInAsAuthenticationType = CookieAuthenticationDefaults.AuthenticationType, // somewhere stated that needs to be after TokenValidationParameters
                UseTokenLifetime           = false,                                           // if this is true then the token life time is used (for example IdentityServer token lifetime is 5 minutes by default) for cookie auth lifetime
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    RedirectToIdentityProvider = notification =>
                    {
                        // if single site setup, the redirect url is automatically set to the page you were trying to access
                        // For example in multi-tenant setup you want to change the return url here based on the current site address
                        // See Episerver sample: https://world.episerver.com/documentation/developer-guides/CMS/security/integrate-azure-ad-using-openid-connect/
                        // and the method: HandleMultiSitereturnUrl
                        //context.ProtocolMessage.RedirectUri = "http://host-of-your-site2/the-return-page/path/here/";

                        // what kind of message are we processing
                        switch (notification.ProtocolMessage.RequestType)
                        {
                        case OpenIdConnectRequestType.Authentication:

                            if (notification.OwinContext.Response.StatusCode == 401)
                            {
                                // if the request is ajax request, like Episerver Dojo framework, don't try to redirect
                                // but return 401 so the UI will properly display the login dialog
                                if (IsAjaxRequest(notification.Request))
                                {
                                    if (Logger.IsInformationEnabled())
                                    {
                                        Logger.Information($"Request is made with AJAX and response is 401.");
                                    }

                                    notification.HandleResponse();
                                    return(Task.FromResult(0));
                                }

                                // To avoid a redirect loop to the IdP server send 403 when user is authenticated but does not have access
                                if (notification.OwinContext.Authentication.User.Identity.IsAuthenticated)
                                {
                                    if (Logger.IsInformationEnabled())
                                    {
                                        Logger.Information($"Request response code would be 401 but user '{notification.OwinContext.Authentication.User.Identity.Name}' is authenticated, switching response code to 403 (forbidden).");
                                    }

                                    notification.OwinContext.Response.StatusCode = 403;
                                    notification.HandleResponse();
                                    return(Task.FromResult(0));
                                }
                            }

                            break;

                        case OpenIdConnectRequestType.Logout:
                            // If signing out, add the id_token_hint if present
                            // see: http://openid.net/specs/openid-connect-session-1_0.html#rfc.section.5

                            if (notification.OwinContext.Authentication.User.Identity.IsAuthenticated)
                            {
                                Logger.Information($"User is logging out. User: {notification.OwinContext.Authentication.User.Identity.Name}.");
                            }

                            var idTokenHint = notification.OwinContext.Authentication.User.FindFirst(OpenIdConnectParameterNames.IdToken);

                            if (idTokenHint != null)
                            {
                                if (Logger.IsDebugEnabled())
                                {
                                    Logger.Debug($"Redirecting to Identity provider for logout with IdTokenHint.");
                                }

                                notification.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                            }
                            else
                            {
                                if (Logger.IsDebugEnabled())
                                {
                                    Logger.Debug($"Redirecting to Identity provider for logout without IdTokenHint.");
                                }
                            }

                            return(Task.FromResult(0));

                        case OpenIdConnectRequestType.Token:
                            // nothing here :D
                            break;

                        default:
                            break;
                        }

                        return(Task.FromResult(0));
                    },
                    AuthorizationCodeReceived = async notification =>
                    {
                        System.Diagnostics.Debug.WriteLine($"Authorization code received for sub: {notification.JwtSecurityToken.Subject}. Received claims: {GetClaimsAsString(notification.JwtSecurityToken.Claims)}.");

                        // show info about the claims if debug logging is enabled
                        if (Logger.IsDebugEnabled())
                        {
                            Logger.Debug($"Authorization code received for sub: {notification.JwtSecurityToken.Subject}. Received claims: {GetClaimsAsString(notification.JwtSecurityToken.Claims)}.");
                        }
                        else
                        {
                            Logger.Information($"Authorization code received for sub: {notification.JwtSecurityToken.Subject}.");
                        }

                        // config has been automatically setup using OIDC discovery because we have set the Authority value previously in when configuring OpenIdConnectAuthenticationOptions
                        OpenIdConnectConfiguration configuration = null;

                        try
                        {
                            // get OpenIdConnectConfiguration
                            configuration = await notification.Options.ConfigurationManager.GetConfigurationAsync(notification.Request.CallCancelled);
                        }
                        catch (Exception ex)
                        {
                            Logger.Error($"Failed to get OpenIdConnectConfiguration. Cannot authorize the client with sub: {notification.JwtSecurityToken.Subject}.", ex);
                            throw;
                        }

                        // configure token client, endpoint is automatically configured using the Auto discovery: /.well-known/openid-configuration
                        var tokenClient = new TokenClient(configuration.TokenEndpoint, notification.Options.ClientId, notification.Options.ClientSecret, style: AuthenticationStyle.PostValues);

                        // exchange the authorization 'code' to access token
                        var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(notification.ProtocolMessage.Code, notification.RedirectUri, cancellationToken: notification.Request.CallCancelled);

                        // check if there was an error fetching the acces token
                        if (tokenResponse.IsError)
                        {
                            Logger.Error($"There was an error retrieving the access token for sub: {notification.JwtSecurityToken.Subject}. Error: {tokenResponse.Error}. Error description: {tokenResponse.ErrorDescription}.");

                            notification.HandleResponse();

                            // TODO : redirect to friendly error page
                            // does 302 redirect, but SEO is not your concern here
                            // notification.Response.Redirect("/your/nice/error/page/address/here/");

                            notification.Response.Write($"Error retrieving access token. {tokenResponse.ErrorDescription}.");
                            return;
                        }

                        if (string.IsNullOrWhiteSpace(tokenResponse.AccessToken))
                        {
                            Logger.Error($"Didn't receive access token for sub: {notification.JwtSecurityToken.Subject}.");

                            notification.HandleResponse();

                            // TODO : redirect to friendly error page
                            // does 302 redirect, but SEO is not your concern here
                            // notification.Response.Redirect("/your/nice/error/page/address/here/");

                            notification.Response.Write($"Error, access token not received. {tokenResponse.ErrorDescription}.");
                            return;
                        }

                        // sub and iss claims musta have same value when using hybrid flow (in the id token and tokenresponse)
                        // http://openid.net/specs/openid-connect-core-1_0.html#HybridIDToken2 3.3.3.6 ID Token
                        // If an ID Token is returned from both the Authorization Endpoint and from the Token Endpoint,
                        // which is the case for the response_type values "code id_token" and "code id_token token", the iss and sub Claim Values MUST be identical in both ID Tokens.

                        if (!string.IsNullOrWhiteSpace(tokenResponse.IdentityToken))
                        {
                            try
                            {
                                JwtSecurityTokenHandler idTokenHandler = new JwtSecurityTokenHandler();
                                var parsedIdToken = idTokenHandler.ReadJwtToken(tokenResponse.IdentityToken);

                                if (string.Compare(parsedIdToken.Issuer, notification.JwtSecurityToken.Issuer, StringComparison.OrdinalIgnoreCase) != 0 ||
                                    string.Compare(parsedIdToken.Subject, notification.JwtSecurityToken.Subject, StringComparison.OrdinalIgnoreCase) != 0)
                                {
                                    Logger.Error($"Authorization endpoint id token 'sub' ({notification.JwtSecurityToken.Subject}) and 'iss' ({notification.JwtSecurityToken.Issuer}) claim values don't match with token endpoint 'sub' ({parsedIdToken.Subject}) and 'iss' ({parsedIdToken.Issuer}) claim values.");

                                    notification.HandleResponse();

                                    // TODO : redirect to friendly error page
                                    // does 302 redirect, but SEO is not your concern here
                                    // notification.Response.Redirect("/your/nice/error/page/address/here/");

                                    notification.Response.Write("Token endpoint identity token doesn't match autohorization endpoint returned identity token.");
                                    return;
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.Error($"Failed to validate token endpoint identity token against autohorization endpoint returned identity token.", ex);

                                notification.HandleResponse();

                                // TODO : redirect to friendly error page
                                // does 302 redirect, but SEO is not your concern here
                                // notification.Response.Redirect("/your/nice/error/page/address/here/");

                                notification.Response.Write("Failed to validate token endpoint identity token against autohorization endpoint returned identity token.");
                                return;
                            }
                        }
                        else
                        {
                            Logger.Information($"Token endpoint didn't return identity token for sub: {notification.JwtSecurityToken.Subject}.");
                        }

                        // get userinfo using the access token
                        var userInfoClient   = new UserInfoClient(configuration.UserInfoEndpoint);
                        var userInfoResponse = await userInfoClient.GetAsync(tokenResponse.AccessToken);

                        // check if there was an error fetching the user information
                        if (userInfoResponse.IsError)
                        {
                            Logger.Error($"There was an error retrieving the user information for sub: {notification.JwtSecurityToken.Subject}. Error: {userInfoResponse.Error}.");

                            notification.HandleResponse();

                            // TODO : redirect to friendly error page
                            // does 302 redirect, but SEO is not your concern here
                            // notification.Response.Redirect("/your/nice/error/page/address/here/");

                            notification.Response.Write($"Error retrieving user information. {userInfoResponse.Error}.");
                            return;
                        }

                        if (Logger.IsDebugEnabled())
                        {
                            Logger.Debug($"Userinfo received for sub: {notification.JwtSecurityToken.Subject}. Received claims: {GetClaimsAsString(userInfoResponse.Claims)}.");
                        }

                        // Create a new claims identity as the automatically created claimsidentity can contain claims that we don't need
                        // and we can keep the authentication cookie size smaller this way
                        // NOTE: Episerver uses the ClaimsIdentity name claim as the username (this will be also the display name when logged in), so make sure it is unique!
                        // Other claims synched automatically are (defined in class EPiServer.Security.ClaimTypeOptions, EPiServer.Framework):
                        // Email claim: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress
                        // GivenName claim: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname
                        // Surname claim: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname

                        // create new claimsidentity and set name claim name to JwtClaimTypes.PreferredUserName and role claim to JwtClaimTypes.Role
                        // NOTE!: The RP MUST NOT rely upon this value being unique, as discussed in http://openid.net/specs/openid-connect-basic-1_0-32.html#ClaimStability
                        // as Episerver uses the Name claim as the username (unique) and also as the display name in edit view, we could use the sub claim but this could be a guid
                        // so for the sake of the demo I will use the JwtClaimTypes.PreferredUserName even though it is said that it can't be tusted to be unique and can contani special characters
                        // in real world cases you just need to know what claims are unique and displayable for the end user, email might be one option but then you need to check that you get it always
                        // in this demo I will always return the same username in the JwtClaimTypes.PreferredUserName as was used to login to the IdP
                        var authClaimsIdentity = new ClaimsIdentity(notification.AuthenticationTicket.Identity.AuthenticationType, CustomClaimNames.EpiUsername, JwtClaimTypes.Role);

                        // split claims to two sets: role claims and other claims
                        List <Claim> roleClaims  = new List <Claim>();
                        List <Claim> otherClaims = new List <Claim>();

                        foreach (var c in userInfoResponse.Claims)
                        {
                            if (string.Compare(c.Type, CustomClaimNames.Permission, StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                roleClaims.Add(c);
                            }
                            else
                            {
                                otherClaims.Add(c);
                            }
                        }

                        // get the preferred username claim and if it doesn't exist use sub claim value
                        string username = otherClaims.GetClaimValue(JwtClaimTypes.PreferredUserName) ?? notification.JwtSecurityToken.Subject;
                        authClaimsIdentity.AddClaim(new Claim(CustomClaimNames.EpiUsername, username));

                        // should we add the claim to allow publishing of content
                        bool addPublisherClaim = false;

                        // is the user admin
                        var adminUserClaim = roleClaims.Find(c => string.Compare(c.Value, PermissionGroupNames.WebSiteSuperUser, StringComparison.OrdinalIgnoreCase) == 0);

                        if (adminUserClaim != null)
                        {
                            //   authClaimsIdentity.AddClaim(new Claim(JwtClaimTypes.Role, EpiRoles.Admin));
                            addPublisherClaim = true;
                        }

                        // you could have a claim for users from previous CMS and then you could have a custom mapping from that claim to new claim(s) used by Episerver
                        //var oldEditorClaim = roleClaims.Find(c => string.Compare(c.Value, "BOGUS_OLD_CMS_USER", StringComparison.OrdinalIgnoreCase) == 0);
                        //if (oldEditorClaim != null)
                        //{
                        //    authClaimsIdentity.AddClaim(new Claim(JwtClaimTypes.Role, "WebEditors"));
                        //    addPublisherClaim = true;
                        //}

                        // is the user editor
                        var editUserClaim = roleClaims.Find(c => string.Compare(c.Value, PermissionGroupNames.WebSiteEditor, StringComparison.OrdinalIgnoreCase) == 0);

                        if (editUserClaim != null)
                        {
                            //  authClaimsIdentity.AddClaim(new Claim(JwtClaimTypes.Role, EpiRoles.Editor));
                            addPublisherClaim = true;
                        }

                        // is the user a reader without edit/publishing rights
                        var readerUserClaim = roleClaims.Find(c => string.Compare(c.Value, PermissionGroupNames.WebSiteReader, StringComparison.OrdinalIgnoreCase) == 0);

                        if (readerUserClaim != null)
                        {
                            // authClaimsIdentity.AddClaim(new Claim(JwtClaimTypes.Role, EpiRoles.Editor));
                            // user will get the WebEditors role but not the role to publish/edit
                            // WebEditors role should only be used to grant access to the edit mode BUT not give any rights for content
                            // that is why we have the "SitePublishers" in this demo, we'll grant full permissions for content for this group
                            // but in real life scenario, you would have different and maybe more granular roles for different actions
                        }

                        // should we grant the publishing rights to the user
                        if (addPublisherClaim)
                        {
                            //   authClaimsIdentity.AddClaim(new Claim(JwtClaimTypes.Role, EpiRoles.Publisher));
                        }

                        // next get the email, givenname and surname claim values, our IdP uses JwtClaimTypes
                        // so this is not something that you can copy to your solution, but you need to check what claims your IdP returns
                        authClaimsIdentity.AddClaimFromSource(ClaimTypes.Email, otherClaims, JwtClaimTypes.Email);
                        authClaimsIdentity.AddClaimFromSource(ClaimTypes.GivenName, otherClaims, JwtClaimTypes.GivenName);
                        authClaimsIdentity.AddClaimFromSource(ClaimTypes.Surname, otherClaims, JwtClaimTypes.FamilyName);

                        // For now we don't need the access token, besides it expires in 60 minutes and we can't refresh it as we don't request for a refreshtoken
                        //authClaimsIdentity.AddClaim(new Claim(OpenIdConnectParameterNames.AccessToken, tokenResponse.AccessToken));
                        //authClaimsIdentity.AddClaim(new Claim("expires_at", DateTime.UtcNow.AddSeconds(tokenResponse.ExpiresIn).ToString()));

                        // this is needed for the logout, logout uses id_token_hint
                        authClaimsIdentity.AddClaim(new Claim(OpenIdConnectParameterNames.IdToken, notification.ProtocolMessage.IdToken));

                        // replace the automatically created authenticationticket with our ticket which contains our minimal set of claims
                        // remember to pass in the original ticket properties for the new ticket
                        notification.AuthenticationTicket = new AuthenticationTicket(authClaimsIdentity, notification.AuthenticationTicket.Properties);
                        System.Diagnostics.Debug.WriteLine($"Authenticated and logging in user '{GetFullName(notification.JwtSecurityToken.Claims)}' (sub: {notification.JwtSecurityToken.Subject}).");

                        Logger.Information($"Authenticated and logging in user '{GetFullName(authClaimsIdentity.Claims)}' (sub: {notification.JwtSecurityToken.Subject}).");

                        // Sync user and the roles to EPiServer in the background
                        // See: https://world.episerver.com/documentation/developer-guides/CMS/security/integrate-azure-ad-using-openid-connect/
                        // Please note that until a user with a role has logged in, you can't apply permissions to that role (as Episerver doesn't naturally know about that role)
                        await ServiceLocator.Current.GetInstance <ISynchronizingUserService>().SynchronizeAsync(notification.AuthenticationTicket.Identity);
                    },
                    AuthenticationFailed = notification =>
                    {
                        Logger.Error($"Authentication failed: {notification.Exception.Message}");

                        notification.HandleResponse();

                        // TODO: redirect to a nice error page
                        // does 302 redirect, but SEO is not your concern here
                        // notification.Response.Redirect("/your/nice/error/page/address/here/");
                        notification.Response.Write(notification.Exception.Message);
                        return(Task.FromResult(0));
                    },
                    SecurityTokenReceived = notification =>
                    {
                        // purely to log "stages" for demo and debugging, in real app usually you can leave this notification un-implemented

                        if (Logger.IsDebugEnabled())
                        {
                            try
                            {
                                Logger.Debug($"Security token received. Code: '{notification.ProtocolMessage.Code}', IdToken: '{notification.ProtocolMessage.IdToken}'.");
                            }
                            catch (Exception ex)
                            {
                                Logger.Error($"Security token received. Failed to read Code and IdToken for debug logging.", ex);
                            }
                        }

                        return(Task.FromResult(0));
                    },
                    SecurityTokenValidated = notification =>
                    {
                        // purely to log "stages" for demo and debugging, in real app usually you can leave this notification un-implemented

                        if (Logger.IsDebugEnabled())
                        {
                            try
                            {
                                Logger.Debug($"Security token validated for sub: {notification.AuthenticationTicket.Identity.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Subject)?.Value}.");
                            }
                            catch (Exception ex)
                            {
                                Logger.Error($"Security token validated. Failed to read values from protocol message for debug logging.", ex);
                            }
                        }

                        return(Task.FromResult(0));
                    },
                    MessageReceived = notification =>
                    {
                        // purely to log "stages" for demo and debugging, in real app usually you can leave this notification un-implemented

                        if (Logger.IsDebugEnabled())
                        {
                            Logger.Debug($"Message received.");
                        }

                        return(Task.FromResult(0));
                    }
                }
            });

            // see: https://docs.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-middleware-in-the-iis-integrated-pipeline#stage-markers
            app.UseStageMarker(PipelineStage.Authenticate);

            // TODO: your util url path here
            app.Map("/util/login.aspx", map =>
            {
                map.Run(ctx =>
                {
                    if (ctx.Authentication.User == null || !ctx.Authentication.User.Identity.IsAuthenticated)
                    {
                        // trigger authentication
                        ctx.Response.StatusCode = 401;
                    }
                    else
                    {
                        ctx.Response.Redirect("/");
                    }

                    return(Task.FromResult(0));
                });
            });

            // TODO: your util url path here
            app.Map("/util/logout.aspx", map =>
            {
                map.Run(ctx =>
                {
                    ctx.Authentication.SignOut();
                    return(Task.FromResult(0));
                });
            });
        }
        public async Task Mint_arbitrary_resource_owner_and_refresh_and_revoke()
        {
            /*
             *  grant_type:arbitrary_resource_owner
             *  client_id:arbitrary-resource-owner-client
             *  client_secret:secret
             *  scope:offline_access nitro metal
             *  arbitrary_claims:{"some-guid":"1234abcd","In":"Flames"}
             *  subject:Ratt
             *  access_token_lifetime:3600000
             */

            var client = new TokenClient(
                _fixture.TestServer.BaseAddress + "connect/token",
                ClientId,
                _fixture.MessageHandler);

            Dictionary <string, string> paramaters = new Dictionary <string, string>()
            {
                { OidcConstants.TokenRequest.ClientId, ClientId },
                { OidcConstants.TokenRequest.ClientSecret, ClientSecret },
                { OidcConstants.TokenRequest.GrantType, ArbitraryResourceOwnerExtensionGrant.Constants.ArbitraryResourceOwner },
                {
                    OidcConstants.TokenRequest.Scope,
                    $"{IdentityServerConstants.StandardScopes.OfflineAccess} nitro metal"
                },
                {
                    ArbitraryNoSubjectExtensionGrant.Constants.ArbitraryClaims,
                    "{'role': ['application', 'limited'],'query': ['dashboard', 'licensing'],'seatId': ['8c59ec41-54f3-460b-a04e-520fc5b9973d'],'piid': ['2368d213-d06c-4c2a-a099-11c34adc3579']}"
                },
                {
                    ArbitraryResourceOwnerExtensionGrant.Constants.Subject,
                    "Ratt"
                },
                { ArbitraryNoSubjectExtensionGrant.Constants.AccessTokenLifetime, "3600" }
            };
            var result = await client.RequestAsync(paramaters);

            result.AccessToken.ShouldNotBeNullOrEmpty();
            result.RefreshToken.ShouldNotBeNull();
            result.ExpiresIn.ShouldNotBeNull();

            paramaters = new Dictionary <string, string>()
            {
                { OidcConstants.TokenRequest.ClientId, ClientId },
                { OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.RefreshToken },
                { OidcConstants.TokenRequest.RefreshToken, result.RefreshToken }
            };
            result = await client.RequestAsync(paramaters);

            result.AccessToken.ShouldNotBeNullOrEmpty();
            result.RefreshToken.ShouldNotBeNull();
            result.ExpiresIn.ShouldNotBeNull();

            var revocationTokenClient = new TokenClient(
                _fixture.TestServer.BaseAddress + "connect/revocation",
                ClientId,
                ClientSecret,
                _fixture.MessageHandler);

            paramaters = new Dictionary <string, string>()
            {
                { "token_type_hint", OidcConstants.TokenTypes.RefreshToken },
                { "token", result.RefreshToken }
            };
            await revocationTokenClient.RequestAsync(paramaters);

            paramaters = new Dictionary <string, string>()
            {
                { OidcConstants.TokenRequest.ClientId, ClientId },
                { OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.RefreshToken },
                { OidcConstants.TokenRequest.RefreshToken, result.RefreshToken }
            };
            result = await client.RequestAsync(paramaters);

            result.Error.ShouldNotBeNullOrEmpty();
            result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant);
        }
コード例 #23
0
        public void CanGetUserInfoFromPatToken()
        {
            TokenClient client     = null !;
            UmaClient   umaClient  = null !;
            string      patToken   = null !;
            string      idToken    = null !;
            string      ticketId   = null !;
            string      rptToken   = null !;
            string      resourceId = null !;

            "Given a token client".x(
                () =>
            {
                client = new TokenClient(
                    TokenCredentials.FromClientCredentials("clientCredentials", "clientCredentials"),
                    _fixture.Client,
                    new Uri(WellKnownOpenidConfiguration));
            });

            "and a UMA client".x(() => { umaClient = new UmaClient(_fixture.Client, new Uri(BaseUrl)); });

            "and a PAT token".x(
                async() =>
            {
                var response = await client.GetToken(
                    TokenRequest.FromPassword("administrator", "password", new[] { "uma_protection" }))
                               .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;

                Assert.NotNull(response);
                Assert.NotNull(response.Item.AccessToken);
                Assert.NotNull(response.Item.IdToken);

                patToken = response.Item.AccessToken;
                idToken  = response.Item.IdToken;
            });

            "and a registered resource".x(
                async() =>
            {
                var resourceSet = new ResourceSet
                {
                    Description = "Test resource",
                    Name        = "Test resource",
                    Scopes      = new[] { "read" },
                    Type        = "Test resource"
                };
                var response =
                    await umaClient.AddResource(resourceSet, patToken).ConfigureAwait(false) as
                    Option <AddResourceSetResponse> .Result;

                Assert.NotNull(response);

                resourceId = response.Item.Id;
            });

            "and an updated authorization policy".x(
                async() =>
            {
                var resourceSet = new ResourceSet
                {
                    Id = resourceId,
                    AuthorizationPolicies =
                        new[]
                    {
                        new PolicyRule
                        {
                            ClientIdsAllowed = new[] { "clientCredentials" }, Scopes = new[] { "read" }
                        }
                    },
                    Description = "Test resource",
                    Name        = "Test resource",
                    Scopes      = new[] { "read" },
                    Type        = "Test resource"
                };
                var response =
                    await umaClient.UpdateResource(resourceSet, patToken).ConfigureAwait(false) as
                    Option <UpdateResourceSetResponse> .Result;

                Assert.NotNull(response);

                resourceId = response.Item.Id;
            });

            "When getting a ticket".x(
                async() =>
            {
                var ticketResponse = await umaClient.RequestPermission(
                    patToken,
                    requests: new PermissionRequest {
                    ResourceSetId = resourceId, Scopes = new[] { "read" }
                })
                                     .ConfigureAwait(false) as Option <TicketResponse> .Result;

                Assert.NotNull(ticketResponse);

                ticketId = ticketResponse.Item.TicketId;
            });

            "and getting an RPT token".x(
                async() =>
            {
                var rptResponse = await client.GetToken(TokenRequest.FromTicketId(ticketId, idToken))
                                  .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result;

                Assert.NotNull(rptResponse);

                rptToken = rptResponse.Item.AccessToken;
            });

            "then can introspect RPT token using PAT token as authentication".x(
                async() =>
            {
                var introspectResult = await umaClient
                                       .Introspect(IntrospectionRequest.Create(rptToken, "access_token", patToken))
                                       .ConfigureAwait(false);

                Assert.IsType <Option <UmaIntrospectionResponse> .Result>(introspectResult);
            });
        }
コード例 #24
0
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseKentorOwinCookieSaver();

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

            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId              = "mvc.5",
                Authority             = "http://localhost:5000/",
                RedirectUri           = "http://localhost:2000/",
                PostLogoutRedirectUri = "http://localhost:2000/",
                ResponseType          = "code id_token",
                Scope = "openid profile offline_access",

                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role"
                },

                SignInAsAuthenticationType = "Cookies",

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async n =>
                    {
                        // use the code to get the access and refresh token
                        var tokenClient = new TokenClient(
                            "http://localhost:5000/connect/token",
                            "mvc.5",
                            "secret");

                        var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(
                            n.Code, n.RedirectUri);

                        if (tokenResponse.IsError)
                        {
                            throw new Exception(tokenResponse.Error);
                        }

                        // use the access token to retrieve claims from userinfo
                        var userInfoClient = new UserInfoClient(
                            new Uri("http://localhost:5000/connect/userinfo"),
                            tokenResponse.AccessToken);

                        var userInfoResponse = await userInfoClient.GetAsync();

                        // create new identity
                        var id = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType);
                        id.AddClaims(userInfoResponse.GetClaimsIdentity().Claims);

                        id.AddClaim(new Claim("access_token", tokenResponse.AccessToken));
                        id.AddClaim(new Claim("expires_at", DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToLocalTime().ToString()));
                        id.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken));
                        id.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                        id.AddClaim(new Claim("sid", n.AuthenticationTicket.Identity.FindFirst("sid").Value));

                        n.AuthenticationTicket = new AuthenticationTicket(
                            new ClaimsIdentity(id.Claims, n.AuthenticationTicket.Identity.AuthenticationType, "name", "role"),
                            n.AuthenticationTicket.Properties);
                    },

                    RedirectToIdentityProvider = n =>
                    {
                        // if signing out, add the id_token_hint
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (idTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                            }
                        }

                        return(Task.FromResult(0));
                    }
                }
            });
        }
コード例 #25
0
ファイル: Startup.cs プロジェクト: AndersJuul/RideShare
        public void Configuration(IAppBuilder app)
        {
            Log.Logger = StandardLoggerConfigurator
                         .GetLoggerConfig().MinimumLevel
                         .Debug()
                         .CreateLogger();

            Log.Logger.Information("Starting...");
            Log.Logger.Information("Version is... " + ConfigurationManager.AppSettings["ReleaseNumber"]);

            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap <Event, EventViewModel>()
                .ForMember(x => x.ViewModelMode, x => x.Ignore())
                .ForMember(x => x.CarEmail, x => x.Ignore())
                .ForMember(x => x.CarName, x => x.Ignore())
                .ForMember(x => x.CarPhone, x => x.Ignore());
            });

            Mapper.Configuration.AssertConfigurationIsValid();

            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            AntiForgeryConfig.UniqueClaimTypeIdentifier =
                JwtClaimTypes.Name;

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies",
                ExpireTimeSpan     = new TimeSpan(0, 30, 0),
                SlidingExpiration  = true
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId    = ClientId,
                Authority   = ConfigurationManager.AppSettings["IdentityServerApplicationUrl"],
                RedirectUri = ConfigurationManager.AppSettings["UrlRideShareWeb"],
                SignInAsAuthenticationType = "Cookies",
                ResponseType          = "code id_token token",
                Scope                 = "openid profile address gallerymanagement roles offline_access email",
                UseTokenLifetime      = false,
                PostLogoutRedirectUri = ConfigurationManager.AppSettings["UrlRideShareWeb"],

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        TokenHelper.DecodeAndWrite(n.ProtocolMessage.IdToken);
                        TokenHelper.DecodeAndWrite(n.ProtocolMessage.AccessToken);

                        var givenNameClaim = n.AuthenticationTicket
                                             .Identity.FindFirst(JwtClaimTypes.GivenName);

                        var familyNameClaim = n.AuthenticationTicket
                                              .Identity.FindFirst(JwtClaimTypes.FamilyName);

                        var subClaim = n.AuthenticationTicket
                                       .Identity.FindFirst(JwtClaimTypes.Subject);

                        var roleClaim = n.AuthenticationTicket
                                        .Identity.FindFirst(JwtClaimTypes.Role);

                        var emailClaim = n.AuthenticationTicket
                                         .Identity.FindFirst(JwtClaimTypes.Email);

                        // create a new claims, issuer + sub as unique identifier
                        var nameClaim = new Claim(JwtClaimTypes.Name,
                                                  Constants.AndersAtHomeIdentityServerIssuerUri + subClaim.Value);

                        var newClaimsIdentity = new ClaimsIdentity(
                            n.AuthenticationTicket.Identity.AuthenticationType,
                            JwtClaimTypes.Name,
                            JwtClaimTypes.Role);

                        newClaimsIdentity.AddClaim(nameClaim);

                        if (givenNameClaim != null)
                        {
                            newClaimsIdentity.AddClaim(givenNameClaim);
                        }

                        if (familyNameClaim != null)
                        {
                            newClaimsIdentity.AddClaim(familyNameClaim);
                        }

                        if (roleClaim != null)
                        {
                            newClaimsIdentity.AddClaim(roleClaim);
                        }

                        if (emailClaim != null)
                        {
                            newClaimsIdentity.AddClaim(emailClaim);
                        }

                        // request a refresh token
                        var tokenClientForRefreshToken = new TokenClient(
                            ConfigurationManager.AppSettings["IdentityServerApplicationUrl"] + "/connect/token",
                            ClientId,
                            Constants.RideShareWebClientSecret);

                        var refreshResponse = await
                                              tokenClientForRefreshToken.RequestAuthorizationCodeAsync(
                            n.ProtocolMessage.Code,
                            ConfigurationManager.AppSettings["UrlRideShareWeb"]);

                        var expirationDateAsRoundtripString
                            = DateTime.SpecifyKind(DateTime.UtcNow.AddSeconds(refreshResponse.ExpiresIn)
                                                   , DateTimeKind.Utc).ToString("o");


                        newClaimsIdentity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                        newClaimsIdentity.AddClaim(new Claim("refresh_token", refreshResponse.RefreshToken));
                        newClaimsIdentity.AddClaim(new Claim("access_token", refreshResponse.AccessToken));
                        newClaimsIdentity.AddClaim(new Claim("expires_at", expirationDateAsRoundtripString));
                        newClaimsIdentity.AddClaim(new Claim("sub", subClaim.Value));

                        // create a new authentication ticket, overwriting the old one.
                        n.AuthenticationTicket = new AuthenticationTicket(
                            newClaimsIdentity,
                            n.AuthenticationTicket.Properties);
                    },
                    RedirectToIdentityProvider = async n =>
                    {
                        await Task.FromResult(0);

                        // get id token to add as id token hint
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var identityTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (identityTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = identityTokenHint.Value;
                            }
                        }
                        //else if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.AuthenticationRequest)
                        //{
                        //    string existingAcrValues = null;
                        //    if (n.ProtocolMessage.Parameters.TryGetValue("acr_values", out existingAcrValues))
                        //    {
                        //        // add "2fa" - acr_values are separated by a space
                        //        n.ProtocolMessage.Parameters["acr_values"] = existingAcrValues + " 2fa";
                        //    }

                        //    n.ProtocolMessage.Parameters["acr_values"] = "2fa";
                        //}
                    }
                }
            });
        }
コード例 #26
0
        public virtual async Task <TokenResponse> Login(string userName, string password, string clientId, string secret = "secret")
        {
            TokenClient client = BuildTokenClient(clientId, secret);

            return(await client.RequestResourceOwnerPasswordAsync(userName, password, "openid profile user_info"));
        }
コード例 #27
0
        public void Configuration(IAppBuilder app)
        {
            // Define que a chave do usuário vem da Claim "sub"
            AntiForgeryConfig.UniqueClaimTypeIdentifier = "sub";
            // Desliga o mapeamento automático de Claims do asp.net, os nomes ficam como as
            // Claims do Acesso Cidadão..
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            // Configurar o OWIN para gerenciar autenticação usando Cookies
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            // Configurando para fazer autenticação usando OpenID Connect
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority = Constants.BaseAddress,
                ClientId  = Constants.ClientIdCorporativo,
                //ClientSecret = Constants.ClientSecretCorporativo,
                RedirectUri  = Constants.RedirectUriCorporativo,
                ResponseType = "id_token code",
                // A maioria desses scopes só está disponível para sistemas corporativos do estado
                // e precisa de permissão explicita da área responsável. Fazer requisição devidamente
                // fundamentada de porque a informação é necessária
                Scope = "openid nome email cpf dataNascimento filiacao permissoes roles offline_access api-teste",
                //Essas permissões só podem ser usadas em sistemas corporativos
                //Scope = "openid cpf nome email dataNascimento permissoes roles",

                // Configura o middleware do openid connect para usar o middleware configurado acima
                // para controlar a autenticação usando cookies
                SignInAsAuthenticationType = "Cookies",

                // Essa parte é totalmente opcional
                // Nesse exemplo a gente vai usar ela para apagar algumas claims que vem do Acesso Cidadão
                // e não queremos guardar e para setar o nome da identity
                // Mas também pode ser usada para fazer qualquer tipo de mapeamento das claims que vem do Acesso Cidadão
                // Por exemplo: Trocar o nome, por primeiro nome e sobrenome, mapear as permissões para outra
                // representação e assim por diante
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async n =>
                    {
                        // use the code to get the access and refresh token
                        var tokenClient = new TokenClient(
                            Constants.TokenEndpoint,
                            Constants.ClientIdCorporativo,
                            Constants.ClientSecretCorporativo);

                        var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(
                            n.Code, n.RedirectUri);

                        if (tokenResponse.IsError)
                        {
                            throw new Exception(tokenResponse.Error);
                        }

                        // use the access token to retrieve claims from userinfo
                        var userInfoClient   = new UserInfoClient(Constants.UserInfoEndpoint);
                        var userInfoResponse = await userInfoClient.GetAsync(tokenResponse.AccessToken);

                        // create new identity
                        var id = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType);
                        id.AddClaims(userInfoResponse.Claims);

                        id.AddClaim(new Claim("access_token", tokenResponse.AccessToken));
                        id.AddClaim(new Claim("expires_at", DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToLocalTime().ToString()));
                        id.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken));
                        id.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                        id.AddClaim(new Claim("sid", n.AuthenticationTicket.Identity.FindFirst("sid").Value));

                        n.AuthenticationTicket = new AuthenticationTicket(
                            new ClaimsIdentity(id.Claims, n.AuthenticationTicket.Identity.AuthenticationType, "nome", "role"),
                            n.AuthenticationTicket.Properties);
                    },

                    RedirectToIdentityProvider = n =>
                    {
                        // if signing out, add the id_token_hint
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (idTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                            }
                        }

                        return(Task.FromResult(0));
                    }
                }
            });
        }
コード例 #28
0
 public async Task <string> Typed([FromServices] TokenClient tokenClient)
 {
     return(await tokenClient.GetToken());
 }
コード例 #29
0
ファイル: Program.cs プロジェクト: jasarsoft/BankOfDotNet
        private static async Task MainAsync()
        {
            var discoRO = await IdentityModel.Client.DiscoveryClient.GetAsync("http://localhost:50000");

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

            //grab a bearer token using ResourceOwnerPassword Grant Type
            var tokenClientRO   = new TokenClient(discoRO.TokenEndpoint, "ro.client", "secret");
            var tokenResponseRO = await tokenClientRO.RequestResourceOwnerPasswordAsync("Manish", "password", "bankOfDotNetApi");

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

            Console.WriteLine(tokenResponseRO.Json);
            Console.WriteLine("\n\n");



            //dicover all the endpoints using metadata od identity server
            var disco = await IdentityModel.Client.DiscoveryClient.GetAsync("http://localhost:50000");

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

            //grab a bearer token using Client Credential Flow
            var tokenClient   = new TokenClient(disco.TokenEndpoint, "client", "secret");
            var tokenResponse = await tokenClient.RequestClientCredentialsAsync("bankOfDotNetApi");

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

            Console.WriteLine(tokenResponse.Json);
            Console.WriteLine("\n\n");

            //cosumer our Customer API
            var client = new HttpClient();

            client.SetBearerToken(tokenResponse.AccessToken);

            var customerInfo = new StringContent(
                JsonConvert.SerializeObject(
                    new { Id = 10, FirstName = "Manish", LastName = "Narayan" }),
                Encoding.UTF8, "application/json");

            var createCustomerResponse = await client.PostAsync("http://localhost:63504/api/customers", customerInfo);

            if (!createCustomerResponse.IsSuccessStatusCode)
            {
                Console.WriteLine(createCustomerResponse.StatusCode);
            }

            var getCustomerResponse = await client.GetAsync("http://localhost:63504/api/customers");

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

                Console.WriteLine(JArray.Parse(content));
            }

            Console.Read();
        }
コード例 #30
0
        private static async Task MainAsync()
        {
            string apiEndPoint      = "http://localhost:58840/api/customers";
            string identityEndPoint = "http://localhost:5000";

            //controllo se ci sono client connessi all'authority di is4
            //resource owner grant-type
            var discoRO = await DiscoveryClient.GetAsync(identityEndPoint);

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

            //ricavo il token da ISvr4 comunicando le credenziali del client
            var tokenClientRO = new TokenClient(discoRO.TokenEndpoint, "ro.client", "secret");
            //vedere gli Users che possono accedere elencati in Config.cs del progetto IS4
            var tokenResponseRO = await tokenClientRO.RequestResourceOwnerPasswordAsync("Gaetano", "password", "BankofdotNetAPI");

            if (tokenResponseRO.IsError)
            {
                Console.WriteLine(tokenResponseRO.Error);
                return;
            }
            Console.WriteLine(tokenResponseRO.Json);
            Console.WriteLine("\n\n");


            //controllo se ci sono client connessi all'authority di is4
            var disco = await DiscoveryClient.GetAsync(identityEndPoint);

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

            //ricavo il token da ISvr4 comunicando le credenziali del client
            var tokenClient   = new TokenClient(disco.TokenEndpoint, "client", "secret");
            var tokenResponse = await tokenClient.RequestClientCredentialsAsync("BankofdotNetAPI");

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }
            Console.WriteLine(tokenResponse.Json);
            Console.WriteLine("\n\n");

            //ottenuto il token posso interrogare le mie API
            var client = new HttpClient();

            client.SetBearerToken(tokenResponseRO.AccessToken);

            //creo un content di tipo json=>string da inviare nel body del post verso la API di creazione customer
            var customerInfo = new StringContent(
                JsonConvert.SerializeObject(
                    new { Id = 12, FirstName = "gaetanos", LastName = "Scrimieri" }), Encoding.UTF8, "application/json");

            //post a web api
            var createcustomerResponse = await client.PostAsync(apiEndPoint, customerInfo);

            if (!createcustomerResponse.IsSuccessStatusCode)
            {
                Console.WriteLine(createcustomerResponse.StatusCode);
            }

            //leggo tutti gli utenti
            var getcustomerResponse = await client.GetAsync(apiEndPoint);

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

                Console.WriteLine(JArray.Parse(content));
            }

            Console.Read();
        }
コード例 #31
0
 public SettingsPage()
 {
     InitializeComponent();
     _tokenClient = new TokenClient();
 }