예제 #1
0
        private void ConfigureServer(bool authedUser = false, IEnumerable <Claim> claims = null)
        {
            var server = new TestServer(
                new WebHostBuilder()
                .ConfigureServices(x =>
            {
                x.AddCarter(configurator: c =>
                            c.WithModule <SecurityClaimsModule>()
                            .WithModule <SecurityModule>());
            })
                .Configure(x =>
            {
                if (authedUser)
                {
                    x.Use(async(context, next) =>
                    {
                        var identity = new GenericIdentity("AuthedUser");
                        if (claims != null)
                        {
                            identity.AddClaims(claims);
                        }

                        context.User = new ClaimsPrincipal(identity);
                        await next();
                    });
                }

                x.UseCarter();
            })
                );

            this.httpClient = server.CreateClient();
        }
예제 #2
0
        public void TestProjectsExist()
        {
            var controller = new EditorController();


            string username = "******";
            string userid   = Guid.NewGuid().ToString("N"); //could be a constant

            List <Claim> claims = new List <Claim> {
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", username),
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", userid)
            };
            var genericIdentity = new GenericIdentity("");

            genericIdentity.AddClaims(claims);
            var genericPrincipal = new GenericPrincipal(genericIdentity, new string[] { "" });

            var controllerContext = new Mock <ControllerContext>();
            var principal         = new Mock <IPrincipal>();

            controllerContext.SetupGet(x => x.HttpContext.User).Returns(genericPrincipal);
            principal.SetupGet(x => x.Identity.IsAuthenticated).Returns(true);
            controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object);
            controller.ControllerContext = controllerContext.Object;

            var queryResult = from rel in db.Project_Users_Relations
                              where rel.UserId == userId
                              join pro in db.Projects on rel.ProjectId equals pro.Id
                              select pro;
        }
        private User AddUserDetailsToContext(HttpContextAccessor httpContextAccessor)
        {
            var adminUser = _applicationService.GetUsers(null, null, null, "EmailAddress", "ASC", "Authorised", "Admin", null, null).FirstOrDefault();

            var logOnUser = new DTO.Request.Application.User
            {
                OrganisationId = adminUser.OrganisationId,
                DisplayName    = adminUser.DisplayName,
                EmailAddress   = adminUser.EmailAddress
            };

            var loggedOnAdminUser = _applicationService.LogonUser(logOnUser);

            IList <Claim> claimCollection = new List <Claim>
            {
                new Claim("UserId", loggedOnAdminUser.UserId.ToString()),
                new Claim("UserSessionId", loggedOnAdminUser.UserSessionId.ToString())
            };

            var identity = new GenericIdentity(loggedOnAdminUser.DisplayName, "TestAdminUser");

            identity.AddClaims(claimCollection);
            var contextUser = new ClaimsPrincipal(identity);

            var httpContext = new DefaultHttpContext()
            {
                User = contextUser,
            };

            httpContextAccessor.HttpContext = httpContext;

            return(loggedOnAdminUser);
        }
        private AuthenticationTicket BuildAuthenticationTicketFromAuthenticationResponse(AzureAuthenticationResponse userDetails)
        {
            string userId = userDetails.AuthMeResponse["user_id"].Value <string>();

            Logger.LogDebug("Building authentication ticket for user : {0}", userId);

            GenericIdentity identity = new GenericIdentity(userId);

            Logger.LogInformation("Adding claims from payload");

            List <Claim> claims = new List <Claim>();

            foreach (JToken claim in userDetails.AuthMeResponse["user_claims"])
            {
                claims.Add(new Claim(claim["typ"].ToString(), claim["val"].ToString()));
            }

            Logger.LogInformation("Adding claims for groups");

            foreach (JToken group in userDetails.GroupMemberships)
            {
                bool isSecurityGroup = group["securityEnabled"].Value <bool>();
                if (isSecurityGroup)
                {
                    claims.Add(new Claim(Constants.GroupsClaimType, group["id"].ToString()));
                }
            }

            Logger.LogInformation("Add claims to new identity");
            identity.AddClaims(claims);

            GenericPrincipal p = new GenericPrincipal(identity, null);

            return(new AuthenticationTicket(p, AzureAuthenticationDefaults.AuthenticationScheme));
        }
