コード例 #1
0
    /// <summary>
    /// Override to Web API filter method to handle Basic Auth check
    /// </summary>
    /// <param name="actionContext"></param>
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (Active)
        {
            var identity = ParseAuthorizationHeader(actionContext);
            if (identity == null)
            {
                Challenge(actionContext);
                return;
            }

            if (!OnAuthorizeUser(identity.Name, identity.Password, actionContext))
            {
                Challenge(actionContext);
                return;
            }

            var principal = new GenericPrincipal(identity, null);

            Thread.CurrentPrincipal = principal;

            // inside of ASP.NET this is required
            //if (HttpContext.Current != null)
            //    HttpContext.Current.User = principal;

            base.OnAuthorization(actionContext);
        }
    }
コード例 #2
0
 /// <summary>
 /// Stores the current <see cref="Thread.CurrentPrincipal"/> and replaces it with
 /// a new role identified in constructor.
 /// </summary>
 /// <param name="methodUnderTest">The method under test</param>
 public override void Before(MethodInfo methodUnderTest)
 {
     originalPrincipal = Thread.CurrentPrincipal;
     var identity = new GenericIdentity("xUnit");
     var principal = new GenericPrincipal(identity, new string[] { Name });
     Thread.CurrentPrincipal = principal;
 }
コード例 #3
0
ファイル: Test2.cs プロジェクト: BackupTheBerlios/boxerp-svn
 public void TrySendIdentity()
 {
     GenericIdentity gident = new GenericIdentity("Testing");
         GenericPrincipal gprincipal = new GenericPrincipal(gident, null);
         Thread.CurrentPrincipal = gprincipal;
         Console.WriteLine("IDentity="+ Thread.CurrentPrincipal.Identity.Name);
         loginObj.ReadIdentity();
 }
コード例 #4
0
ファイル: Add_user.aspx.cs プロジェクト: bman2338/WaffleWerk
    // this code has been depricated as the number of online users now work
    // with the global.asax file. It won't hurt anything though.
    protected void RegisterUserWithRoles_CreatedUser(object sender, EventArgs e)
    {
        // do not show newly created user as Online
        MembershipUser muser = Membership.GetUser(RegisterUserWithRoles.UserName);
        muser.LastActivityDate = DateTime.Now.AddDays(-1);
        Membership.UpdateUser(muser);

        IPrincipal user = new GenericPrincipal(new GenericIdentity(muser.UserName), new string[0]);
        ProvisionNewUser(user);
    }
コード例 #5
0
    public void Demand()
    {
        PolicyDecision decision = new PolicyDecision(config);
        decision.ApplicationName = "Application 3";

        PolicyPermission permission = new PolicyPermission("Permission 1", decision);

        IIdentity identity = new GenericIdentity("User 1");
        IPrincipal principal = new GenericPrincipal(identity, new String[] { "Role 1" });
        Thread.CurrentPrincipal = principal;
        Assert.Throws(typeof(SecurityException),
          permission.Demand);

        identity = new GenericIdentity("User 2");
        principal = new GenericPrincipal(identity, new String[] { "Role 1", "Role 2", "Role 3" });
        Thread.CurrentPrincipal = principal;
        Assert.DoesNotThrow(permission.Demand);
    }
コード例 #6
0
    /// <summary>
    /// Parses the request headers to check the permission of the sender.
    /// If it has a Basic Authentication then it makes all the checks on the user
    /// </summary>
    /// <param name="request">The HTTP request message to send</param>
    /// <param name="cancellationToken">Token to send if the request will crash</param>
    /// <returns>The task object representing the asynchronous operation</returns>
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var authHeader = request.Headers.Authorization;

        if (authHeader == null)
        {
            return base.SendAsync(request, cancellationToken);
        }

        if (authHeader.Scheme != "Basic")
        {
            return base.SendAsync(request, cancellationToken);
        }

        var encodedUserPass = authHeader.Parameter.Trim();
        var userPass = Encoding.ASCII.GetString(Convert.FromBase64String(encodedUserPass));
        var parts = userPass.Split(":".ToCharArray());
        var username = parts[0];
        var password = parts[1];

        GRASPEntities db = new GRASPEntities();

        var item = (from u in db.User_Credential
                    join r in db.Roles on u.roles_id equals r.id
                    where u.username == username && u.password == password
                    select new { u, r }).FirstOrDefault();
        if (item == null)
        {
            return base.SendAsync(request, cancellationToken);
        }

        var identity = new GenericIdentity(username, "Basic");
        string[] roles = new string[1];
        roles[0] = item.r.description;
        var principal = new GenericPrincipal(identity, roles);
        Thread.CurrentPrincipal = principal;
        if (HttpContext.Current != null)
        {
            HttpContext.Current.User = principal;
        }

        return base.SendAsync(request, cancellationToken);
    }
