public async Task When_Authenticate_ResourceOwner_Then_Claims_Are_Returned()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string subject   = "subject";
            var          parameter = new LocalAuthenticationParameter
            {
                UserName = "******",
                Password = "******"
            };
            var resourceOwner = new ResourceOwner
            {
                Id = subject
            };

            _authenticateResourceOwnerServiceStub.Setup(r => r.AuthenticateResourceOwnerAsync(It.IsAny <string>(),
                                                                                              It.IsAny <string>()))
            .Returns(Task.FromResult(resourceOwner));

            // ACT
            var res = await _localUserAuthenticationAction.Execute(parameter);

            // ASSERT
            Assert.NotNull(res);
        }
Пример #2
0
        public Scope Put(Scope ToUpdate)
        {
            if (!this.Request.Items.ContainsKey("auth:user"))
            {
                return(null);
            }

            ResourceOwner user = this.Request.Items.GetValue <ResourceOwner>("auth:user");


            Scope scope = null;

            ///TODO:implement admin account check
            if (false)
            {
                scope = ScopeModel.SetScope(ToUpdate);
            }
            else
            {
                scope = ScopeModel.SetScope(ToUpdate, user);
            }

            if (scope != null)
            {
                return(scope);
            }

            Response.StatusCode        = (int)System.Net.HttpStatusCode.Forbidden;
            Response.StatusDescription = "You do not have access to update this scope";
            return(null);
        }
        public async Task When_Passing_Needed_Parameter_To_LocalUserAuthentication_Then_Operation_Is_Called()
        {
            // ARRANGE
            InitializeFakeObjects();
            var localAuthenticationParameter = new LocalAuthenticationParameter
            {
                Password = "******",
                UserName = "******"
            };
            var resourceOwner = new ResourceOwner
            {
                Password = "******",
                Id       = "username"
            };

            _localUserAuthenticationActionFake.Setup(l => l.Execute(It.IsAny <LocalAuthenticationParameter>()))
            .Returns(Task.FromResult(resourceOwner));

            // ACT
            var result = await _authenticateActions.LocalUserAuthentication(localAuthenticationParameter);

            // ASSERT
            Assert.NotNull(result);
            Assert.True(result.Id == "username" && result.Password == "password");
        }
Пример #4
0
        public static void RedirectToAuthorization(this WebOperationContext context, ServerWithAuthorizationCode server, Uri redirectionUri, ResourceOwner resourceOwner)
        {

            context.OutgoingResponse.StatusCode = HttpStatusCode.Redirect;
            SetRedirectUriInToken(server, resourceOwner, redirectionUri);
            context.OutgoingResponse.Location = GetAuthorizationLocation(server, redirectionUri, resourceOwner);
        }
Пример #5
0
        public void TokenToXElement()
        {
            var server1 = new ServerWithAuthorizationCode("test", "testsecret",
                                                          new Uri("http://example.org/foo"),
                                                          new Uri("http://example.org/access"),
                                                          new Uri("http://example.org/test2"));
            var resourceOwner1 = new ResourceOwner("testmann1");

            var token = new Token(server1, resourceOwner1);

            token.AuthorizationCode = "auth1";
            token.AccessToken       = "access1";
            token.RefreshToken      = "refresht";
            token.RedirectUri       = new Uri("http://example.org/redirect");

            var element1 = token.ToXElement();

            element1.Name.ToString().Should().Be("Token");
            element1.Element("Server").Value.Should().Be(server1.Guid.ToString());
            element1.Element("ResourceOwner").Value.Should().Be(resourceOwner1.Name);
            element1.Element("AuthorizationCode").Value.Should().Be("auth1");
            element1.Element("AccessToken").Value.Should().Be("access1");
            element1.Element("RefreshToken").Value.Should().Be("refresht");
            element1.Element("RedirectUri").Value.Should().Be("http://example.org/redirect");
        }
Пример #6
0
        public async Task SendAsync(string code, ResourceOwner user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (user.Claims == null)
            {
                throw new ArgumentNullException(nameof(user.Claims));
            }

            var phoneNumberClaim = user.Claims.FirstOrDefault(c => c.Type == "phone_number");

            if (phoneNumberClaim == null)
            {
                throw new ArgumentException("the phone number is missing");
            }

            await SendMessage(new TwilioSmsCredentials
            {
                AccountSid = _options.TwilioAccountSid,
                AuthToken  = _options.TwilioAuthToken,
                FromNumber = _options.TwilioFromNumber,
            }, phoneNumberClaim.Value, string.Format(_options.TwilioMessage, code));
        }
