AddIdentity() public method

Adds a single ClaimsIdentity to an internal list.
if 'identity' is null.
public AddIdentity ( ClaimsIdentity identity ) : void
identity ClaimsIdentity the add.
return void
        public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
        {
            var id = new ClaimsIdentity("ClaimsAuthenticationManager");
            id.AddClaim(new Claim(ClaimTypes.Role, "RoleFromClaimsAuthManager", null, "ClaimsAuthenticationManagerMock"));
            incomingPrincipal.AddIdentity(id);

            return incomingPrincipal;
        }
Exemplo n.º 2
0
        /// <summary>
        /// Add an additional ClaimsIdentity to the ClaimsPrincipal in the "server.User" environment key
        /// </summary>
        /// <param name="identity"></param>
        public void AddUserIdentity(IIdentity identity)
        {
            if (identity == null)
            {
                throw new ArgumentNullException("identity");
            }
            var newClaimsPrincipal = new ClaimsPrincipal(identity);

            IPrincipal existingPrincipal = _context.Request.User;
            if (existingPrincipal != null)
            {
                var existingClaimsPrincipal = existingPrincipal as ClaimsPrincipal;
                if (existingClaimsPrincipal == null)
                {
                    IIdentity existingIdentity = existingPrincipal.Identity;
                    if (existingIdentity.IsAuthenticated)
                    {
                        newClaimsPrincipal.AddIdentity(existingIdentity as ClaimsIdentity ?? new ClaimsIdentity(existingIdentity));
                    }
                }
                else
                {
                    foreach (var existingClaimsIdentity in existingClaimsPrincipal.Identities)
                    {
                        if (existingClaimsIdentity.IsAuthenticated)
                        {
                            newClaimsPrincipal.AddIdentity(existingClaimsIdentity);
                        }
                    }
                }
            }
            _context.Request.User = newClaimsPrincipal;
        }
Exemplo n.º 3
0
        public async Task handler_should_throw_exception_with_existing_device()
        {
            var command = new CreateDevice
            {
                Id       = "device1",
                Enabled  = true,
                Password = "******"
            };

            var userName    = "******";
            var httpContext = new DefaultHttpContext();
            var user        = new System.Security.Claims.ClaimsPrincipal();

            user.AddIdentity(new System.Security.Claims.ClaimsIdentity(new List <Claim> {
                new Claim(ClaimTypes.Name, userName)
            }));
            httpContext.User = user;
            _httpContextAccessor.HttpContext.Returns(httpContext);

            var account = new Account()
            {
                Id = Guid.NewGuid()
            };

            _accountRepository.GetByUserName(userName).Returns(account);

            _deviceRepository.Get(command.Id).Returns(new Device());

            Should.Throw <DeviceAlreadyExistsException>(() => _handler.Handle(command, new System.Threading.CancellationToken()));
        }
        public ActionResult GetAccessToken(string code)
        {
            var query = new Dictionary<string, string>();
            query.Add("client_id", Constants.GITHUB_CLIENT_ID);
            query.Add("client_secret", Constants.GITHUB_CLIENT_SEC);
            query.Add("code", code);
            query.Add("state", Constants.GITHUB_OAUTH_STATE);

            // send request
            JObject resp = Utility.MakeJsonHttpRequest(Constants.GITHUB_AK_URL, query);
            string accessToken = (string)resp["access_token"];

            // call sts and return
            // build cliam
            var claim = new ClaimsPrincipal();
            var id = new ClaimsIdentity();
            id.AddClaim(new Claim(Constants.CLAIM_TYPE_GITHUB_AK, accessToken));
            claim.AddIdentity(id);

            // send claim
            var sigingCredentials = new X509SigningCredentials(Utility.GetCertificate(Constants.CERTIFICATE_NAME));

            var config = new SecurityTokenServiceConfiguration(Constants.ISSUER_NAME, sigingCredentials);
            var sts = new CustomSecurityTokenService(config);

            var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(Request.Url);
            var responesMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, claim, sts);

            var formData = responesMessage.WriteFormPost();
            return new ContentResult() { Content = formData, ContentType = "text/html" };
        }
        public async Task Invoke(HttpContext context)
        {
            var headers         = context.Request.Headers;
            var claimsPrincipal = new System.Security.Claims.ClaimsPrincipal();

            if (!headers.ContainsKey("x-api-key"))
            {
                context.User = claimsPrincipal;
                context.Response.StatusCode = 400;
            }
            else
            {
                if (headers["x-api-key"] == apiKey.key)
                {
                    var claim    = new Claim(ClaimTypes.Role, "User");
                    var identity = new ClaimsIdentity();
                    identity.AddClaim(claim);
                    claimsPrincipal.AddIdentity(identity);
                    context.User = claimsPrincipal;

                    await _next(context);

                    return;
                }
                else if (headers["x-api-key"] == apiKey.adminKey)
                {
                    var claim    = new Claim(ClaimTypes.Role, "Admin");
                    var identity = new ClaimsIdentity();
                    identity.AddClaim(claim);
                    claimsPrincipal.AddIdentity(identity);
                    context.User = claimsPrincipal;

                    await _next(context);

                    return;
                }
                else
                {
                    context.Response.StatusCode = 403;
                }
            }
            //var watch = new Stopwatch();
            //watch.Start();
            //await _next(context);
            //context.Response.Headers.Add("X-Processing-Time-Milliseconds",
            //new[] { watch.ElapsedMilliseconds.ToString() });
        }