コード例 #7
0
    // this code verifies the submitted URL and unlocks the user's account

    protected void Page_Load(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(Request.QueryString["ID"]))
            StatusMessage.Text = "The UserId was not included in the querystring...";
        else
        {
            Guid userId;

            try
            {
                userId = new Guid(Request.QueryString["ID"]);
            }
            catch
            {
                StatusMessage.Text = "The UserId passed into the querystring is not in the proper format...";
                return;
            }

            MembershipUser usr = Membership.GetUser(userId);
            if (usr == null)
                StatusMessage.Text = "User account could not be found...";
            else
            {
                // Approve the user
                if (!usr.IsApproved)
                {
                    usr.IsApproved = true;
                    Membership.UpdateUser(usr);

                    // user is a temporary IPrincipal just used to Provision New User so give it 
                    // whatever roles are needed to set up the user's account properly.
                    // NOTE: These roles will _not_ be saved in the Membership datastore.
                    string[] roles = new string[] { /* PUT ROLES REQUIRED FOR USER ACCOUNT SETUP HERE */ };
                    IPrincipal user = new GenericPrincipal(new GenericIdentity(usr.UserName),roles);

                    ProvisionNewUser(user);
                }
                StatusMessage.Text = "Your account has been approved. Please <a href=\"Login.aspx\">login</a> to the site.";
            }
        }
    }
コード例 #8
0
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        IIdentity identity = GetIdentity();

        if (identity == null)
        {
            var challengeMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            challengeMessage.Headers.WwwAuthenticate.Add(
                new AuthenticationHeaderValue("oauth", "location=\"" + this.BuildFacebookAuthUri(actionContext.Request) + "\""));
            throw new HttpResponseException(challengeMessage);
        }

        var principle = new GenericPrincipal(identity, new string[0]);

        // set the thread context
        Thread.CurrentPrincipal = principle;

        if (!this.AuthorizeCore(principle))
        {
            throw new HttpResponseException(actionContext.Request.CreateResponse(HttpStatusCode.Forbidden));
        }
    }
コード例 #9
0
    protected void btnRegister_Click(object sender, EventArgs e)
    {
        string UserId = this.txtUserName.Text;
        MembershipUser user = Membership.CreateUser(UserId, UserId, txtEmail.Text);
        if (user != null)
        {
            FormsAuthentication.Authenticate(UserId, UserId);
            WebProfile Profile = new WebProfile();
            Profile.Initialize(UserId, true);
            Profile.FirstName = this.txtFirstName.Text;
            Profile.LastName = this.txtLastName.Text;
            Profile.Newsletter = this.chkNewsLetter.Checked;
            Profile.Email = this.txtEmail.Text;
            Profile.Save();

            GenericIdentity userIdentity = new GenericIdentity(UserId);
            GenericPrincipal userPrincipal =
              new GenericPrincipal(userIdentity, new string[] { "User" });
            Context.User = userPrincipal;

            if (!Roles.IsUserInRole(User.Identity.Name, "User"))
            {
                PAB.Web.Providers.SimpleSqlRoleProvider prov = new SimpleSqlRoleProvider();
                NameValueCollection config = new NameValueCollection();
                config["connectionStringName"] = "OpenId";
                System.Configuration.ConnectionStringSettings ConnectionStringSettings =
                    System.Configuration.ConfigurationManager.ConnectionStrings[config["connectionStringName"]];
                prov.Initialize("", config);
                prov.AddUsersToRoles(new string[] { User.Identity.Name }, new string[] { "User" });
            }
            // go to a page for users who are authenticated
            Response.Redirect("Default2.aspx");
        }
        else
        {
            //uh-oh! you handle it appropriately.
        }

    }