Пример #7
0
        public void GetToken()
        {
            var server1 = new ServerWithAuthorizationCode("test", "testsecret",
                                                          new Uri("http://example.org/foo"),
                                                          new Uri("http://example.org/access"),
                                                          new Uri("http://example.org/test2"));
            var resourceOwner1 = new ResourceOwner("testmann1");

            Tokens.CleanUpForTests();
            var token1 = Tokens.GetToken(server1, resourceOwner1);

            token1.Should().NotBeNull();
            token1.ResourceOwner.Should().Be(resourceOwner1);
            token1.Server.Should().Be(server1);
            token1.AuthorizationCode.Should().BeNullOrEmpty();
            token1.AccessToken.Should().BeNullOrEmpty();
            token1.RefreshToken.Should().BeNullOrEmpty();

            token1.AuthorizationCode = "AuthorizationCode";
            token1.AccessToken       = "AccessToken";
            token1.RefreshToken      = "RefreshToken";
            token1.Expires           = DateTime.Now;

            var token2 = Tokens.GetToken(server1, resourceOwner1);

            token2.AuthorizationCode.Should().Be("AuthorizationCode");
            token2.AccessToken.Should().Be("AccessToken");
            token2.RefreshToken.Should().Be("RefreshToken");
            DateTime.Now.Subtract(token2.Expires).Should().BeLessOrEqualTo(new TimeSpan(0, 0, 1, 0));
        }
Пример #8
0
        public void TokenComperator()
        {
            var server1 = new ServerWithAuthorizationCode("test", "testsecret",
                                                          new Uri("http://example.org/foo"),
                                                          new Uri("http://example.org/access"),
                                                          new Uri("http://example.org/test2"));
            var server2 = new ServerWithAuthorizationCode("test2", "testsecret",
                                                          new Uri("http://example.org/fo32o"),
                                                          new Uri("http://example.org/access"),
                                                          new Uri("http://example.org/tesdst2"));
            var resourceOwner1 = new ResourceOwner("testmann1");
            var resourceOwner2 = new ResourceOwner("testmann2");

            var token1 = new Token(server1, resourceOwner1);
            var token2 = new Token(server1, resourceOwner2);
            var token3 = new Token(server2, resourceOwner1);
            var token4 = new Token(server2, resourceOwner2);
            var token5 = new Token(server1, resourceOwner1);

            token1.Equals(token1).Should().BeTrue();
            token1.Equals(token2).Should().BeFalse();
            token1.Equals(token3).Should().BeFalse();
            token1.Equals(token4).Should().BeFalse();
            token1.Equals(token5).Should().BeTrue();

            (token1 == token5).Should().BeTrue();
            (token1 == token2).Should().BeFalse();
            (token1 != token2).Should().BeTrue();
            (token1 == null).Should().BeFalse();

            token1.Equals(42).Should().BeFalse();
            token1.Equals(null).Should().BeFalse();
        }
Пример #9
0
        public async Task <ResourceOwner> GetUser()
        {
            using var session = _store.OpenSession();
            {
                var existing = new ResourceOwner
                {
                    Subject        = "administrator",
                    CreateDateTime = DateTime.UtcNow,
                    IsLocalAccount = true,
                    UpdateDateTime = DateTimeOffset.UtcNow,
                    Password       = "******".ToSha256Hash(string.Empty)
                };
                existing.Claims = existing.Claims.Concat(
                    new[]
                {
                    new Claim("scope", "manager"),
                    new Claim("scope", "uma_protection"),
                    new Claim("role", "administrator"),
                })
                                  .ToArray();
                session.Store(existing);
                await session.SaveChangesAsync().ConfigureAwait(false);

                return(existing);
            }
        }
Пример #10
0
        public object Delete(Client ToDelete)
        {
            bool deleted = false;

            if (!this.Request.Items.ContainsKey("auth:user"))
            {
                return(null);
            }

            ResourceOwner user = this.Request.Items.GetValue <ResourceOwner>("auth:user");

            ///TODO:implement admin account check
            if (false)
            {
                deleted = ClientModel.DeleteClient(ToDelete);
            }
            else
            {
                deleted = ClientModel.DeleteClient(ToDelete, user);
            }

            HttpResult res = new HttpResult()
            {
                StatusDescription = "Client Deleted",
            };

            if (!deleted)
            {
                res.StatusCode        = System.Net.HttpStatusCode.Forbidden;
                res.StatusDescription = "You do not have access to this client";
            }

            return(res);
        }
Пример #11
0
        public async Task <bool> SendCode(string code, string twoFactorAuthType, ResourceOwner user)
        {
            if (string.IsNullOrWhiteSpace(code))
            {
                throw new ArgumentNullException(nameof(code));
            }

            if (string.IsNullOrWhiteSpace(twoFactorAuthType))
            {
                throw new ArgumentNullException(nameof(twoFactorAuthType));
            }

            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            var service = Get(twoFactorAuthType);

            if (service == null)
            {
                return(false);
            }

            await service.SendAsync(code, user);

            return(true);
        }
Пример #12
0
        public Client Put(Client ToUpdate)
        {
            Client updated = null;

            if (!this.Request.Items.ContainsKey("auth:user"))
            {
                return(null);
            }

            ResourceOwner user = this.Request.Items.GetValue <ResourceOwner>("auth:user");

            ///TODO:implement admin account check
            if (false)
            {
                updated = ClientModel.SetClient(ToUpdate);
            }
            else
            {
                updated = ClientModel.SetClient(ToUpdate, user);
            }

            if (updated == null)
            {
                Response.StatusCode        = (int)System.Net.HttpStatusCode.Forbidden;
                Response.StatusDescription = "You do not have access to this client";
            }

            return(updated);
        }