예제 #5
0
        private AuthenticationTicket BuildIdentityFromJsonPayload(JObject payload)
        {
            var id           = payload["user_id"].Value <string>();
            var idToken      = payload["id_token"].Value <string>();
            var providerName = payload["provider_name"].Value <string>();

            Logger.LogDebug("payload was fetched from endpoint. id: {0}", id);

            var identity = new GenericIdentity(id);

            Logger.LogInformation("building claims from payload...");

            List <Claim> claims = new List <Claim>();

            foreach (var claim in payload["user_claims"])
            {
                claims.Add(new Claim(claim["typ"].ToString(), claim["val"].ToString()));
            }

            Logger.LogInformation("Add claims to new identity");

            identity.AddClaims(claims);
            identity.AddClaim(new Claim("id_token", idToken));
            identity.AddClaim(new Claim("provider_name", providerName));
            var p = new GenericPrincipal(identity, null);

            return(new AuthenticationTicket(
                       p,
                       EasyAuthAuthenticationDefaults.AuthenticationScheme
                       ));
        }
예제 #6
0
        public void TestInitialize()
        {
            _orderId = 1;
            _userId  = "1";

            var identity = new GenericIdentity("*****@*****.**");

            identity.AddClaims(new List <Claim> {
                new Claim(ClaimTypes.Name, "*****@*****.**"),
                new Claim(ClaimTypes.NameIdentifier, _userId)
            });

            var principal = new GenericPrincipal(identity, null);

            _orders = new List <Order>();

            _orders.Add(new Order
            {
                Id        = _orderId,
                OrderDate = DateTime.Now,
                Customer  = new ApplicationUser()
                {
                    Id = _userId, UserName = "******"
                },
                CustomerId = _userId,
                OrderItems = new List <OrderItem>
                {
                    new OrderItem()
                    {
                        ItemId    = 1,
                        OrderId   = _orderId,
                        Price     = 1,
                        LinePrice = 2,
                        Quantity  = 2
                    },
                    new OrderItem()
                    {
                        ItemId    = 2,
                        OrderId   = _orderId,
                        Price     = 3,
                        LinePrice = 3,
                        Quantity  = 1
                    }
                },
                TotalPrice = 5
            });

            Mapper.Reset();
            Mapper.Initialize(cfg => cfg.AddProfile <AutoMapperProfile>());

            _mockOrders = new Mock <DbSet <Order> >();

            _mockContext = new Mock <IApplicationDbContext>();

            _repository = new OrderRepository(_mockContext.Object);

            _mockOrders.SetSource(_orders);

            _mockContext.SetupGet(c => c.Orders).Returns(_mockOrders.Object);
        }
        /// <summary>
        /// Mock http context/identity authentication
        /// </summary>
        /// <param name="controller">Controller where extends PortfolioBaseController</param>
        /// <param name="systemUserId">System User ID</param>
        /// <param name="firstName">System First Name</param>
        /// <param name="lastName">System Last Name</param>
        /// <param name="email">System User Email</param>
        /// <param name="roles">System User Roles</param>
        public static void InitAuthentication <TController>(this TController controller, int systemUserId, string firstName, string lastName, string email, string[] roles)
            where TController : PortfolioBaseController
        {
            //Setup Identity and assign to Principal
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, systemUserId.ToString()),
                new Claim(ClaimTypes.Surname, lastName),
                new Claim(ClaimTypes.Email, email)
            };
            var genericIdentity = new GenericIdentity(firstName);

            genericIdentity.AddClaims(claims);
            var genericPrincipal = new GenericPrincipal(genericIdentity, roles);

            //Setup HTTP Context and assign to Controller Context
            var mockHttpContext = new Mock <System.Web.HttpContextBase>();

            mockHttpContext.SetupGet(x => x.User).Returns(genericPrincipal);
            var controllerContext = new Mock <ControllerContext>();

            controllerContext.Setup(t => t.HttpContext).Returns(mockHttpContext.Object);

            //Assign Principal to Authentication Manager
            var mockAuthenticationManager = new Mock <IAuthenticationManager>();

            mockAuthenticationManager.Setup(i => i.User).Returns(genericPrincipal);

            //Assign Controller Context and Authentication Manager to controller
            controller.ControllerContext     = controllerContext.Object;
            controller.AuthenticationManager = mockAuthenticationManager.Object;
        }