コード例 #10
0
        /// <summary>
        /// Assign the agent connected as a principal of the system
        /// </summary>
        /// <param name="OidAgent">OID of the agent connected to the system</param>
        public IPrincipal AgentAssign(ONOid OidAgent)
        {
            // Retrieve old principal
            IPrincipal lPrincipalOld = Thread.CurrentPrincipal;

            // Create Identity
            GenericIdentity lIdentity = new GenericIdentity(OidAgent.ToString());

            // Create Principal
            string[] lRoles = new string[LeafActiveAgentFacets.Count];

            for (int i = 0; i < LeafActiveAgentFacets.Count; i++)
            {
                lRoles[i] = LeafActiveAgentFacets[i];
            }

            GenericPrincipal lPrincipal = new GenericPrincipal(lIdentity, lRoles);

            // Assign to the current thread
            Thread.CurrentPrincipal = lPrincipal;

            return(lPrincipalOld);
        }
コード例 #11
0
        /// <summary>
        /// Logs on the user with the specified credentials.
        /// </summary>
        /// <param name="userDataContext">The user data context.</param>
        /// <param name="login">The login.</param>
        /// <param name="password">The password.</param>
        /// <returns>
        /// An instance of <see cref="IPrincipal" /> if the logon was successful. Otherwise, a
        /// <see cref="SecurityException" /> is thrown.
        /// </returns>
        /// <remarks>The returned principal only contains the name of the user.</remarks>
        protected override IPrincipal Logon(XElement userDataContext, string login, string password)
        {
            // Get all users that match the login and password.
            var users =
                from u in userDataContext.Elements(this._userNamespace, "user")
                where
                u.Element(this._userNamespace, "credentials").Element(this._userNamespace, "login").Value == login &&
                u.Element(this._userNamespace, "credentials").Element(this._userNamespace, "password").Value == password.Hash()
                select u;

            // If no or more than one user was found, throw an exception.
            if (users.Count() != 1)
            {
                throw new SecurityException(String.Format(CultureInfo.CurrentUICulture,
                                                          "Logon denied for login '{0}'.", login));
            }

            // Otherwise, set up a basic principal.
            var principal = new GenericPrincipal(new GenericIdentity(login), new string[0]);

            // Return the principal to the caller.
            return(principal);
        }
コード例 #12
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var authHeader = actionContext.Request.Headers.Authorization;

            if (authHeader != null)
            {
                if (authHeader.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(authHeader.Parameter))
                {
                    var credEncoded      = authHeader.Parameter;
                    var encoding         = Encoding.GetEncoding("iso-8859-1");
                    var Cred             = encoding.GetString(Convert.FromBase64String(credEncoded));
                    var split            = Cred.Split(':');
                    var userName         = split[0];
                    var password         = split[1];
                    var rolse            = new string[] { "Admin" };
                    var genericPrincipal = new GenericPrincipal(new GenericIdentity(userName, "Admin"), rolse);
                    Thread.CurrentPrincipal = genericPrincipal;
                    return;
                }
            }

            HandleUnAuthorizeRequest(actionContext);
        }
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var authHeader = actionContext.Request.Headers.Authorization;

            if (authHeader != null)
            {
                var authenticationToken        = actionContext.Request.Headers.Authorization.Parameter;
                var decodedAuthenticationToken = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationToken));
                var usernamePasswordArray      = decodedAuthenticationToken.Split(':');
                var userName = usernamePasswordArray[0];
                var password = usernamePasswordArray[1];

                if (IsAuthorizedUser(userName, password))
                {
                    var principal = new GenericPrincipal(new GenericIdentity(userName), null);
                    Thread.CurrentPrincipal = principal;

                    return;
                }
            }

            HandleUnathorized(actionContext);
        }
コード例 #14
0
        public void SerializationRoundtrip()
        {
            GenericIdentity  gi = new GenericIdentity("mono", "dna");
            GenericPrincipal gp = new GenericPrincipal(gi, new string[2] {
                "monkey", "hackers"
            });
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream    ms = new MemoryStream();

            bf.Serialize(ms, gp);

            //Console.WriteLine (BitConverter.ToString (ms.ToArray ()));

            ms.Position = 0;
            GenericPrincipal clone = (GenericPrincipal)bf.Deserialize(ms);

            Assert.AreEqual(gp.Identity.Name, clone.Identity.Name, "Name");
            Assert.AreEqual(gp.Identity.AuthenticationType, clone.Identity.AuthenticationType, "AuthenticationType");
            Assert.AreEqual(gp.Identity.IsAuthenticated, clone.Identity.IsAuthenticated, "IsAuthenticated");
            Assert.IsTrue(gp.IsInRole("monkey"), "IsInRole-monkey");
            Assert.IsTrue(gp.IsInRole("hackers"), "IsInRole-hackers");
            Assert.IsFalse(gp.IsInRole("donkey"), "IsInRole-donkey");
        }