Пример #13
0
        public void TokenComperator()
        {
            var server1 = new ServerWithAuthorizationCode("test", "testsecret",
                                                          new Uri("http://example.org/foo"),
                                                          new Uri("http://example.org/access"),
                                                          new Uri("http://example.org/test2"));
            var server2 = new ServerWithAuthorizationCode("test2", "testsecret",
                                                          new Uri("http://example.org/fo32o"),
                                                          new Uri("http://example.org/access"),
                                                          new Uri("http://example.org/tesdst2"));
            var resourceOwner1 = new ResourceOwner("testmann1");
            var resourceOwner2 = new ResourceOwner("testmann2");

            var token1 = new Token(server1,resourceOwner1);
            var token2 = new Token(server1,resourceOwner2);
            var token3 = new Token(server2,resourceOwner1);
            var token4 = new Token(server2,resourceOwner2);
            var token5 = new Token(server1,resourceOwner1);

            token1.Equals(token1).Should().BeTrue();
            token1.Equals(token2).Should().BeFalse();
            token1.Equals(token3).Should().BeFalse();
            token1.Equals(token4).Should().BeFalse();
            token1.Equals(token5).Should().BeTrue();

            (token1 == token5).Should().BeTrue();
            (token1 == token2).Should().BeFalse();
            (token1 != token2).Should().BeTrue();
            (token1 == null).Should().BeFalse();

            token1.Equals(42).Should().BeFalse();
            token1.Equals(null).Should().BeFalse();

        }
Пример #14
0
        public void GetToken()
        {
            var server1 = new ServerWithAuthorizationCode("test", "testsecret",
                                                          new Uri("http://example.org/foo"),
                                                          new Uri("http://example.org/access"),
                                                          new Uri("http://example.org/test2"));
            var resourceOwner1 = new ResourceOwner("testmann1");
            Tokens.CleanUpForTests();
            var token1 = Tokens.GetToken(server1, resourceOwner1);

            token1.Should().NotBeNull();
            token1.ResourceOwner.Should().Be(resourceOwner1);
            token1.Server.Should().Be(server1);
            token1.AuthorizationCode.Should().BeNullOrEmpty();
            token1.AccessToken.Should().BeNullOrEmpty();
            token1.RefreshToken.Should().BeNullOrEmpty();

            token1.AuthorizationCode = "AuthorizationCode";
            token1.AccessToken = "AccessToken";
            token1.RefreshToken = "RefreshToken";
            token1.Expires = DateTime.Now;

            var token2 = Tokens.GetToken(server1, resourceOwner1);

            token2.AuthorizationCode.Should().Be("AuthorizationCode");
            token2.AccessToken.Should().Be("AccessToken");
            token2.RefreshToken.Should().Be("RefreshToken");
            DateTime.Now.Subtract(token2.Expires).Should().BeLessOrEqualTo(new TimeSpan(0, 0, 1, 0));

        }