Exemplo n.º 6
0
        public void AddingPreservesNewIdentitiesAndDropsEmpty()
        {
            var context = new DefaultHttpContext();
            var existingPrincipal = new ClaimsPrincipal(new ClaimsIdentity());
            var identityNoAuthTypeWithClaim = new ClaimsIdentity();
            identityNoAuthTypeWithClaim.AddClaim(new Claim("identityNoAuthTypeWithClaim", "yes"));
            existingPrincipal.AddIdentity(identityNoAuthTypeWithClaim);
            var identityEmptyWithAuthType = new ClaimsIdentity("empty");
            existingPrincipal.AddIdentity(identityEmptyWithAuthType);
            context.User = existingPrincipal;

            context.User.Identity.IsAuthenticated.ShouldBe(false);

            var newPrincipal = new ClaimsPrincipal();
            var newEmptyIdentity = new ClaimsIdentity();
            var identityTwo = new ClaimsIdentity("yep");
            newPrincipal.AddIdentity(newEmptyIdentity);
            newPrincipal.AddIdentity(identityTwo);

            SecurityHelper.AddUserPrincipal(context, newPrincipal);

            // Preserve newPrincipal order
            context.User.Identity.IsAuthenticated.ShouldBe(false);
            context.User.Identity.Name.ShouldBe(null);

            var principal = context.User;
            principal.Identities.Count().ShouldBe(4);
            principal.Identities.Skip(0).First().ShouldBe(newEmptyIdentity);
            principal.Identities.Skip(1).First().ShouldBe(identityTwo);
            principal.Identities.Skip(2).First().ShouldBe(identityNoAuthTypeWithClaim);
            principal.Identities.Skip(3).First().ShouldBe(identityEmptyWithAuthType);

            // This merge should drop newEmptyIdentity since its empty
            SecurityHelper.AddUserPrincipal(context, new GenericPrincipal(new GenericIdentity("Test3", "Gamma"), new string[0]));

            context.User.Identity.AuthenticationType.ShouldBe("Gamma");
            context.User.Identity.Name.ShouldBe("Test3");

            principal = context.User;
            principal.Identities.Count().ShouldBe(4);
            principal.Identities.Skip(0).First().Name.ShouldBe("Test3");
            principal.Identities.Skip(1).First().ShouldBe(identityTwo);
            principal.Identities.Skip(2).First().ShouldBe(identityNoAuthTypeWithClaim);
            principal.Identities.Skip(3).First().ShouldBe(identityEmptyWithAuthType);
        }
        public static void SetFakeUser(this Controller controller, string userId)
        {
            SetFakeHttpContextIfNotAlreadySet(controller);

            var claimsPrincipal = new ClaimsPrincipal();
            claimsPrincipal.AddIdentity(new ClaimsIdentity(new List<Claim> { new Claim(ClaimTypes.NameIdentifier, userId) }));

            Mock.Get(controller.HttpContext).SetupGet(httpContext => httpContext.User).Returns(claimsPrincipal);
        }
Exemplo n.º 8
0
        public async Task Invoke(HttpContext context)
        {
            var claimsPrincipal = new System.Security.Claims.ClaimsPrincipal();

            var headers = context.Request.Headers;

            if (!headers.ContainsKey("x-api-key"))
            {
                context.User = claimsPrincipal;
                context.Response.StatusCode = 400;
            }
            else
            {
                if (headers["x-api-key"] == _apiKey.key)
                {
                    var claim    = new Claim(ClaimTypes.Role, "User");
                    var identity = new ClaimsIdentity();
                    identity.AddClaim(claim);
                    claimsPrincipal.AddIdentity(identity);
                    context.User = claimsPrincipal;

                    await _next(context);

                    return;
                }
                else if (headers["x-api-key"] == _apiKey.adminKey)
                {
                    var claim    = new Claim(ClaimTypes.Role, "Admin");
                    var identity = new ClaimsIdentity();
                    identity.AddClaim(claim);
                    claimsPrincipal.AddIdentity(identity);
                    context.User = claimsPrincipal;

                    await _next(context);

                    return;
                }
                else
                {
                    context.User = claimsPrincipal;
                    context.Response.StatusCode = 403;
                }
            }
        }