コード例 #15
0
        /// <summary>
        /// Returns the principal cached against the user or creates and returns a new principal if the
        /// user has not got a cached principal.
        /// </summary>
        /// <param name="cachedUser"></param>
        /// <param name="cachedUserTag"></param>
        /// <returns></returns>
        public IPrincipal CreatePrincipal(CachedUser cachedUser, CachedUserTag cachedUserTag)
        {
            var result = cachedUserTag.Principal;

            if (result == null)
            {
                var roles = new List <string>();
                roles.Add(Roles.User);
                if (cachedUser.IsAdministrator)
                {
                    roles.Add(Roles.Admin);
                }

                result = new GenericPrincipal(
                    new GenericIdentity(cachedUser.User.LoginName, "basic"),
                    roles.ToArray()
                    );

                cachedUserTag.Principal = result;
            }

            return(result);
        }
コード例 #16
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var authHeader = actionContext.Request.Headers.Authorization;

            if (authHeader != null)
            {
                if (authHeader.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) && !String.IsNullOrWhiteSpace(authHeader.Parameter))
                {
                    var credentials = GetCredentials(authHeader);
                    var username    = credentials[0];
                    var password    = credentials[1];

                    if (AreCredentialsCorrect(username, password, actionContext))
                    {
                        var principal = new GenericPrincipal(new GenericIdentity(username), null);
                        Thread.CurrentPrincipal = principal;
                        return;
                    }
                }
            }

            HandleUnauthorised(actionContext);
        }
コード例 #17
0
        public SecurityTestsCommon(TestModel testModel, StreamWriter output, string userRole, string messagePrefix)
        {
            Model         = testModel;
            OutputFile    = output;
            MessagePrefix = messagePrefix;

            var roles = string.IsNullOrEmpty(userRole) ? new string[] { } : new string[] { userRole };

            User = new GenericPrincipal(new GenericIdentity("AnonUser"), roles);

            _handler = new HttpClientHandler();
            if (!string.IsNullOrEmpty(userRole))
            {
                var securityCookieContainer = new CookieContainer();
                securityCookieContainer.Add(Model.ApiUrl, new Cookie("SecurityTestRole", userRole));
                _handler.CookieContainer = securityCookieContainer;
            }

            Client             = new HttpClient(_handler);
            Client.BaseAddress = Model.ApiUrl;
            Client.DefaultRequestHeaders.Accept.Clear();
            Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }
コード例 #18
0
        public ActionResult Login(string form_login, string form_password)
        {
            UserDao userDao = new UserDao();
            User    user    = userDao.IsAllowed(form_login, form_password);

            if (user != null)
            {
                FormsAuthentication.SetAuthCookie(form_login, false);
                GenericIdentity  id        = new GenericIdentity(form_login, "FormAuthentication");
                GenericPrincipal principal = new GenericPrincipal(id, new string[0]);
                HttpContext.User = principal;

                user.IsManager = UserDao.IsManager(user);
                user.IsFinance = UserDao.IsFinance(user);

                Session["user"] = user;
                return(Redirect("~/Home/Index"));
            }
            else
            {
                return(RedirectToAction("Login"));
            }
        }
コード例 #19
0
        public void SetUser(string name)
        {
            kernel.Unbind <IPrincipal>();
            kernel.Unbind <IUserProvider>();
            kernel.Unbind <IRepository <ApplicationUser> >();
            var mockUserProvider = new Mock <IUserProvider>();
            var genericPrincipal = new GenericPrincipal(new GenericIdentity(name), new string[0]);

            mockUserProvider.Setup(x => x.GetUser(It.IsAny <Controller>())).Returns(genericPrincipal);
            kernel.Bind <IUserProvider>().ToConstant(mockUserProvider.Object);

            var mockUsersRepository = new Mock <IRepository <ApplicationUser> >();

            mockUsersRepository.Setup(x => x.Items).Returns(new List <ApplicationUser>()
            {
                new ApplicationUser
                {
                    UserName = name,
                    Id       = genericPrincipal.Identity.GetUserId()
                }
            }.AsQueryable());
            kernel.Bind <IRepository <ApplicationUser> >().ToConstant(mockUsersRepository.Object);
        }