Пример #15
0
        public void CannotDeleteClaimsNotPartOfScope()
        {
            HttpResponseMessage response      = null !;
            ResourceOwner       resourceOwner = null !;

            "When deleting user claims not in scope".x(
                async() =>
            {
                var request = new HttpRequestMessage
                {
                    Method     = HttpMethod.Delete,
                    RequestUri = new Uri(
                        _fixture.Server.BaseAddress + "resource_owners/claims?type=some_other_claim")
                };
                request.Headers.Authorization = new AuthenticationHeaderValue(
                    "Bearer",
                    _administratorToken.AccessToken);
                response = await _fixture.Client().SendAsync(request).ConfigureAwait(false);
            });

            "Then is ok request".x(() => { Assert.Equal(HttpStatusCode.OK, response.StatusCode); });

            "And when getting resource owner from store".x(
                async() =>
            {
                var store = (IResourceOwnerStore)_fixture.Server.Host.Services.GetService(
                    typeof(IResourceOwnerStore));
                resourceOwner = await store.Get("administrator", CancellationToken.None).ConfigureAwait(false);
            });

            "Then resource owner still has claim".x(
                () => { Assert.Contains(resourceOwner.Claims, c => c.Type == "some_other_claim"); });
        }
        public async Task When_Passing_A_Not_Allowed_Scopes_Then_Exception_Is_Throw()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string clientAssertion                 = "clientAssertion";
            const string clientAssertionType             = "clientAssertionType";
            const string clientId                        = "clientId";
            const string clientSecret                    = "clientSecret";
            const string invalidScope                    = "invalidScope";
            var          resourceOwnerGrantTypeParameter = new ResourceOwnerGrantTypeParameter
            {
                ClientAssertion     = clientAssertion,
                ClientAssertionType = clientAssertionType,
                ClientId            = clientId,
                ClientSecret        = clientSecret,
                Scope = invalidScope
            };
            var client        = new AuthenticationResult(new Models.Client(), null);
            var resourceOwner = new ResourceOwner();

            _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>()))
            .Returns(new AuthenticateInstruction());
            _authenticateClientFake.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateInstruction>()))
            .Returns(() => Task.FromResult(client));
            _resourceOwnerValidatorFake.Setup(
                r => r.AuthenticateResourceOwnerAsync(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(() => Task.FromResult(resourceOwner));
            _scopeValidatorFake.Setup(s => s.Check(It.IsAny <string>(), It.IsAny <Models.Client>()))
            .Returns(() => new ScopeValidationResult(false));

            // ACT & ASSERTS
            var exception = await Assert.ThrowsAsync <IdentityServerException>(() => _getTokenByResourceOwnerCredentialsGrantTypeAction.Execute(resourceOwnerGrantTypeParameter, null));

            Assert.True(exception.Code == ErrorCodes.InvalidScope);
        }
Пример #17
0
        /// <inheritdoc />
        public Task <Option> Update(ResourceOwner resourceOwner, CancellationToken cancellationToken)
        {
            if (resourceOwner == null)
            {
                throw new ArgumentNullException(nameof(resourceOwner));
            }

            var user = _users.FirstOrDefault(u => u.Subject == resourceOwner.Subject);

            if (user == null)
            {
                return(Task.FromResult <Option>(new Option.Error(new ErrorDetails
                {
                    Title = ErrorCodes.InternalError,
                    Detail = Strings.TheRoDoesntExist,
                    Status = HttpStatusCode.InternalServerError
                })));
            }

            user.IsLocalAccount          = resourceOwner.IsLocalAccount;
            user.TwoFactorAuthentication = resourceOwner.TwoFactorAuthentication;
            user.UpdateDateTime          = DateTimeOffset.UtcNow;
            user.Claims = resourceOwner.Claims;
            return(Task.FromResult <Option>(new Option.Success()));
        }
Пример #18
0
        public async Task When_No_Consent_Has_Been_Given_Then_Create_And_Insert_A_New_One()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string subject = "subject";
            var          authorizationParameter = new AuthorizationParameter
            {
                Claims       = null,
                Scope        = "profile",
                ResponseMode = ResponseMode.None
            };
            var claims = new List <Claim>
            {
                new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.Subject, subject)
            };
            var claimsIdentity  = new ClaimsIdentity(claims, "SimpleIdentityServer");
            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            var client          = new Models.Client
            {
                ClientId = "clientId"
            };
            var resourceOwner = new ResourceOwner
            {
                Id = subject
            };
            var actionResult = new ActionResult
            {
                Type = TypeActionResult.RedirectToCallBackUrl,
                RedirectInstruction = new RedirectInstruction
                {
                }
            };
            ICollection <Scope> scopes = new List <Scope>();

            _consentHelperFake.Setup(c => c.GetConfirmedConsentsAsync(It.IsAny <string>(),
                                                                      It.IsAny <AuthorizationParameter>()))
            .Returns(Task.FromResult((Models.Consent)null));
            _clientRepositoryFake.Setup(c => c.GetClientByIdAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(client));
            _parameterParserHelperFake.Setup(p => p.ParseScopes(It.IsAny <string>()))
            .Returns(new List <string>());
            _scopeRepositoryFake.Setup(s => s.SearchByNamesAsync(It.IsAny <IEnumerable <string> >()))
            .Returns(Task.FromResult(scopes));
            _authenticateResourceOwnerServiceStub.Setup(r => r.AuthenticateResourceOwnerAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(resourceOwner));
            _actionResultFactoryFake.Setup(a => a.CreateAnEmptyActionResultWithRedirectionToCallBackUrl())
            .Returns(actionResult);
            _parameterParserHelperFake.Setup(p => p.ParseResponseTypes(It.IsAny <string>()))
            .Returns(new List <ResponseType> {
                ResponseType.code
            });

            // ACT
            var result = await _confirmConsentAction.Execute(authorizationParameter, claimsPrincipal);

            // ASSERT
            _consentRepositoryFake.Verify(c => c.InsertAsync(It.IsAny <Models.Consent>()));
            _actionResultFactoryFake.Verify(a => a.CreateAnEmptyActionResultWithRedirectionToCallBackUrl());
            Assert.True(result.RedirectInstruction.ResponseMode == ResponseMode.query);
        }
        public async Task SendAsync(string code, ResourceOwner user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (user.Claims == null)
            {
                throw new ArgumentNullException(nameof(user.Claims));
            }

            var phoneNumberClaim = user.Claims.FirstOrDefault(c => c.Type == Core.Jwt.Constants.StandardResourceOwnerClaimNames.PhoneNumber);

            if (phoneNumberClaim == null)
            {
                throw new ArgumentException("the phone number is missing");
            }

            var settings = await _settingClient.GetSettingsByResolving(_configurationUrl);

            if (!_settingNames.All(k => settings.Any(s => s.Key == k)))
            {
                throw new InvalidOperationException("there are one or more missing settings");
            }

            var dic = settings.ToDictionary(s => s.Key);

            await SendMessage(new TwilioSmsCredentials
            {
                AccountSid = dic[TwilioAccountSid].Value,
                AuthToken  = dic[TwilioAuthToken].Value,
                FromNumber = dic[TwilioFromNumber].Value,
            }, phoneNumberClaim.Value, string.Format(dic[TwilioMessage].Value, code));
        }