Exemplo n.º 9
0
        public void AddingPreservesNewIdentitiesAndDropsEmpty()
        {
            var existingPrincipal = new ClaimsPrincipal(new ClaimsIdentity());
            var identityNoAuthTypeWithClaim = new ClaimsIdentity();
            identityNoAuthTypeWithClaim.AddClaim(new Claim("identityNoAuthTypeWithClaim", "yes"));
            existingPrincipal.AddIdentity(identityNoAuthTypeWithClaim);
            var identityEmptyWithAuthType = new ClaimsIdentity("empty");
            existingPrincipal.AddIdentity(identityEmptyWithAuthType);

            Assert.False(existingPrincipal.Identity.IsAuthenticated);

            var newPrincipal = new ClaimsPrincipal();
            var newEmptyIdentity = new ClaimsIdentity();
            var identityTwo = new ClaimsIdentity("yep");
            newPrincipal.AddIdentity(newEmptyIdentity);
            newPrincipal.AddIdentity(identityTwo);

            var user = SecurityHelper.MergeUserPrincipal(existingPrincipal, newPrincipal);

            // Preserve newPrincipal order
            Assert.False(user.Identity.IsAuthenticated);
            Assert.Null(user.Identity.Name);

            Assert.Equal(4, user.Identities.Count());
            Assert.Equal(newEmptyIdentity, user.Identities.Skip(0).First());
            Assert.Equal(identityTwo, user.Identities.Skip(1).First());
            Assert.Equal(identityNoAuthTypeWithClaim, user.Identities.Skip(2).First());
            Assert.Equal(identityEmptyWithAuthType, user.Identities.Skip(3).First());

            // This merge should drop newEmptyIdentity since its empty
            user = SecurityHelper.MergeUserPrincipal(user, new GenericPrincipal(new GenericIdentity("Test3", "Gamma"), new string[0]));

            Assert.Equal("Gamma", user.Identity.AuthenticationType);
            Assert.Equal("Test3", user.Identity.Name);

            Assert.Equal(4, user.Identities.Count());
            Assert.Equal("Test3", user.Identities.Skip(0).First().Name);
            Assert.Equal(identityTwo, user.Identities.Skip(1).First());
            Assert.Equal(identityNoAuthTypeWithClaim, user.Identities.Skip(2).First());
            Assert.Equal(identityEmptyWithAuthType, user.Identities.Skip(3).First());

        }
        public static void SetFakeUserAndUserType(this Controller controller, string userId, UserType userType)
        {
            SetFakeHttpContextIfNotAlreadySet(controller);

            var claimsPrincipal = new ClaimsPrincipal();
            claimsPrincipal.AddIdentity(new ClaimsIdentity(new List<Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, userId),
                new Claim(AllReady.Security.ClaimTypes.UserType, Enum.GetName(typeof (UserType), userType))
            }));

            Mock.Get(controller.HttpContext).SetupGet(httpContext => httpContext.User).Returns(claimsPrincipal);
        }
        public static ClaimsPrincipal ClaimsPrincipal(string userName = null)
        {
            var currentIdentity = Thread.CurrentPrincipal.Identity;

            var name = userName ?? currentIdentity.Name;

            var identity = new ClaimsIdentity();
            identity.AddClaim(new Claim("nameidentifier",name));

            var principal = new ClaimsPrincipal();
            principal.AddIdentity(identity);
            return principal;
        }
        public void OrgAdminsCanEditAllReadyTasks()
        {
            var claimsPrincipal = new ClaimsPrincipal();
            claimsPrincipal.AddIdentity(new ClaimsIdentity(new List<Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, "1"),
                new Claim(AllReady.Security.ClaimTypes.UserType, Enum.GetName(typeof (UserType), UserType.OrgAdmin))
            }));

            var sut = new DetermineIfATaskIsEditable();
            var result = sut.For(claimsPrincipal, null, null);

            Assert.True(result);
        }
Exemplo n.º 13
0
        public ClaimsPrincipal ValidateUser(string token)
        {
            try
            {
                //Claims don't deserialize :(
                //var jwttoken = JsonWebToken.DecodeToObject<JwtToken>(token, configProvider.GetAppSetting("securekey"));

                var decodedtoken = JsonWebToken.DecodeToObject(token, _configProvider.GetAppSetting("securekey")) as Dictionary<string, object>;
                if (decodedtoken == null)
                    return null;

                var jwttoken = new JwtToken()
                {
                    Audience = (string)decodedtoken["Audience"],
                    Issuer = (string)decodedtoken["Issuer"],
                    Expiry = DateTime.Parse(decodedtoken["Expiry"].ToString()),
                };

                if (decodedtoken.ContainsKey("Claims"))
                {
                    var claims = new List<Claim>();

                    for (int i = 0; i < ((ArrayList)decodedtoken["Claims"]).Count; i++)
                    {
                        var type = ((Dictionary<string, object>)((ArrayList)decodedtoken["Claims"])[i])["Type"].ToString();
                        var value = ((Dictionary<string, object>)((ArrayList)decodedtoken["Claims"])[i])["Value"].ToString();
                        claims.Add(new Claim(type, value));
                    }

                    jwttoken.Claims = claims;
                }

                if (jwttoken.Expiry < DateTime.UtcNow)
                {
                    return null;
                }

                //TODO Tidy on 3.8 Mono release
                var claimsPrincipal = new ClaimsPrincipal();
                var claimsIdentity = new ClaimsIdentity("Token");
                claimsIdentity.AddClaims(jwttoken.Claims);
                claimsPrincipal.AddIdentity(claimsIdentity);
                return claimsPrincipal;
            }
            catch (Exception)
            {
                return null;
            }
        }