コード例 #20
0
        protected void Application_AuthenticateRequest()
        {
            if (User == null)
            {
                return;
            }

            string mail = Context.User.Identity.Name;

            string[] roles = null;

            using (ITExpertsContext db = new ITExpertsContext())
            {
                User user = db.Users.FirstOrDefault(x => x.Email == mail);

                roles = db.Roles.Where(x => x.RoleId == user.RoleId).Select(x => x.RoleName).ToArray();
            }

            IIdentity  userIdentity = new GenericIdentity(mail);
            IPrincipal newUserObj   = new GenericPrincipal(userIdentity, roles);

            Context.User = newUserObj;
        }
コード例 #21
0
        /// <summary>
        /// 从Http请求里获取用户数据
        /// </summary>
        /// <typeparam name="UserDataT">用户数据</typeparam>
        /// <param name="userIdentity">用户标识</param>
        /// <returns>用户数据</returns>
        public static UserDataT ParseUserData <UserDataT>(string userIdentity = UserIdentity.DEFAULT_USER_IDENTITY)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (cookie == null || string.IsNullOrEmpty(cookie.Value))
            {
                return(default(UserDataT));
            }

            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
            UserDataT userData = ticket.UserData.DeserializeFromJson <UserDataT>();

            if (userData == null)
            {
                return(userData);
            }

            GenericPrincipal prin = new GenericPrincipal(new UserIdentity(true, userIdentity), null);

            HttpContext.Current.User = prin;

            return(userData);
        }
コード例 #22
0
#pragma warning disable CS1998 // This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
#pragma warning restore CS1998 // This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
        {
            try
            {
                //Method to authenticate not implemented

                var identity = new ClaimsIdentity(context.Options.AuthenticationType);

                identity.AddClaim(new Claim("Usuario", "123"));

                var principal = new GenericPrincipal(identity, new string[] { });

                Thread.CurrentPrincipal = principal;

                context.Validated(identity);
            }
            catch (Exception ex)
            {
                context.SetError("invalid_grant", ex.Message);
                return;
            }
        }
コード例 #23
0
        protected void Seed(string roleName, string roleDescription)
        {
            var identity  = new GenericIdentity("*****@*****.**");
            var principal = new GenericPrincipal(identity, new[] { RoleName.AuthorizationAgent });
            var role      = _queryProcessor.Execute(new RoleByName(principal, roleName));

            if (role == null)
            {
                _createRole.Handle(new CreateRole(roleName)
                {
                    Description = roleDescription,
                });
            }
            else
            {
                _updateRole.Handle(new UpdateRole(principal)
                {
                    EntityId    = role.EntityId,
                    Description = roleDescription,
                });
            }
            _unitOfWork.SaveChanges();
        }
コード例 #24
0
        public void GreeterPurchaseCDThroughOfficerApproval()
        {
            GenericIdentity  identity  = new GenericIdentity("GreeterUser");
            GenericPrincipal principal = new GenericPrincipal(identity, new string[] { "Greeter" });

            Thread.CurrentPrincipal = principal;

            // authenticate with an Officer role
            authService.Identity = "BranchManagerUser";
            authService.Roles    = new string[] { "BranchManager" };

            Account source = new Account();

            source.Balance = 10500;
            decimal amount   = 10001;           // need officer approval
            int     duration = 10;

            presenter.ApproveAndPurchaseCD(source, amount, duration);

            Assert.IsNotNull(accountService.CDAccount);
            Assert.AreEqual(((Customer)entry.Person).CustomerId, accountService.CDAccount.CustomerId);
            Assert.AreEqual(Convert.ToSingle(amount), accountService.CDAccount.Balance);
        }
コード例 #25
0
        public HomeController()
        {
            IPrincipal user = new GenericPrincipal(new GenericIdentity("User 1"), new[] { "student" });

            var e = new Event
            {
                Created     = DateTime.Now,
                Start       = DateTime.Now,
                End         = DateTime.Now.AddDays(1),
                Description = "Test",
                Location    = "sdfsdf"
            };


            ICalendarRepository repository = new CalendarRepository(user);
            var calendar = repository.CreateCalendar("me");

            //calendar.ID = "student-calendar";
            (calendar as CalendarInfo).AddItem(e);
            repository.Save(calendar, e);

            RegisterService(repository);
        }