Пример #20
0
        /// <inheritdoc />
        public async Task <Option> Update(ResourceOwner resourceOwner, CancellationToken cancellationToken)
        {
            await using var session = _sessionFactory();
            var user = await session.LoadAsync <ResourceOwner>(resourceOwner.Subject, cancellationToken)
                       .ConfigureAwait(false);

            if (user == null)
            {
                return(new ErrorDetails
                {
                    Title = ErrorCodes.InternalError,
                    Detail = SharedStrings.TheRoDoesntExist,
                    Status = HttpStatusCode.InternalServerError
                });
            }

            user.IsLocalAccount          = resourceOwner.IsLocalAccount;
            user.ExternalLogins          = resourceOwner.ExternalLogins;
            user.TwoFactorAuthentication = resourceOwner.TwoFactorAuthentication;
            user.UpdateDateTime          = DateTimeOffset.UtcNow;
            user.Claims = resourceOwner.Claims;
            session.Update(resourceOwner);
            await session.SaveChangesAsync(cancellationToken).ConfigureAwait(false);

            return(new Option.Success());
        }
Пример #21
0
        public async Task When_Resource_Owner_Credentials_Are_Correct_Then_Event_Is_Logged_And_Claims_Are_Returned()
        {
            // ARRANGE
            const string subject = "subject";

            InitializeFakeObjects();
            var localAuthenticationParameter = new LocalAuthenticationParameter();
            var authorizationParameter       = new AuthorizationParameter();
            var resourceOwner = new ResourceOwner
            {
                Id = subject
            };

            _authenticateResourceOwnerServiceStub.Setup(r => r.AuthenticateResourceOwnerAsync(It.IsAny <string>(), It.IsAny <string>())).Returns(Task.FromResult(resourceOwner));

            // ACT
            var result = await _localUserAuthenticationAction.Execute(localAuthenticationParameter,
                                                                      authorizationParameter,
                                                                      null);

            // Specify the resource owner authentication date
            Assert.NotNull(result);
            Assert.NotNull(result.Claims);
            Assert.True(result.Claims.Any(r => r.Type == ClaimTypes.AuthenticationInstant ||
                                          r.Type == Jwt.Constants.StandardResourceOwnerClaimNames.Subject));
        }
        public async Task <bool> Execute(ResourceOwner parameter)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }

            if (string.IsNullOrWhiteSpace(parameter.Id))
            {
                throw new ArgumentNullException(nameof(parameter.Id));
            }

            if (await _resourceOwnerRepository.GetAsync(parameter.Id) == null)
            {
                throw new IdentityServerManagerException(
                          ErrorCodes.InvalidParameterCode,
                          string.Format(ErrorDescriptions.TheResourceOwnerDoesntExist, parameter.Id));
            }

            if (parameter.Claims != null)
            {
                Claim updatedClaim;
                if (((updatedClaim = parameter.Claims.FirstOrDefault(c => c.Type == SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.UpdatedAt)) != null))
                {
                    parameter.Claims.Remove(updatedClaim);
                }

                parameter.Claims.Add(new Claim(SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.UpdatedAt, DateTime.UtcNow.ToString()));
            }

            return(await _resourceOwnerRepository.UpdateAsync(parameter));
        }
        public async Task <bool> UpdateAsync(ResourceOwner resourceOwner)
        {
            using (var transaction = await _context.Database.BeginTransactionAsync().ConfigureAwait(false))
            {
                try
                {
                    var user   = resourceOwner.ToEntity();
                    var record = await _context.Users
                                 .Include(r => r.Claims)
                                 .FirstOrDefaultAsync(r => r.Subject == user.Subject)
                                 .ConfigureAwait(false);

                    if (record == null)
                    {
                        return(false);
                    }

                    record.Username       = user.Username;
                    record.Password       = user.Password;
                    record.IsLocalAccount = resourceOwner.IsLocalAccount;
                    record.Claims         = user.Claims;
                    await _context.SaveChangesAsync().ConfigureAwait(false);

                    transaction.Commit();
                    return(true);
                }
                catch (Exception ex)
                {
                    _managerEventSource.Failure(ex);
                    transaction.Rollback();
                    return(false);
                }
            }
        }
Пример #24
0
        public StaticResourceDto(ResourceOwner resourceOwner, string name, string displayName, string state, string path = null, bool isPublic = false,
                                 int?order = null)
        {
            ResourceOwner = resourceOwner;
            Name          = name;
            DisplayName   = displayName;
            State         = state;
            Path          = path;
            IsPublic      = isPublic;
            Order         = order;

            if (string.IsNullOrWhiteSpace(path))
            {
                var p     = string.Empty;
                var split = state.Split('.');
                foreach (var s in split)
                {
                    if (s.ToLower() == "root")
                    {
                        continue;
                    }

                    p = p + $"/{s}";
                }

                Path = p;
            }
        }