예제 #8
0
        private void ConfigureServer(bool authedUser = false, IEnumerable <Claim> claims = null)
        {
            var server = new TestServer(new WebHostBuilder()
                                        .ConfigureServices(x => { x.AddBotwin(typeof(TestModule).GetTypeInfo().Assembly); })
                                        .Configure(x =>
            {
                if (authedUser)
                {
                    x.Use(async(context, next) =>
                    {
                        var identity = new GenericIdentity("AuthedUser");
                        if (claims != null)
                        {
                            identity.AddClaims(claims);
                        }
                        context.User = new ClaimsPrincipal(identity);
                        await next();
                    });
                }

                x.UseBotwin();
            })
                                        );

            this.httpClient = server.CreateClient();
        }
예제 #9
0
 public ActionResult Login(LoginViewModel model)
 {
     var user = new User
     {
         Username = model.Username,
         Password = model.Password
     };
     if (_userBusiness.IsExisted(user))
     {
         var genericIdentity = new GenericIdentity(model.Username, DefaultAuthenticationTypes.ApplicationCookie);
         genericIdentity.AddClaims(new[]
         {
             new Claim(ClaimTypes.Name, model.Username),
             new Claim(ClaimTypes.Role, "Admin"),
             new Claim("/CustomClaim/Permission", "Contact"),
         });
         var authentication = new CookieBaseAuthentication(HttpContext.GetOwinContext(), genericIdentity);
         authentication.SignIn();
         if (string.IsNullOrEmpty(model.ReturnUrl))
         {
             return RedirectToAction("Index", "Home");
         }
         return Redirect(model.ReturnUrl);
     }
     ModelState.AddModelError("", "tk ko ton tai");
     return View();
 }
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.ControllerContext.Controller.GetType() == typeof(SecurityController))
            {
                return;
            }

            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request
                                         .CreateResponse(HttpStatusCode.Unauthorized);
                // If the request was unauthorized, add the WWW-Authenticate header
                // to the response which indicates that it require basic authentication
                if (actionContext.Response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    actionContext.Response.Headers.Add("WWW-Authenticate",
                                                       string.Format("Basic realm=\"{0}\"", Realm));
                }
                return;
            }

            SetAuthenticationDomain();

            var    usernamePasswordArray = GetAuthenticationHeader(actionContext);
            string username = string.Empty, password = string.Empty;

            if (usernamePasswordArray.Length == 2)
            {
                username = usernamePasswordArray[0];
                password = usernamePasswordArray[1];
            }

            var user = _authenticationDomain.LogInUser(username, password);

            if (user != null)
            {
                var identity = new GenericIdentity(username);
                identity.AddClaims(GetUserClaims(user, user.Roles));

                IPrincipal principal = new GenericPrincipal(identity, null);

                if (!IsRolePermissionOk(user.Roles))
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
                    return;
                }

                Thread.CurrentPrincipal = principal;
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.User = principal;
                }
            }
            else
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
        }
예제 #11
0
        public ClaimsPrincipal CreateLoggedInUser(string userID)
        {
            var identity = new GenericIdentity("TestUser");

            identity.AddClaims(new List <Claim> {
                new Claim(ClaimTypes.Sid, userID),
            });
            return(new ClaimsPrincipal(identity));
        }
예제 #12
0
        public static ClaimsPrincipal GetClaimsPrincipal(this User user, string scheme)
        {
            var identity = new GenericIdentity(user.Id.ToString(), scheme);

            identity.AddClaim(new Claim(ClaimTypes.GivenName, user.Name));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Login));
            identity.AddClaims(user.GetMasterClassClaims());
            return(new GenericPrincipal(identity, user.Roles));
        }
        private ClaimsPrincipal GetFakePrincipal(string email, int id)
        {
            var ident  = new GenericIdentity("test user");
            var claims = new List <Claim>();

            claims.Add(new Claim(ClaimTypes.Email, email));
            claims.Add(new Claim(ClaimTypes.NameIdentifier, id.ToString()));
            ident.AddClaims(claims);
            return(new ClaimsPrincipal(ident));
        }
예제 #14
0
        private ClaimsPrincipal CreateLoggedInUser()
        {
            var identity = new GenericIdentity("TestUser");

            identity.AddClaims(new List <Claim> {
                new Claim(ClaimTypes.Sid, "UserId")
            });

            return(new ClaimsPrincipal(identity));
        }