コード例 #26
0
        public static void MockCurrentUser(this Controller controller, string userId, string userName)
        {
            var identity = new GenericIdentity(userName);

            identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
                                        userName));
            identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier",
                                        userId));

            var principal = new GenericPrincipal(identity, null);

            //var mockHttpContext = new Mock<HttpContextBase>();
            //mockHttpContext.SetupGet(c => c.User).Returns(principal);

            //var mockControllerContext = new Mock<ControllerContext>();
            //mockControllerContext.SetupGet(c => c.HttpContext).Returns(mockHttpContext.Object);

            //controller.ControllerContext = mockControllerContext.Object;

            controller.ControllerContext = Mock.Of <ControllerContext>(ctx =>
                                                                       ctx.HttpContext == Mock.Of <HttpContextBase>(http =>
                                                                                                                    http.User == principal));
        }
コード例 #27
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var userIdentity = ParseHeader(actionContext);

            if (userIdentity == null)
            {
                Challenge(actionContext, ResultStatusEnum.BasicError);
                return;
            }
            ResultStatusEnum resultStatusEnum = OnAuthorize(userIdentity.Name, userIdentity.Password, actionContext);

            if (resultStatusEnum != ResultStatusEnum.ok)
            {
                Challenge(actionContext, resultStatusEnum);
                return;
            }

            var principal = new GenericPrincipal(userIdentity, null);

            Thread.CurrentPrincipal = principal;

            base.OnAuthorization(actionContext);
        }
コード例 #28
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            var user = _userService.Authenticate(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "User or Password is invalid!");
                return;
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, user.Email));
            identity.AddClaim(new Claim(ClaimTypes.Role, user.IsAdmin ? "admin" : ""));

            var principal = new GenericPrincipal(identity, new string[] { user.IsAdmin ? "admin" : "" });

            Thread.CurrentPrincipal = principal;

            context.Validated(identity);
        }
        private void SetPrinciple(string username)
        {
            var roles = _membershipAdapter.GetRolesForUser(username);
            var user  = _membershipAdapter.GetUser(username);

            User modelUser;

            using (var session = _sessionFactory.OpenSession())
            {
                modelUser = session.Get <User>(user.UserId);
            }

            var identity = CreateIdentity(user.Username, modelUser);

            var principal = new GenericPrincipal(identity, roles);

            Thread.CurrentPrincipal = principal;

            if (HttpContext.Current != null)
            {
                HttpContext.Current.User = principal;
            }
        }
コード例 #30
0
        public static void Main_11_3_1()//Main_11_3_1
        {
            string[] roles = { "将军", "士官", "士兵" };
            //创建GenericIdentity对象
            GenericIdentity identity = new GenericIdentity("小王");
            //创建GenericPrincipal对象
            GenericPrincipal principal = new GenericPrincipal(identity, roles);

            //将principal对象附加到当前线程
            Thread.CurrentPrincipal = principal;

            //执行验证
            if (Thread.CurrentPrincipal.Identity.Name == "小王")
            {
                Console.WriteLine("小王可以指挥士兵。");
            }

            //执行角色检查
            if (Thread.CurrentPrincipal.IsInRole("士官"))
            {
                Console.WriteLine(identity.Name + ",士官你好。");
            }
        }
コード例 #31
0
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            using (var context = new WcfTest3Entities())
            {
                using (var userManager = new UserManager <IdentityUser>(new UserStore <IdentityUser>(context)))
                {
                    var identity = operationContext.ServiceSecurityContext.PrimaryIdentity;
                    var user     = userManager.FindByName(identity.Name);

                    if (user == null)
                    {
                        throw new FaultException("Username not known.");
                    }

                    var roles = userManager.GetRoles(user.Id).ToArray();

                    var principal = new GenericPrincipal(operationContext.ServiceSecurityContext.PrimaryIdentity, roles);
                    operationContext.ServiceSecurityContext.AuthorizationContext.Properties["Principal"] = principal;

                    return(true);
                }
            }
        }
コード例 #32
0
        public override void OnAuthorization(HttpActionContext context)
        {
            HttpRequestMessage req       = context.Request;
            GenericPrincipal   principal = req.GetRequestContext().Principal as GenericPrincipal;

            string[]      roles              = this.Roles.Split(',');
            int           numRoles           = roles.Length;
            bool          hasPermissions     = true;
            List <string> missingPermissions = new List <string>();

            foreach (string role in roles)
            {
                if (!principal.IsInRole(role))
                {
                    hasPermissions = false;
                    missingPermissions.Add(role);
                }
            }
            if (!hasPermissions)
            {
                HandleUnauthorizedRequest(context, missingPermissions);
            }
        }