Пример #25
0
        public async Task <ExternalOpenIdAuthenticationResult> Execute(
            List <Claim> claims,
            AuthorizationParameter authorizationParameter,
            string code)
        {
            // 1. Check parameters.
            if (claims == null || !claims.Any())
            {
                throw new ArgumentNullException(nameof(claims));
            }

            if (authorizationParameter == null)
            {
                throw new ArgumentNullException(nameof(authorizationParameter));
            }

            if (string.IsNullOrWhiteSpace(code))
            {
                throw new ArgumentNullException(nameof(code));
            }

            // 2. Subject cannot be extracted.
            var subject = claims.GetSubject();

            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new IdentityServerException(ErrorCodes.UnhandledExceptionCode,
                                                  ErrorDescriptions.NoSubjectCanBeExtracted);
            }

            // 3. Create the resource owner if needed.
            var resourceOwner = await _authenticateResourceOwnerService.AuthenticateResourceOwnerAsync(subject);

            if (resourceOwner == null)
            {
                var standardClaims = await _claimRepository.GetAllAsync();

                resourceOwner = new ResourceOwner
                {
                    Id                      = subject,
                    IsLocalAccount          = false,
                    TwoFactorAuthentication = TwoFactorAuthentications.NONE,
                    Claims                  = claims.Where(c => standardClaims.Any(sc => sc == c.Type)).ToList()
                };
                if (!resourceOwner.Claims.Any(c => c.Type == Jwt.Constants.StandardResourceOwnerClaimNames.Subject))
                {
                    resourceOwner.Claims.Add(new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.Subject, subject));
                }

                await _resourceOwnerRepository.InsertAsync(resourceOwner);
            }
            return(new ExternalOpenIdAuthenticationResult
            {
                ActionResult = await _authenticateHelper.ProcessRedirection(authorizationParameter,
                                                                            code,
                                                                            "subject",
                                                                            claims),
                Claims = resourceOwner.Claims
            });
        }
Пример #26
0
        public async Task <ActionResult> LocalLoginOpenId(OpenidLocalAuthenticationViewModel viewModel)
        {
            if (viewModel == null)
            {
                throw new ArgumentNullException(nameof(viewModel));
            }

            if (string.IsNullOrWhiteSpace(viewModel.Code))
            {
                throw new ArgumentNullException(nameof(viewModel.Code));
            }

            await SetUser().ConfigureAwait(false);

            var acrUser = await _authenticationService.GetAuthenticatedUser(this, Host.Constants.CookieNames.AcrCookieName).ConfigureAwait(false);

            var acrUserSubject = (acrUser == null || acrUser.IsAuthenticated() == false) ? null : acrUser.Claims.First(c => c.Type == Core.Jwt.Constants.StandardResourceOwnerClaimNames.Subject).Value;
            var uiLocales      = DefaultLanguage;
            // 1. Decrypt the request
            var request = _dataProtector.Unprotect <AuthorizationRequest>(viewModel.Code);

            // 2. Retrieve the default language
            uiLocales = string.IsNullOrWhiteSpace(request.UiLocales) ? DefaultLanguage : request.UiLocales;
            if (ModelState.IsValid)
            {
                ResourceOwner resourceOwner = null;
                try
                {
                    resourceOwner = await _smsAuthenticationOperation.Execute(viewModel.PhoneNumber, acrUserSubject).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    _simpleIdentityServerEventSource.Failure(ex.Message);
                    ModelState.AddModelError("message_error", ex.Message);
                }

                if (resourceOwner != null)
                {
                    var claims = resourceOwner.Claims;
                    claims.Add(new Claim(ClaimTypes.AuthenticationInstant, DateTimeOffset.UtcNow.ConvertToUnixTimestamp().ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Integer));
                    await SetPasswordLessCookie(claims).ConfigureAwait(false);

                    try
                    {
                        return(RedirectToAction("ConfirmCode", new { code = viewModel.Code }));
                    }
                    catch (Exception ex)
                    {
                        _simpleIdentityServerEventSource.Failure(ex.Message);
                        ModelState.AddModelError("message_error", "TWILIO account is not valid");
                    }
                }
            }

            await TranslateView(uiLocales).ConfigureAwait(false);
            await SetIdProviders(viewModel).ConfigureAwait(false);

            return(View("OpenId", viewModel));
        }
Пример #27
0
        public async Task When_No_Consent_Has_Been_Given_And_ResponseMode_Is_No_Correct_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            const string subject = "subject";
            const string state   = "state";
            var          authorizationParameter = new AuthorizationParameter
            {
                Claims       = null,
                Scope        = "profile",
                ResponseMode = ResponseMode.None,
                State        = state
            };
            var claims = new List <Claim>
            {
                new Claim(Constants.StandardResourceOwnerClaimNames.Subject, subject)
            };
            var client = new Client
            {
                ClientId = "clientId"
            };
            var resourceOwner = new ResourceOwner
            {
                Id = subject
            };
            var actionResult = new ActionResult
            {
                Type = TypeActionResult.RedirectToCallBackUrl,
                RedirectInstruction = new RedirectInstruction()
            };
            ICollection <string> scopeNames = new List <string>();
            ICollection <Scope>  scopes     = new List <Scope>();

            _consentHelperFake.Setup(c => c.GetConfirmedConsentsAsync(It.IsAny <string>(),
                                                                      It.IsAny <AuthorizationParameter>()))
            .Returns(Task.FromResult((SimpleIdServer.Core.Common.Models.Consent)null));
            _clientRepositoryFake.Setup(c => c.GetClientByIdAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(client));
            _parameterParserHelperFake.Setup(p => p.ParseScopes(It.IsAny <string>()))
            .Returns(scopeNames);
            _resourceOwnerRepositoryFake.Setup(r => r.GetAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(resourceOwner));
            _actionResultFactoryFake.Setup(a => a.CreateAnEmptyActionResultWithRedirectionToCallBackUrl())
            .Returns(actionResult);
            _scopeRepositoryFake.Setup(s => s.SearchByNamesAsync(It.IsAny <IEnumerable <string> >()))
            .Returns(Task.FromResult(scopes));
            _parameterParserHelperFake.Setup(p => p.ParseResponseTypes(It.IsAny <string>()))
            .Returns(new List <ResponseType> {
                ResponseType.id_token, ResponseType.id_token
            });

            // ACT & ASSERT
            var exception = await Assert.ThrowsAsync <IdentityServerExceptionWithState>(() => _confirmConsentAction.Execute(authorizationParameter, subject, null));

            Assert.NotNull(exception);
            Assert.True(exception.Code == ErrorCodes.InvalidRequestCode);
            Assert.True(exception.Message == ErrorDescriptions.TheAuthorizationFlowIsNotSupported);
            Assert.True(exception.State == state);
        }