예제 #15
0
        public ClaimsPrincipal CreateLoggedInUserWithRoleCanManage(string userID)
        {
            var roles    = new[] { RoleName.CanManage };
            var identity = new GenericIdentity("TestUser");

            identity.AddClaims(new List <Claim> {
                new Claim(ClaimTypes.Sid, userID),
            });
            var principal = new GenericPrincipal(identity, roles);

            return(new ClaimsPrincipal(principal));
        }
예제 #16
0
    public JwtSecurityToken Create(JwtCreatorOptions options)
    {
        var identity = new GenericIdentity(options.Name);

        identity.AddClaim(new Claim(JwtRegisteredClaimNames.Sub, options.Name));

        var id = Guid.NewGuid().ToString().GetHashCode().ToString("x", CultureInfo.InvariantCulture);

        identity.AddClaim(new Claim(JwtRegisteredClaimNames.Jti, id));

        if (options.Scopes is { } scopesToAdd)
        {
            identity.AddClaims(scopesToAdd.Select(s => new Claim("scope", s)));
        }

        if (options.Roles is { } rolesToAdd)
        {
            identity.AddClaims(rolesToAdd.Select(r => new Claim(ClaimTypes.Role, r)));
        }

        if (options.Claims is { Count : > 0 } claimsToAdd)
        {
            identity.AddClaims(claimsToAdd.Select(kvp => new Claim(kvp.Key, kvp.Value)));
        }

        // Although the JwtPayload supports having multiple audiences registered, the
        // creator methods and constructors don't provide a way of setting multiple
        // audiences. Instead, we have to register an `aud` claim for each audience
        // we want to add so that the multiple audiences are populated correctly.
        if (options.Audiences is { Count : > 0 } audiences)
        {
            identity.AddClaims(audiences.Select(aud => new Claim(JwtRegisteredClaimNames.Aud, aud)));
        }

        var handler = new JwtSecurityTokenHandler();
        var jwtSigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256Signature);
        var jwtToken = handler.CreateJwtSecurityToken(Issuer, audience: null, identity, options.NotBefore, options.ExpiresOn, issuedAt: DateTime.UtcNow, jwtSigningCredentials);

        return(jwtToken);
    }
예제 #17
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            // Azure app service will send the x-ms-client-principal-id when authenticated
            app.Use(async(context, next) =>
            {
                // Create a user on current thread from provided header
                if (context.Request.Headers.ContainsKey("X-MS-CLIENT-PRINCIPAL-ID"))
                {
                    // Read headers from Azure
                    var azureAppServicePrincipalIdHeader   = context.Request.Headers["X-MS-CLIENT-PRINCIPAL-ID"][0];
                    var azureAppServicePrincipalNameHeader = context.Request.Headers["X-MS-CLIENT-PRINCIPAL-NAME"][0];

                    // Create claims id
                    var claims = new Claim[] {
                        new Claim("http://schemas.microsoft.com/identity/claims/objectidentifier", azureAppServicePrincipalIdHeader),
                        new Claim("name", azureAppServicePrincipalNameHeader)
                    };

                    // Set user in current context as claims principal
                    var identity = new GenericIdentity(azureAppServicePrincipalIdHeader);
                    identity.AddClaims(claims);

                    // Set current thread user to identity
                    context.User = new GenericPrincipal(identity, null);
                }
                ;

                await next.Invoke();
            });

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
예제 #18
0
        public static void MockCurrentUser(this ApiController controller, string userId, string userName)
        {
            var identity = new GenericIdentity(userName);

            identity.AddClaims(new List <Claim> {
                new Claim(ClaimTypes.Name, userName),
                new Claim(ClaimTypes.NameIdentifier, userId)
            });

            var principal = new GenericPrincipal(identity, null);

            controller.User = principal;
        }
예제 #19
0
        public static void MockCurrentUser(this ApiController controller, string userId, string userName)
        {
            var securityClaims = new List <Claim> {
                new Claim(ClaimTypeNameIdentifierUri, userId),
                new Claim(ClaimTypeNameUri, userName)
            };

            var identity = new GenericIdentity("");

            identity.AddClaims(securityClaims);
            var principal = new GenericPrincipal(identity, null);

            controller.User = principal;
        }