Exemplo n.º 14
0
        public async Task InteropWithNewCookieContainsIdentity()
        {
            var user = new ClaimsPrincipal();
            var identity = new ClaimsIdentity("scheme");
            identity.AddClaim(new Claim(ClaimTypes.Name, "Alice"));
            user.AddIdentity(identity);

            var dataProtection = DataProtectionProvider.Create(new DirectoryInfo("..\\..\\artifacts"));
            var dataProtector = dataProtection.CreateProtector(
                "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", // full name of the ASP.NET Core type
                CookieAuthenticationDefaults.AuthenticationType, "v2");

            var builder = new WebHostBuilder()
                .Configure(app =>
                {
                    app.UseCookieAuthentication(new AspNetCore.Builder.CookieAuthenticationOptions
                    {
                        DataProtectionProvider = dataProtection
                    });
                    app.Run(context => context.Authentication.SignInAsync("Cookies", user));
                })
                .ConfigureServices(services => services.AddAuthentication());
            var newServer = new AspNetCore.TestHost.TestServer(builder);

            var cookie = await SendAndGetCookie(newServer, "http://example.com/login");

            var server = TestServer.Create(app =>
            {
                app.Properties["host.AppName"] = "Microsoft.Owin.Security.Tests";

                app.UseCookieAuthentication(new Owin.Security.Cookies.CookieAuthenticationOptions
                {
                    TicketDataFormat = new AspNetTicketDataFormat(new DataProtectorShim(dataProtector)),
                    CookieName = AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.CookiePrefix
                        + AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme,
                });

                app.Run(async context =>
                {
                    var result = await context.Authentication.AuthenticateAsync("Cookies");
                    Describe(context.Response, result);
                });
            });

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", cookie);

            Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));
        }
Exemplo n.º 15
0
        /// <summary>
        /// Add an additional ClaimsIdentity to the ClaimsPrincipal
        /// </summary>
        /// <param name="identity"></param>
        public static void AddUserIdentity([NotNull] HttpContext context, [NotNull] IIdentity identity)
        {
            var newClaimsPrincipal = new ClaimsPrincipal(identity);

            ClaimsPrincipal existingPrincipal = context.User;
            if (existingPrincipal != null)
            {
                foreach (var existingClaimsIdentity in existingPrincipal.Identities)
                {
                    if (existingClaimsIdentity.IsAuthenticated)
                    {
                        newClaimsPrincipal.AddIdentity(existingClaimsIdentity);
                    }
                }
            }
            context.User = newClaimsPrincipal;
        }
        public void AllReadyTaskThatHasInstanceOfEventAndEventHasInstanceOfCampaignAndCampaignHasInstanceOfOrganizerAndOrganizerIdEqualsUserIdIsEditable()
        {
            const string userId = "1";

            var claimsPrincipal = new ClaimsPrincipal();
            claimsPrincipal.AddIdentity(new ClaimsIdentity(new List<Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, "1"),
                new Claim(AllReady.Security.ClaimTypes.UserType, Enum.GetName(typeof (UserType), UserType.BasicUser))
            }));

            var allReadyTask = new AllReadyTask { Event = new Event { Campaign = new Campaign { Organizer = new ApplicationUser { Id = userId }}}};

            var sut = new DetermineIfATaskIsEditable();
            var result = sut.For(claimsPrincipal, allReadyTask, null);

            Assert.True(result);
        }
Exemplo n.º 17
0
        public void Ctor_IPrincipal()
        {
            var baseId = new ClaimsIdentity(
                           new List<Claim> { new Claim("claim_type", "claim_value") },
                           "");
            var basePrincipal = new ClaimsPrincipal();
            basePrincipal.AddIdentity(baseId);

            var cp = new ClaimsPrincipal(basePrincipal);

            Assert.NotNull(cp.Identities);
            Assert.Equal(1, cp.Identities.Count());

            Assert.Same(baseId, cp.Identities.First());

            Assert.Same(baseId, cp.Identity);

            Assert.NotNull(cp.Claims);
            Assert.Equal(1, cp.Claims.Count());
            Assert.True(cp.Claims.Any(claim => claim.Type == "claim_type" && claim.Value == "claim_value"), "#7");
        }