コード例 #33
0
        public IPrincipal CreatePrincipal(string username, string password)
        {
            bool   isAuthen = false;
            string userRole = string.Empty;

            using (AuthenticationBLL authenBll = new AuthenticationBLL())
            {
                isAuthen = authenBll.CheckApiAuthen(username, password, out userRole);
            }

            if (isAuthen)
            {
                var identity = new GenericIdentity(username);

                //get roles for user
                IPrincipal principal = new GenericPrincipal(identity, new[] { userRole });
                return(principal);
            }
            else
            {
                return(null);
            }
        }
コード例 #34
0
        /// <summary>
        /// Checks basic authentication request
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(HttpActionContext filterContext)
        {
            if (!_isActive)
            {
                return;
            }
            var identity = FetchAuthHeader(filterContext);

            if (identity == null)
            {
                ChallengeAuthRequest(filterContext);
                return;
            }
            var genericPrincipal = new GenericPrincipal(identity, null);

            Thread.CurrentPrincipal = genericPrincipal;
            if (!OnAuthorizeUser(identity.Name, identity.Password, filterContext))
            {
                ChallengeAuthRequest(filterContext);
                return;
            }
            base.OnAuthorization(filterContext);
        }
コード例 #35
0
ファイル: DemoController.cs プロジェクト: jasonccliu/Web-API
        public IEnumerable <string> Get()
        {
            MyHttpServer httpServer = new MyHttpServer();

            //Thread.CurrentPrincipal == Null
            Thread.CurrentPrincipal = null;
            HttpRequestMessage request = new HttpRequestMessage();

            httpServer.SendAsync(request, new CancellationToken(false));
            GenericPrincipal principal = (GenericPrincipal)Thread.CurrentPrincipal;
            string           identity1 = string.IsNullOrEmpty(principal.Identity.Name) ? "N/A" : principal.Identity.Name;

            //Thread.CurrentPrincipal != Null
            GenericIdentity identity = new GenericIdentity("Artech");

            Thread.CurrentPrincipal = new GenericPrincipal(identity, new string[0]);
            request = new HttpRequestMessage();
            httpServer.SendAsync(request, new CancellationToken(false));
            principal = (GenericPrincipal)Thread.CurrentPrincipal;
            string identity2 = string.IsNullOrEmpty(principal.Identity.Name) ? "N/A" : principal.Identity.Name;

            return(new string[] { identity1, identity2 });
        }
コード例 #36
0
        protected void Seed(string roleName, string roleDescription)
        {
            var role = _queryProcessor.Execute(new GetRoleBySlugQuery(roleName.Replace(" ", "-")));

            if (role == null)
            {
                _createRole.Handle(new CreateRoleCommand(roleName)
                {
                    Description = roleDescription,
                });
            }
            else
            {
                var identity  = new GenericIdentity(GetType().Name);
                var principal = new GenericPrincipal(identity, new[] { RoleName.AuthorizationAgent });
                _updateRole.Handle(new UpdateRoleCommand(principal)
                {
                    EntityId    = role.EntityId,
                    Description = roleDescription,
                });
            }
            _unitOfWork.SaveChanges();
        }
コード例 #37
0
    protected static IPrincipal ConvertWindowsIdentityToGenericPrincipal(WindowsIdentity windowsIdentity)
    {
        if (windowsIdentity == null)
        {
            return(null);
        }
        // Identity in format DOMAIN\Username
        var identity   = new GenericIdentity(windowsIdentity.Name);
        var groupNames = new string[0];

        if (windowsIdentity.Groups != null)
        {
            // Array of Group-Names in format DOMAIN\Group
            groupNames = windowsIdentity.Groups
                         .Select(gId => gId.Translate(typeof(NTAccount)))
                         .Select(gNt => gNt.ToString())
                         .ToArray();
        }

        var genericPrincipal = new GenericPrincipal(identity, groupNames);

        return(genericPrincipal);
    }