예제 #20
0
        public static GenericPrincipal GetPrincipal(string userId, string userName)
        {
            var claims = new List <Claim>
            {
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", userName),
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", userId)
            };
            var genericIdentity = new GenericIdentity(userName);

            genericIdentity.AddClaims(claims);
            var genericPrincipal = new GenericPrincipal(genericIdentity, new string[0]);

            return(genericPrincipal);
        }
예제 #21
0
        public static IPrincipal GetPrincipalMock(string id, string name, string[] roles)
        {
            List <Claim> claims = new List <Claim>
            {
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", name),
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", id),
                new Claim(WebApiConstants.ClaimOrganizationId, "1")
            };
            var genericIdentity = new GenericIdentity(string.Empty);

            genericIdentity.AddClaims(claims);
            var genericPrincipal = new GenericPrincipal(genericIdentity, roles);

            return(genericPrincipal);
        }
예제 #22
0
        private void SetupPrincipalInControllerContext(string userId)
        {
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, userId)
            };

            var genericIdentity = new GenericIdentity("newMockIdentity");

            genericIdentity.AddClaims(claims);

            var genericPrincipal = new GenericPrincipal(genericIdentity, new string[] { });

            _userController.User = genericPrincipal;
        }
        public static void MockCurrentUser(this Controller controller, string userId, string userName)
        {
            var securityClaims = new List <Claim> {
                new Claim(ClaimTypeNameIdentifierUri, userId),
                new Claim(ClaimTypeNameUri, userName)
            };

            var identity = new GenericIdentity("");

            identity.AddClaims(securityClaims);
            var principal = new GenericPrincipal(identity, null);

            controller.ControllerContext = Mock.Of <ControllerContext>(ctx =>
                                                                       ctx.HttpContext == Mock.Of <HttpContextBase>(http =>
                                                                                                                    http.User == principal));
        }
        public async Task Invoke(HttpContext context)
        {
            var identity = new GenericIdentity("*****@*****.**");
            var claims   = new List <Claim>
            {
                new Claim(ClaimTypes.Role, Roles.Admin),
                new Claim(ClaimTypes.Name, "Name"),
                new Claim(ClaimTypes.Surname, "Surname")
            };

            identity.AddClaims(claims);

            context.User = new ClaimsPrincipal(identity);

            await _next(context);
        }