Exemplo n.º 18
0
        public async Task handler_should_create_device_with_correct_data()
        {
            var command = new CreateDevice
            {
                Id       = "device1",
                Enabled  = true,
                Password = "******"
            };

            var userName    = "******";
            var httpContext = new DefaultHttpContext();
            var user        = new System.Security.Claims.ClaimsPrincipal();

            user.AddIdentity(new System.Security.Claims.ClaimsIdentity(new List <Claim> {
                new Claim(ClaimTypes.Name, userName)
            }));
            httpContext.User = user;
            _httpContextAccessor.HttpContext.Returns(httpContext);

            var account = new Account()
            {
                Id = Guid.NewGuid()
            };

            _accountRepository.GetByUserName(userName).Returns(account);

            _deviceRepository.Get(command.Id).Returns((Device)null);

            await _handler.Handle(command, new System.Threading.CancellationToken());

            await _deviceRepository.Received().Create(Arg.Is <Device>(d =>
                                                                      d.Id == command.Id &&
                                                                      d.Enabled == command.Enabled));

            await _accountDeviceRepository.Received().Create(Arg.Is <AccountDevice>(ad =>
                                                                                    ad.DeviceId == command.Id &&
                                                                                    ad.AccountId == account.Id));

            await _hiveMqCredentialsService.Received().AddCredentials(command.Id, command.Password);
        }
        public async Task handler_should_return_device_with_correct_data()
        {
            var command = new GetDevice
            {
                Id = "device1",
            };

            var userName    = "******";
            var httpContext = new DefaultHttpContext();
            var user        = new System.Security.Claims.ClaimsPrincipal();

            user.AddIdentity(new System.Security.Claims.ClaimsIdentity(new List <Claim> {
                new Claim(ClaimTypes.Name, userName)
            }));
            httpContext.User = user;
            _httpContextAccessor.HttpContext.Returns(httpContext);

            var account = new Account()
            {
                Id = Guid.NewGuid()
            };

            _accountRepository.GetByUserName(userName).Returns(account);

            var device = new Device {
                Id = command.Id
            };

            var accountDevice = new AccountDevice {
                AccountId = account.Id, DeviceId = device.Id
            };

            _accountDeviceRepository.Get((account.Id, device.Id)).Returns(accountDevice);

            _deviceRepository.Get(command.Id).Returns(device);

            var deviceDto = await _handler.Handle(command, new System.Threading.CancellationToken());

            deviceDto.Id.ShouldBe(device.Id);
        }
Exemplo n.º 20
0
        /// <inheritdoc />
        public virtual async Task OnAuthorizationAsync([NotNull] AuthorizationContext context)
        {
            // Build a ClaimsPrincipal with the Policy's required authentication types
            if (Policy.ActiveAuthenticationSchemes != null && Policy.ActiveAuthenticationSchemes.Any())
            {
                var newPrincipal = new ClaimsPrincipal();
                foreach (var scheme in Policy.ActiveAuthenticationSchemes)
                {
                    var result = (await context.HttpContext.Authentication.AuthenticateAsync(scheme))?.Principal;
                    if (result != null)
                    {
                        newPrincipal.AddIdentities(result.Identities);
                    }
                }
                // If all schemes failed authentication, provide a default identity anyways
                if (newPrincipal.Identity == null)
                {
                    newPrincipal.AddIdentity(new ClaimsIdentity());
                }
                context.HttpContext.User = newPrincipal;
            }

            // Allow Anonymous skips all authorization
            if (context.Filters.Any(item => item is IAllowAnonymous))
            {
                return;
            }

            var httpContext = context.HttpContext;
            var authService = httpContext.RequestServices.GetRequiredService<IAuthorizationService>();

            // Note: Default Anonymous User is new ClaimsPrincipal(new ClaimsIdentity())
            if (httpContext.User == null ||
                !httpContext.User.Identities.Any(i => i.IsAuthenticated) ||
                !await authService.AuthorizeAsync(httpContext.User, context, Policy))
            {
                context.Result = new ChallengeResult(Policy.ActiveAuthenticationSchemes.ToArray());
            }
        }