コード例 #38
0
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            // Authorization bearer <token>
            var token = Request.Headers["Authorization"].ToString();

            // var body = Request.Body;
            if (string.IsNullOrEmpty(token))
            {
                return(null);
            }
            var bearerValue = token.Substring("bearer".Length).Trim();


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

            clms.Add(new Claim(ClaimTypes.Name, _authManager.ValidUsers[bearerValue]));

            var identity         = new ClaimsIdentity(clms, "Custom");
            var principle        = new GenericPrincipal(identity, null);
            var authenticnTicket = new AuthenticationTicket(principle, "Cstm");

            return(AuthenticateResult.Success(authenticnTicket));
        }
コード例 #39
0
        private AuthenticateResult validateToken()
        {
            // Making Claim with Identity
            var validatedToken = cAuthManger.Tokens.FirstOrDefault(t => t.Key == _tokenSession);

            if (validatedToken.Key == null)
            {
                return(AuthenticateResult.Fail("UnAuthorize"));
            }

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, validatedToken.Value.Item1),
                new Claim(ClaimTypes.Role, validatedToken.Value.Item2)
            };

            var identity = new ClaimsIdentity(claims, Scheme.Name);

            var principle = new GenericPrincipal(identity, new[] { validatedToken.Value.Item2 });
            var ticket    = new AuthenticationTicket(principle, Scheme.Name);

            return(AuthenticateResult.Success(ticket));
        }
コード例 #40
0
    /**
     * 2. Fired after LogginIn method to perform authentication
     */
    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        bool authenticated = false;

        string userNameTxt = Login1.UserName;
        string passTxt = Login1.Password;

        authenticated = userServices.authenticateUser(userNameTxt, passTxt);

        e.Authenticated = authenticated; // set login status.

        if (authenticated)
        {

            string roles = userServices.getRoles(userNameTxt);

            // Create the authentication ticket
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket
                                    (1,                             // Version
                                     userNameTxt,                   // User name
                                     DateTime.Now,                  // Creation
                                     DateTime.Now.AddMinutes(60),   // Expiration
                                     false,                         // Persistent
                                     roles);                        // User data

            // Code to create an encrypted string representation of the ticket and store it as data within an HttpCookie object.
            // Now encrypt the ticket.
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
            // Create a cookie and add the encrypted ticket to the cookie as data.
            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

            // Add the cookie to the cookies collection returned to the user's browser.
            Response.Cookies.Add(authCookie);

            // Redirect the user to the originally requested page
            // Response.Redirect(FormsAuthentication.GetRedirectUrl(userNameTxt, false));
        }

        // Extract the forms authentication cookie
        string cookieName = FormsAuthentication.FormsCookieName;
        HttpCookie authCookie2 = Context.Request.Cookies[cookieName];

        if (null == authCookie2)
        {
            // There is no authentication cookie.
            return;
        }

        //Add the following code to extract and decrypt the authentication ticket from the forms authentication cookie.
        FormsAuthenticationTicket authTicket2 = null;
        try
        {
            authTicket2 = FormsAuthentication.Decrypt(authCookie2.Value);
        }
        catch (Exception ex)
        {
            // Log exception details (omitted for simplicity)
            return;
        }

        if (null == authTicket2)
        {
            // Cookie failed to decrypt.
            return;
        }

        //Add the following code to parse out the pipe separate list of role names attached to the ticket when the user was originally authenticated.
        // When the ticket was created, the UserData property was assigned a
        // pipe delimited string of role names.
        string[] roles2 = authTicket2.UserData.Split(new char[] { '|' });

        //Add the following code to create a FormsIdentity object with the user name obtained from the ticket name and a GenericPrincipal object that contains this identity together with the user's role list.
        // Create an Identity object
        FormsIdentity id = new FormsIdentity(authTicket2);

        // This principal will flow throughout the request.
        GenericPrincipal principal = new GenericPrincipal(id, roles2);
        // Attach the new principal object to the current HttpContext object
        Context.User = principal;
    }
コード例 #41
0
ファイル: Win32Sec.cs プロジェクト: Robin--/Warewolf
    public bool IsWarewolfAuthorised(string privilege, string userName, string resourceGuid)
    {
        userName = CleanUser(userName);

        IPrincipal identity;
        try
        {
            identity = new WindowsPrincipal(new WindowsIdentity(userName));
        }
        catch (Exception)
        {
            var groups = GetLocalUserGroupsForTaskSchedule(userName);
            var tmp = new GenericIdentity(userName);
            identity = new GenericPrincipal(tmp, groups.ToArray());
        }

        if (_authorizationService.IsAuthorized(identity, AuthorizationContext.Execute, resourceGuid))
        {
            return true;
        }

        return false;
    }