Пример #28
0
        }                                                                        //injected by IOC

        public List <Approval> GetApprovalByResourceOwner(ResourceOwner ResourceOwner)
        {
            if (ResourceOwner == null)
            {
                throw  new ArgumentNullException("ResourceOwner");
            }
            return(GetApprovalByResourceOwner(ResourceOwner.id));
        }
Пример #29
0
 public bool CreateOrUpdate(ResourceOwner Owner)
 {
     if (Update(Owner))
     {
         return(true);
     }
     return(Create(Owner));
 }
Пример #30
0
        /// <inheritdoc />
        public async Task <bool> Insert(ResourceOwner resourceOwner, CancellationToken cancellationToken = default)
        {
            await using var session = _sessionFactory();
            resourceOwner.Password  = resourceOwner.Password?.ToSha256Hash(_salt);
            session.Store(resourceOwner);
            await session.SaveChangesAsync(cancellationToken).ConfigureAwait(false);

            return(true);
        }
        public async Task <bool> Execute(AddUserParameter addUserParameter)
        {
            if (addUserParameter == null)
            {
                throw new ArgumentNullException(nameof(addUserParameter));
            }

            if (string.IsNullOrEmpty(addUserParameter.Login))
            {
                throw new ArgumentNullException(nameof(addUserParameter.Login));
            }

            if (string.IsNullOrWhiteSpace(addUserParameter.Password))
            {
                throw new ArgumentNullException(nameof(addUserParameter.Password));
            }

            if (await _authenticateResourceOwnerService.AuthenticateResourceOwnerAsync(addUserParameter.Login,
                                                                                       addUserParameter.Password) != null)
            {
                throw new IdentityServerException(
                          Errors.ErrorCodes.UnhandledExceptionCode,
                          Errors.ErrorDescriptions.TheRoWithCredentialsAlreadyExists);
            }

            var newClaims = new List <Claim>
            {
                new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.UpdatedAt, DateTime.UtcNow.ToString()),
                new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.Subject, addUserParameter.Login)
            };
            var newResourceOwner = new ResourceOwner
            {
                Id     = addUserParameter.Login,
                Claims = newClaims,
                TwoFactorAuthentication = TwoFactorAuthentications.NONE,
                IsLocalAccount          = true,
                Password = _authenticateResourceOwnerService.GetHashedPassword(addUserParameter.Password)
            };
            var claims = (await _claimRepository.GetAllAsync()).Select(c => c.Code);

            if (addUserParameter.Claims != null)
            {
                foreach (var claim in addUserParameter.Claims.Where(c => claims.Contains(c.Type)))
                {
                    newResourceOwner.Claims.Add(claim);
                }
            }

            if (!newResourceOwner.Claims.Any(c => c.Type == Jwt.Constants.StandardResourceOwnerClaimNames.Subject))
            {
                newResourceOwner.Claims.Add(new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.Subject, addUserParameter.Login));
            }

            await _resourceOwnerRepository.InsertAsync(newResourceOwner);

            return(true);
        }