Exemplo n.º 21
0
        public void InteropSerializerCanReadNewTicket()
        {
            var user = new ClaimsPrincipal();
            var identity = new ClaimsIdentity("scheme");
            identity.AddClaim(new Claim("Test", "Value"));
            user.AddIdentity(identity);

            var expires = DateTime.Today;
            var issued = new DateTime(1979, 11, 11);
            var properties = new Http.Authentication.AuthenticationProperties();
            properties.IsPersistent = true;
            properties.RedirectUri = "/redirect";
            properties.Items["key"] = "value";
            properties.ExpiresUtc = expires;
            properties.IssuedUtc = issued;

            var newTicket = new AuthenticationTicket(user, properties, "scheme");
            var newSerializer = new TicketSerializer();

            var bytes = newSerializer.Serialize(newTicket);

            var interopSerializer = new AspNetTicketSerializer();
            var interopTicket = interopSerializer.Deserialize(bytes);

            Assert.NotNull(interopTicket);
            var newIdentity = interopTicket.Identity;
            Assert.NotNull(newIdentity);
            Assert.Equal("scheme", newIdentity.AuthenticationType);
            Assert.True(newIdentity.HasClaim(c => c.Type == "Test" && c.Value == "Value"));
            Assert.NotNull(interopTicket.Properties);
            Assert.True(interopTicket.Properties.IsPersistent);
            Assert.Equal("/redirect", interopTicket.Properties.RedirectUri);
            Assert.Equal("value", interopTicket.Properties.Dictionary["key"]);
            Assert.Equal(expires, interopTicket.Properties.ExpiresUtc);
            Assert.Equal(issued, interopTicket.Properties.IssuedUtc);
        }
        public void Should_Override_User_In_Owin_Environment()
        {

            //Given
            var fakeTokenValidator = A.Fake<ITokenValidator>();

            var secureuser = new ClaimsPrincipal();           
            var claimsIdentity = new ClaimsIdentity("Token");
            claimsIdentity.AddClaim(new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "DumbUser"));
            secureuser.AddIdentity(claimsIdentity);

            A.CallTo(() => fakeTokenValidator.ValidateUser(A<string>.Ignored))
                .Returns(secureuser);

            var owinhttps = GetStatelessAuth(GetNextFunc(), tokenValidator: fakeTokenValidator);

            //TODO Tidy on 3.8 Mono release
            var overriddenUser = new ClaimsPrincipal();
            var overriddenIdentity = new ClaimsIdentity("Token");
            overriddenIdentity.AddClaim(new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "Administrator"));
            overriddenUser.AddIdentity(overriddenIdentity);

            var environment = new Dictionary<string, object>
            {
                { "owin.RequestHeaders", new Dictionary<string, string[]>() { { "Authorization", new[] { "mysecuretoken" } } } },
                { "owin.RequestPath", "/" },
                { "owin.RequestMethod", "GET" },
                { ServerUser, overriddenUser }
            };

            //When
            var task = owinhttps.Invoke(environment);

            //Then
            var user = environment[ServerUser] as ClaimsPrincipal;

            //TODO Tidy on 3.8 Mono release
            Assert.True(user.HasClaim(x => x.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" && x.Value == "DumbUser"));
        }
Exemplo n.º 23
0
        private AuthorizationContext GetAuthorizationContext(Action<ServiceCollection> registerServices, bool anonymous = false)
        {
            var validUser = new ClaimsPrincipal(
                new ClaimsIdentity(
                    new Claim[] {
                        new Claim("Permission", "CanViewPage"),
                        new Claim(ClaimTypes.Role, "Administrator"),
                        new Claim(ClaimTypes.Role, "User"),
                        new Claim(ClaimTypes.NameIdentifier, "John")},
                        "Basic"));

            validUser.AddIdentity(
                new ClaimsIdentity(
                    new Claim[] {
                        new Claim("Permission", "CupBearer"),
                        new Claim(ClaimTypes.Role, "Token"),
                        new Claim(ClaimTypes.NameIdentifier, "John Bear")},
                        "Bearer"));

            // ServiceProvider
            var serviceCollection = new ServiceCollection();
            if (registerServices != null)
            {
                registerServices(serviceCollection);
            }

            var serviceProvider = serviceCollection.BuildServiceProvider();

            // HttpContext
            var httpContext = new Mock<HttpContext>();
            httpContext.SetupProperty(c => c.User);
            if (!anonymous)
            {
                httpContext.Object.User = validUser;
            }
            httpContext.SetupGet(c => c.RequestServices).Returns(serviceProvider);

            // AuthorizationContext
            var actionContext = new ActionContext(
                httpContext: httpContext.Object,
                routeData: new RouteData(),
                actionDescriptor: null
                );

            var authorizationContext = new AuthorizationContext(
                actionContext,
                Enumerable.Empty<IFilter>().ToList()
            );

            return authorizationContext;
        }
Exemplo n.º 24
0
        public async Task InteropWithNewCookieContainsIdentity()
        {
            var user = new ClaimsPrincipal();
            var identity = new ClaimsIdentity("scheme");
            identity.AddClaim(new Claim(ClaimTypes.Name, "Alice"));
            user.AddIdentity(identity);

            var dataProtection = new DataProtection.DataProtectionProvider(new DirectoryInfo("..\\..\\artifacts"));
            var newServer = TestHost.TestServer.Create(app =>
            {
                app.UseCookieAuthentication(options => options.DataProtectionProvider = dataProtection);
                app.Run(context => context.Authentication.SignInAsync("Cookies", user));
            }, services => services.AddAuthentication());

            var cookie = await SendAndGetCookie(newServer, "http://example.com/login");

            var server = TestServer.Create(app =>
            {
                app.Properties["host.AppName"] = "Microsoft.Owin.Security.Tests";
                app.UseCookieAuthentication(new CookieAuthenticationOptions(), dataProtection);
                app.Run(async context =>
                {
                    var result = await context.Authentication.AuthenticateAsync("Cookies");
                    Describe(context.Response, result);
                });
            });

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", cookie);

            Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));
        }