예제 #25
0
        public static async Task GetAzureIdentity(HttpContext context)
        {
            // Create a user on current thread from provided header
            if (context.User?.Identity == null || context.User.Identity.IsAuthenticated == false)
            {
                //invoke /.auth/me
                var cookieContainer       = new CookieContainer();
                HttpClientHandler handler = new HttpClientHandler
                {
                    CookieContainer = cookieContainer
                };
                string uriString = $"{context.Request.Scheme}://{context.Request.Host}";
                foreach (var c in context.Request.Cookies)
                {
                    cookieContainer.Add(new Uri(uriString), new Cookie(c.Key, c.Value));
                }
                using (HttpClient client = new HttpClient(handler))
                {
                    var res = await client.GetAsync($"{uriString}/.auth/me");

                    if (res.StatusCode == HttpStatusCode.OK)
                    {
                        var jsonResult = await res.Content.ReadAsStringAsync();

                        //parse json
                        var    obj      = JArray.Parse(jsonResult);
                        string userId   = obj[0]["user_id"].Value <string>(); //user_id
                        var    provider = obj[0]["provider_name"].Value <string>();

                        // Create claims id
                        List <Claim> claims = new List <Claim>();
                        foreach (var claim in obj[0]["user_claims"])
                        {
                            claims.Add(new Claim(claim["typ"].ToString(), claim["val"].ToString()));
                        }
                        claims.Add(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity"));
                        claims.Add(new Claim(ClaimTypes.Actor, provider));
                        // Set user in current context as claims principal
                        var identity = new GenericIdentity(userId);
                        identity.AddClaims(claims);

                        // Set current thread user to identity
                        context.User = new GenericPrincipal(identity, null);
                    }
                }
            }
        }
예제 #26
0
        private GenericPrincipal CreateUser()
        {
            string       username = "******";
            string       userid   = Guid.NewGuid().ToString("N"); //could be a constant
            List <Claim> claims   = new List <Claim>
            {
                new Claim(ClaimTypes.Name, username),
                new Claim(ClaimTypes.NameIdentifier, userid)
            };

            var genericIdentity = new GenericIdentity("");

            genericIdentity.AddClaims(claims);
            var genericPrincipal = new GenericPrincipal(genericIdentity, new[] { "Administrator" });

            return(genericPrincipal);
        }
        public async Task InvokeAsync(HttpContext context)
        {
            if (context.Request.Headers.ContainsKey("X-MS-CLIENT-PRINCIPAL-ID"))
            {
                var azureAppServicePrincipalIdHeader = context.Request.Headers["X-MS-CLIENT-PRINCIPAL-ID"][0];

                var uriString       = $"{context.Request.Scheme}://{context.Request.Host}";
                var cookieContainer = new CookieContainer();
                var handler         = new HttpClientHandler()
                {
                    CookieContainer = cookieContainer
                };

                foreach (var c in context.Request.Cookies)
                {
                    cookieContainer.Add(new Uri(uriString), new Cookie(c.Key, c.Value));
                }

                var jsonResult = string.Empty;
                using (var client = new HttpClient(handler))
                {
                    var res = await client.GetAsync($"{uriString}/.auth/me");

                    jsonResult = await res.Content.ReadAsStringAsync();
                }



                var obj = JArray.Parse(jsonResult);

                var claims = new List <Claim>();
                foreach (var claim in obj[0]["user_claims"])
                {
                    claims.Add(new Claim(claim["typ"].ToString(), claim["val"].ToString()));
                }

                var identity = new GenericIdentity(azureAppServicePrincipalIdHeader);
                identity.AddClaims(claims);

                context.User = new GenericPrincipal(identity, null);
            }

            await _next(context);
        }
예제 #28
0
        private void ConfigureServer(bool authedUser = false, IEnumerable <Claim> claims = null)
        {
            var server = new TestServer(
                new WebHostBuilder()
                .ConfigureServices(x =>
            {
                x.AddAuthorization(options =>
                {
                    options.AddPolicy("reallysecurepolicy", policy => { policy.RequireClaim(ClaimTypes.Actor); });
                    options.AddPolicy("reallysecuresecondpolicy", policy => { policy.RequireClaim(ClaimTypes.Email); });
                });

                x.AddCarter(configurator: c =>
                            c.WithModule <SecurityClaimsModule>()
                            .WithModule <SecurityModule>()
                            .WithModule <SecureSinglePolicyModule>()
                            .WithModule <SecureMultiPolicyModule>()
                            );
            })
                .Configure(x =>
            {
                if (authedUser)
                {
                    x.Use(async(context, next) =>
                    {
                        var identity = new GenericIdentity("AuthedUser");
                        if (claims != null)
                        {
                            identity.AddClaims(claims);
                        }

                        context.User = new ClaimsPrincipal(identity);
                        await next();
                    });
                }

                x.UseCarter();
            })
                );

            this.httpClient = server.CreateClient();
        }
예제 #29
0
        public static UserPrincipal Create(string username, string[] roles, IEnumerable <Claim> claims, string dbName)
        {
            GenericIdentity i = new GenericIdentity(username, "token");

            if (claims != null)
            {
                i.AddClaims(claims);
            }

            if (roles == null)
            {
                roles = new string[] { }
            }
            ;

            return(new UserPrincipal(i, roles)
            {
                DB = App.MongoClient.GetDatabase(dbName)
            });
        }
예제 #30
0
        /// <summary>
        /// Initializes the HTTP context.
        /// </summary>
        private static void InitHttpContext()
        {
            if (m_controllerContext != null)
            {
                return;
            }

            var          m_HttpContext = new Mock <System.Web.HttpContextBase>();
            List <Claim> claims        = new List <Claim> {
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", username),
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", userId)
            };
            var genericIdentity = new GenericIdentity("");

            genericIdentity.AddClaims(claims);
            var genericPrincipal = new GenericPrincipal(genericIdentity, new string[] { });

            m_HttpContext.SetupGet(x => x.User).Returns(genericPrincipal);
            m_controllerContext = new Mock <ControllerContext>();
            m_controllerContext.Setup(t => t.HttpContext).Returns(m_HttpContext.Object);
        }