Пример #32
0
        public void ResourceOwnerFromXElement()
        {
            var element       = new XElement("ResourceOwner", new XElement("name", "user1"), new XElement("guid", "99c33d15-5fc1-417c-ae4e-0df51621c874"));
            var resourceOwner = ResourceOwner.FromXElement(element);

            resourceOwner.Should().NotBeNull();
            resourceOwner.Name.Should().Be("user1");
            resourceOwner.Guid.ToString().Should().Be("99c33d15-5fc1-417c-ae4e-0df51621c874");
        }
        public async Task <IActionResult> LocalLogin(LocalAuthenticationViewModel localAuthenticationViewModel)
        {
            var authenticatedUser = await SetUser();

            if (authenticatedUser != null &&
                authenticatedUser.Identity != null &&
                authenticatedUser.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "User", new { area = "UserManagement" }));
            }

            if (localAuthenticationViewModel == null)
            {
                throw new ArgumentNullException(nameof(localAuthenticationViewModel));
            }

            if (ModelState.IsValid)
            {
                ResourceOwner resourceOwner = null;
                try
                {
                    resourceOwner = await _smsAuthenticationOperation.Execute(localAuthenticationViewModel.PhoneNumber);
                }
                catch (Exception ex)
                {
                    _simpleIdentityServerEventSource.Failure(ex.Message);
                    ModelState.AddModelError("message_error", ex.Message);
                }

                if (resourceOwner != null)
                {
                    var claims = resourceOwner.Claims;
                    claims.Add(new Claim(ClaimTypes.AuthenticationInstant,
                                         DateTimeOffset.UtcNow.ConvertToUnixTimestamp().ToString(CultureInfo.InvariantCulture),
                                         ClaimValueTypes.Integer));
                    await SetPasswordLessCookie(claims);

                    try
                    {
                        return(RedirectToAction("ConfirmCode"));
                    }
                    catch (Exception ex)
                    {
                        _simpleIdentityServerEventSource.Failure(ex.Message);
                        ModelState.AddModelError("message_error", "TWILIO account is not valid");
                    }
                }
            }

            var viewModel = new AuthorizeViewModel();

            await SetIdProviders(viewModel);
            await TranslateView(DefaultLanguage);

            return(View("Index", viewModel));
        }
Пример #34
0
        private static string GetAuthorizationLocation(ServerWithAuthorizationCode server, Uri redirectionUri, ResourceOwner resourceOwner)
        {
            var scopes = server.Scopes.Aggregate("", (current, scope) => current + (scope + " ")).Trim();

            return server.AuthorizationRequestUri + "?response_type=code&client_id=" +
                   server.ClientId +
                   "&state=" + server.Guid + "_" + resourceOwner.Guid +
                   "&scope=" + HttpUtility.UrlEncode(scopes) +
                   "&redirect_uri=" + HttpUtility.UrlEncode(redirectionUri.ToString());
        }
Пример #35
0
        public void ResourceOwnerToXElement()
        {
            var resourceOwner = new ResourceOwner("user1");
            var element = resourceOwner.ToXElement();

            element.Should().NotBeNull();
            element.Element("name").Should().NotBeNull();
            element.Element("name").Value.Should().Be("user1");
            element.Element("guid").Should().NotBeNull();
            element.Element("guid").Value.Should().Be(resourceOwner.Guid.ToString());
        }
Пример #36
0
        public void SetUp()
        {
            Tokens.CleanUpForTests();
            ResourceOwners.CleanUpForTests();
            ServersWithAuthorizationCode.CleanUpForTests();

            var authorizationRequestUri = new Uri("http://example.org/GetAccessAndRefreshTokenTest/Authorization");
            var accessTokenUri = new Uri("http://example.org/GetAccessAndRefreshTokenTest/Access");
            var redirectionUri = new Uri("http://example.org/GetAccessAndRefreshTokenTest/redirectionUri");
            _server = ServersWithAuthorizationCode.Add("123456789", "testsecret", authorizationRequestUri,accessTokenUri, redirectionUri);
            _resourceOwner = ResourceOwners.Add("Test");
            _token = Tokens.GetToken(_server, _resourceOwner);
            _token.RedirectUri = _server.RedirectionUri;
            _token.AuthorizationCode = "Aplx10BeZQQYbYS6WxSbIA";
        }
 public ResourceUsed(ResourceOwner o, int cost)
 {
     this.owner = o;
     this.cost = cost;
     this.usedDoubleResource = false;
 }
Пример #38
0
 private static void SetRedirectUriInToken(ServerWithAuthorizationCode server, ResourceOwner resourceOwner, Uri redirectionUri)
 {
     var token = Tokens.GetToken(server, resourceOwner);
     token.RedirectUri = redirectionUri;
 }
Пример #39
0
 public static void RedirectToAuthorization(this IWebOperationContext context, ServerWithAuthorizationCode server, ResourceOwner resourceOwner)
 {
     context.RedirectToAuthorization(server, server.RedirectionUri, resourceOwner);
 }
Пример #40
0
        public void TokenToXElement()
        {
            var server1 = new ServerWithAuthorizationCode("test", "testsecret",
                                                          new Uri("http://example.org/foo"),
                                                          new Uri("http://example.org/access"),
                                                          new Uri("http://example.org/test2"));
            var resourceOwner1 = new ResourceOwner("testmann1");

            var token = new Token(server1, resourceOwner1);
            token.AuthorizationCode = "auth1";
            token.AccessToken = "access1";
            token.RefreshToken = "refresht";
            token.RedirectUri = new Uri("http://example.org/redirect");
            
            var element1 = token.ToXElement();

            element1.Name.ToString().Should().Be("Token");
            element1.Element("Server").Value.Should().Be(server1.Guid.ToString());
            element1.Element("ResourceOwner").Value.Should().Be(resourceOwner1.Name);
            element1.Element("AuthorizationCode").Value.Should().Be("auth1");
            element1.Element("AccessToken").Value.Should().Be("access1");
            element1.Element("RefreshToken").Value.Should().Be("refresht");
            element1.Element("RedirectUri").Value.Should().Be("http://example.org/redirect");
            

        }