Exemplo n.º 25
0
		public void IPrincipalCtorClaimsPrincipalWithMultipleIdentitiesWorks ()
		{
			var baseId1 = new ClaimsIdentity ("baseId1");
			var baseId2 = new GenericIdentity ("generic_name", "baseId2");
			var baseId3 = WindowsIdentity.GetAnonymous ();

			var basePrincipal = new ClaimsPrincipal (baseId1);
			basePrincipal.AddIdentity (baseId2);
			basePrincipal.AddIdentity (baseId3);

			var p = new ClaimsPrincipal (basePrincipal);
			Assert.IsNotNull (p.Identities, "#1");
			Assert.AreEqual (3, p.Identities.Count (), "#2");

			Assert.IsNotNull (p.Claims, "#3");
			Assert.AreEqual (1, p.Claims.Count (), "#4");

			// The Identity property favours WindowsIdentity
			Assert.AreEqual (baseId3, p.Identity, "#5");

			Assert.IsTrue (p.Claims.Any (claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "generic_name"), "#6");

			Assert.AreEqual (baseId2.Claims.First (), p.Claims.First (), "#7");
		}
Exemplo n.º 26
0
		public void IPrincipalCtorClaimsPrincipalWorks ()
		{
			var baseId = new ClaimsIdentity (
				           new List<Claim> { new Claim ("claim_type", "claim_value") },
				           "");
			var basePrincipal = new ClaimsPrincipal ();
			basePrincipal.AddIdentity (baseId);

			var p = new ClaimsPrincipal (basePrincipal);

			Assert.IsNotNull (p.Identities, "#1");
			Assert.AreEqual (1, p.Identities.Count (), "#2");

			Assert.AreEqual (baseId, p.Identities.First (), "#3");

			Assert.AreEqual (baseId, p.Identity, "#4");

			Assert.IsNotNull (p.Claims, "$5");
			Assert.AreEqual (1, p.Claims.Count (), "#6");
			Assert.IsTrue (p.Claims.Any (claim => claim.Type == "claim_type" && claim.Value == "claim_value"), "#7");
		}
Exemplo n.º 27
0
        /// <summary>
        /// Clones a principal by filtering its identities.
        /// </summary>
        /// <param name="principal">The <see cref="ClaimsPrincipal"/> instance to filter.</param>
        /// <param name="filter">
        /// The delegate filtering the claims: return <c>true</c>
        /// to accept the claim, <c>false</c> to remove it.
        /// </param>
        public static ClaimsPrincipal Clone(this ClaimsPrincipal principal, Func<Claim, bool> filter) {
            if (principal == null) {
                throw new ArgumentNullException(nameof(principal));
            }

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

            var clone = new ClaimsPrincipal();

            foreach (var identity in principal.Identities) {
                clone.AddIdentity(identity.Clone(filter));
            }

            return clone;
        }
Exemplo n.º 28
0
        /// <summary>
        /// Begins handling the current user, whether to create the user in the database.
        /// </summary>
        /// <param name="context">The owin context</param>
        /// <returns>An awaitable task</returns>
        public async override Task Invoke(IOwinContext context)
        {
            try
            {
                if (context.IsOptionsRequest())
                {
                    await Next.Invoke(context);
                    return;
                }

                logger.Debug("Method: Invoke, BEGIN");
                logger.Trace("Request is preflight request?: {0}", context.IsOptionsRequest());
                var identity = context.Authentication.User.Identity;
                var username = identity.Name.Substring(identity.Name.LastIndexOf(@"\", StringComparison.OrdinalIgnoreCase) + 1);

                logger.Trace("Trying to retrieve user {0} from the database", username);
                var user = await userDatabaseRepository.Get(username);
                var error = false;
                var roles = new List<Role>();

                if (!user.HasValue)
                {
                    logger.Trace("User {0} does not exist in database", username);
                    logger.Trace("Retrieve \"User\" role from database");
                    var role = (await roleRepository.GetAll())
                        .FirstOrDefault(r => r.Name.Equals("User", StringComparison.OrdinalIgnoreCase));

                    roles.Add(role);
                    Debug.Assert(role != null, "Must have a predefined role: \"User\"");

                    logger.Trace("Retrieve user information from Active Directory");
                    var adUser = await userActiveDirectoryRepository.Get(username);
                    error = await adUser.Match(async u =>
                    {
                        logger.Trace("User info retrieved from Active Directory!");
                        u.Roles = roles;

                        logger.Trace("Creating user {0} in the database", username);
                        var onCreated = new Func<User, Task<bool>>(createdUser =>
                        {
                            return Task.FromResult(true);
                        });

                        var created = await userDatabaseRepository.Create(u, onCreated);
                        if (!created.HasValue)
                        {
                            // Error, couldn't create user in DB
                            logger.Error("Could not create user {0} in the database!", username);
                            return true;
                        }

                        logger.Trace("Created user {0} in the database!", username);
                        user = created;
                        return false;
                    },
                    () =>
                    {
                    // Error user, does not exist in AD
                    logger.Error("No user information for {0} in Active Directory!", username);
                        return Task.FromResult(true);
                    });

                }

                if (error)
                {
                    logger.Trace("Returning with error 500. Reason given earlier");
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    return;
                }

                // Set principal roles
                var actualUser = user.ValueOrFailure();
                logger.Trace("Extracting user {1} with ID {0}...", actualUser.ID, username);

                //// Note: .NET Framework 1.1 and onwards IsInRole is case-insensitive!
                //// source: https://msdn.microsoft.com/en-us/library/fs485fwh(v=vs.110).aspx
                logger.Trace("Setting authenticated user to principal");
                var claimsPrincipal = new ClaimsPrincipal();
                var claimsIdentity = new ClaimsIdentity(AuthenticationTypes.Windows);

                logger.Trace("Filtering out the claims...");
                var claims = context.Authentication.User.Claims.Where(c => !c.Type.Equals(ClaimTypes.Name, StringComparison.OrdinalIgnoreCase));

                logger.Trace("Adding filtered claims...");
                claimsIdentity.AddClaims(claims);

                logger.Trace("Setting claim to username: {0}", actualUser.Username);
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, actualUser.Username));

                foreach (var role in actualUser.Roles)
                {
                    logger.Trace("Adding role \"{0}\" to claims", role.Name);
                    claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, role.Name));
                }

                logger.Trace("Adding identity to principal...");
                claimsPrincipal.AddIdentity(claimsIdentity);

                logger.Trace("Setting context to principal...");
                context.Authentication.User = claimsPrincipal;

                logger.Trace("Saving user in owin context: ({0}, {1})...", Constants.CURRENT_USER, actualUser.Username);
                context.Set(Constants.CURRENT_USER, actualUser);

                logger.Trace("Proceeding with the owin middleware pipeline");
                await Next.Invoke(context);
                logger.Debug("Method: Invoke, END");
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw;
            }
        }
        internal static async Task<AuthorizationCode> FromDbFormat(StoredAuthorizationCode code, IAsyncDocumentSession s, IScopeStore scopeStore)
        {
            var result = new AuthorizationCode
            {
                CreationTime = code.CreationTime,
                IsOpenId = code.IsOpenId,
                RedirectUri = code.RedirectUri,
                WasConsentShown = code.WasConsentShown,
                Nonce = code.Nonce,
                Client = Data.StoredClient.FromDbFormat(await s.LoadAsync<Data.StoredClient>("clients/" + code.Client)),
                CodeChallenge = code.CodeChallenge,
                CodeChallengeMethod = code.CodeChallengeMethod,
                SessionId = code.SessionId,
                RequestedScopes = await scopeStore.FindScopesAsync(code.RequestedScopes)
            };

            var claimsPrinciple = new ClaimsPrincipal();
            foreach (var id in code.Subject)
            {
                claimsPrinciple.AddIdentity(Data.StoredIdentity.FromDbFormat(id));
            }
            result.Subject = claimsPrinciple;

            return result;
        }
        private static FormsModel ReadData(JsonReader reader)
        {
            bool isPersistent;
            DateTimeOffset expireUtc;
            var principal = new ClaimsPrincipal();

            reader
                .StartObject()
                .Property("p", out isPersistent, true)
                .Property("e", out expireUtc, DateTimeOffset.MinValue)
                .StartArray("i");

            while (reader.TokenType != JsonToken.EndArray)
            {
                string authenticationType;
                string nameClaimType;
                string roleClaimType;
                var claims = new List<Claim>();

                reader
                    .StartObject()
                    .Property("at", out authenticationType, null)
                    .Property("nct", out nameClaimType, ClaimsIdentity.DefaultNameClaimType)
                    .Property("rct", out roleClaimType, ClaimsIdentity.DefaultRoleClaimType)
                    .StartArray("c");

                while (reader.TokenType != JsonToken.EndArray)
                {
                    string claimType;
                    string claimValue;
                    reader
                        .StartObject()
                        .Property("t", out claimType, nameClaimType)
                        .Property("v", out claimValue, null)
                        .EndObject();
                    claims.Add(new Claim(claimType, claimValue));
                }

                reader
                    .EndArray()
                    .EndObject();

                principal.AddIdentity(new ClaimsIdentity(
                    claims,
                    authenticationType,
                    nameClaimType,
                    roleClaimType));
            }

            reader
                .EndArray()
                .EndObject(final: true);

            return new FormsModel
            {
                IsPersistent = isPersistent,
                ExpireUtc = expireUtc,
                Principal = principal
            };
        }