コード例 #1
0
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            var request = filterContext.HttpContext.Request;
            var authorization = request.Headers["Authorization"];

            // No authorization, do nothing
            if (string.IsNullOrEmpty(authorization) || !authorization.Contains("Basic"))
                return;

            // Parse username and password from header
            byte[] encodedDataAsBytes = Convert.FromBase64String(authorization.Replace("Basic ", ""));
            string value = Encoding.ASCII.GetString(encodedDataAsBytes);

            string username = value.Substring(0, value.IndexOf(':'));
            string password = value.Substring(value.IndexOf(':') + 1);

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                filterContext.Result = new HttpUnauthorizedResult("Username or password missing");
                return;
            }

            // Validate username and password
            var user = AuthenticatedUsers.Users.FirstOrDefault(u => u.Name == username && u.Password == password);

            if (user == null)
            {
                filterContext.Result = new HttpUnauthorizedResult("Invalid username and password");
                return;
            }

            // Set principal
            filterContext.Principal = new GenericPrincipal(user, user.Roles);
        }
コード例 #2
0
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            IIdentity ident = filterContext.Principal.Identity;

            if (!ident.IsAuthenticated || !(ident.Name == "admin" || ident.Name == "alex"))
                filterContext.Result = new HttpUnauthorizedResult(); //доступ к данному ресурсу для пользовател запрещен
        }
コード例 #3
0
        protected override void OnAuthentication(AuthenticationContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                IEnumerable<string> permissions = null;

                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(ConfigurationManager.AppSettings["BaseUrl"]);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    HttpResponseMessage response = client.GetAsync("api/security/GetPermissionsForUser?username=" + User.Identity.Name).Result;

                    if (response.IsSuccessStatusCode)
                    {
                        permissions = response.Content.ReadAsAsync<IEnumerable<string>>().Result;
                    }
                }

                var id = ClaimsPrincipal.Current.Identities.First();
                if (permissions != null)
                {
                    foreach (var permission in permissions)
                    {
                        id.AddClaim(new Claim(ClaimTypes.Role, permission));
                    }
                }
            }
        }
コード例 #4
0
ファイル: SDCController.cs プロジェクト: teo-mateo/sdc
        protected override void OnAuthentication(AuthenticationContext filterContext)
        {
            if (filterContext.Principal.Identity.IsAuthenticated && Session["UserInfo"] == null)
                WebSecurity.Logout();

            base.OnAuthentication(filterContext);
        }
コード例 #5
0
 public void OnAuthentication(AuthenticationContext filterContext)
 {
     filterContext.Principal = new GenericPrincipal(
                                 filterContext.HttpContext.User.Identity,
                                 new[] {"Admin"}
                               );
 }
コード例 #6
0
        public void OnAuthentication(System.Web.Mvc.Filters.AuthenticationContext filterContext)
        {
            SessionSecurityToken sst = null;

            try
            {
                if (FederatedAuthentication.SessionAuthenticationModule.TryReadSessionTokenFromCookie(out sst))
                {
                    var ticketClaim = sst.ClaimsPrincipal.Claims.FirstOrDefault(c => c.Type == "token");

                    // validate that the cookie wasn't expired
                    if (ticketClaim != null && !IsExpired(ticketClaim.Value))
                    {
                        filterContext.Principal = sst.ClaimsPrincipal;

                        if (BaseController.CurrentUser == null)
                        {
                            var token = (sst.ClaimsPrincipal.Identity as ClaimsIdentity).FindFirst("token")?.Value;
                            BaseController.CurrentUser = AuthProviderHost.PrimaryAuthProvider.GetAccount(token, null);
                        }
                    }
                    else
                    {
                        // clear the cookie so we don't have to do this every time
                        SignOut();
                    }
                }
            }
            catch
            {
                // unfortunately, "TryReadSession" throws.  often.
            }
        }
コード例 #7
0
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            HttpRequestBase request = filterContext.HttpContext.Request;
            string[] values = request.Headers.GetValues("Authorization");

            if (values == null || values.Length != 1)
            {
                // No authentication was attempted (for this authentication method).
                // Do not set either Principal (which would indicate success) or Result (which would indicate an error).
                return;
            }

            string value = values[0];

            if (value == null || !value.StartsWith("Basic "))
            {
                // No authentication was attempted (for this authentication method).
                // Do not set either Principal (which would indicate success) or Result (which would indicate an error).
                return;
            }

            string encodedCredentials = value.Substring("Basic ".Length);

            if (encodedCredentials != null)
            {
                encodedCredentials = encodedCredentials.TrimStart(' ');
            }

            if (String.IsNullOrEmpty(encodedCredentials))
            {
                // Authentication was attempted but failed. Set Result to indicate an error.
                filterContext.Result = new HttpStatusCodeResult(401, "Missing credentials");
                return;
            }

            Tuple<string, string> userNameAndPasword = ExtractUserNameAndPassword(encodedCredentials);

            if (userNameAndPasword == null)
            {
                // Authentication was attempted but failed. Set Result to indicate an error.
                filterContext.Result = new HttpStatusCodeResult(401, "Invalid credentials");
                return;
            }

            string userName = userNameAndPasword.Item1;
            string password = userNameAndPasword.Item2;

            IPrincipal principal = Authenticate(userName, password);

            if (principal == null)
            {
                // Authentication was attempted but failed. Set Result to indicate an error.
                filterContext.Result = new HttpStatusCodeResult(401, "Invalid username or password");
            }
            else
            {
                // Authentication was attempted and succeeded. Set Principal to the authenticated user.
                filterContext.Principal = principal;
            }
        }
コード例 #8
0
 public void OnAuthentication(AuthenticationContext context)
 {
     IIdentity ident = context.Principal.Identity;
     if (!ident.IsAuthenticated || !ident.Name.EndsWith("@google.com")) {
         context.Result = new HttpUnauthorizedResult();
     }
 }
コード例 #9
0
        protected virtual bool IsAuthenticated(AuthenticationContext filterContext, out IPrincipal user)
        {
            user = filterContext.Principal;
            if (null != user & user.Identity.IsAuthenticated)
            {
                return true;
            }

            AuthenticationHeaderValue token = this.GetAuthenticationHeaderValue(filterContext);
            if (null != token && token.Scheme == BasicAuthenticationScheme)
            {
                string credential = Encoding.Default.GetString(Convert.FromBase64String(token.Parameter));
                string[] split = credential.Split(':');
                if (split.Length == 2)
                {
                    string userName = split[0];
                    string password;
                    if (userAccounters.TryGetValue(userName, out password))
                    {
                        if (password == split[1])
                        {
                            GenericIdentity identity = new GenericIdentity(userName);
                            user = new GenericPrincipal(identity, new string[0]);
                            return true;
                        }
                    }
                }
            }
            return false;
        }
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            var user = filterContext.HttpContext.User;

            //Demo purpose only. The custom principal could be retrived via the current context.
            filterContext.Principal = new MyCustomPrincipal(filterContext.HttpContext.User.Identity, new[] { "Admin" }, "Red");
        }
コード例 #11
0
 public void OnAuthentication(AuthenticationContext context)
 {
     if (!Common.ChekSuperAdmin())
     {
         context.Result = new HttpUnauthorizedResult(); // mark unauthorized
     }
 }
コード例 #12
0
 public void OnAuthentication(AuthenticationContext filterContext)
 {
     System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
     System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
     log.Debug("Start: " + methodBase.Name);
     try
     {
         if (UserLogin.ValidateUserRequest())
         {
             filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Home" }, { "action", "Login" }, { "area", "" } });
         }
         else
         {
             string context = filterContext.Controller.ControllerContext.HttpContext.Request.Path;
             int UserID = Convert.ToInt32(filterContext.HttpContext.Session["UserID"]);
             string Role = MenuBinding.CheckURlAndGetUserRole(context, UserID);
             if (Role == null)
             {
                 filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Home" }, { "action", "Index" }, { "area", "" } });
             }
             filterContext.Controller.ViewBag.Role = Role;
         }
     }
     catch (Exception ex)
     {
         log.Error("Error: " + ex);
     }
     log.Debug("End: " + methodBase.Name);
 }
コード例 #13
0
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            IIdentity ident = filterContext.Principal.Identity;

            if (!ident.IsAuthenticated)
                filterContext.Result = new HttpUnauthorizedResult();
        }
コード例 #14
0
 protected override void OnAuthentication(AuthenticationContext filterContext)
 {
     base.OnAuthentication(filterContext);
     try
     {
         string action = filterContext.RouteData.Values["action"].ToString();
         if (string.Equals(action, "login", StringComparison.OrdinalIgnoreCase)) { return; }
         if (string.Equals(action, "logout", StringComparison.OrdinalIgnoreCase)) { return; }
         if (Request.IsAuthenticated)
         {
             UserInfo user = JsonConvert.DeserializeObject<UserInfo>(User.Identity.Name);
             LoginUser = user;
             filterContext.HttpContext.Items.Add("currentUser", user);
         }
         else
         {
             Response.Redirect("/Admin/User/Login");
             filterContext.Result = new EmptyResult();
         }
     }
     catch (Exception ex)
     {
         Response.Redirect("/Admin/User/Login");
         filterContext.Result = new EmptyResult();
         throw ex;
     }
 }
コード例 #15
0
 public void OnAuthentication(AuthenticationContext filterContext)
 {
     if (!UserContext.User.IsAdmin)
     {
         filterContext.Result = new HttpUnauthorizedResult();
     }
 }
コード例 #16
0
 /// <summary>
 /// Sets the filterContext.HttpContext.User to the principal built 
 /// from the McoCitizen of the current McoSession (if there is any 
 /// McoCitizen in the session).
 /// </summary>
 /// <param name="filterContext">The context of the current 
 /// ActionFilter</param>
 public void OnAuthentication(AuthenticationContext filterContext)
 {
     McoCitizen citizen = McoSession.GetCitizen(filterContext.HttpContext);
     if (citizen != null)
     {
         filterContext.HttpContext.User = citizen.Principal;
     }
 }
コード例 #17
0
 public void OnAuthentication(AuthenticationContext filterContext)
 {
     var user = filterContext.HttpContext.User;
     if (user == null || !user.Identity.IsAuthenticated)
     {
         filterContext.Result = new HttpUnauthorizedResult();
     }
 }
コード例 #18
0
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            IIdentity ident = filterContext.Principal.Identity;
            var user = Storage.currentUser;

            if (!ident.IsAuthenticated || user == null )
                filterContext.Result = new HttpUnauthorizedResult(); //доступ к данному ресурсу для пользовател запрещен
        }
コード例 #19
0
 public void OnAuthentication(AuthenticationContext filterContext)
 {
     if (filterContext == null || filterContext.Principal == null || filterContext.Principal.Identity == null ||
         !filterContext.Principal.Identity.IsAuthenticated)
     {
         filterContext.Result = new HttpUnauthorizedResult();
     }
 }
コード例 #20
0
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            if (SkipAuthentication(filterContext))
                return;

            if (!AuthenticateSuccess(filterContext))
                HandleUnauthenticated(filterContext);
        }
コード例 #21
0
 protected override void OnAuthentication(AuthenticationContext filterContext)
 {
     base.OnAuthentication(filterContext);
     var user= Session["user"] as User;
     if (user==null )
     {
         Response.Redirect("/Login");
     }
 }
コード例 #22
0
ファイル: SecurityCheck.cs プロジェクト: vzdesic/PZI
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            //In real life your custom principal might be retrieved via 
            //different source. i.e context/request etc.
            //We can also fill it from Session variable
            filterContext.Principal = filterContext.HttpContext.User;

            //TODO: Make some story around that.
        }
コード例 #23
0
		public void OnAuthentication(AuthenticationContext filterContext)
		{
			var credentialId = AuthenticationUtility.CredentialId;

			if(string.IsNullOrWhiteSpace(credentialId))
				filterContext.Principal = CredentialPrincipal.Empty;
			else
				filterContext.Principal = new CredentialPrincipal(new CredentialIdentity(credentialId, this.CredentialProvider));
		}
コード例 #24
0
        private bool SkipAuthentication(AuthenticationContext context)
        {
            var request = context.HttpContext.Request;

            if (request.AppRelativeCurrentExecutionFilePath.ToLower() == _loginAction || request.CurrentExecutionFilePath.ToLower() == _loginAction)
                return true;

            return _skipAuthentication(context);
        }
コード例 #25
0
        public virtual void OnAuthentication(System.Web.Mvc.Filters.AuthenticationContext filterContext)
        {
            var currentUser = filterContext.HttpContext.Session["user"] as Account;

            if (currentUser != null)
            {
                filterContext.Principal = new LocalPrincipal(new LocalIdentity(currentUser.Id, currentUser.Username, currentUser.EmailAddress));
            }
        }
コード例 #26
0
 public void OnAuthentication(AuthenticationContext filterContext)
 {
     if (!filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any() &&
         !filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any() &&
         UserContext.User == null)
     {
         filterContext.Result = new HttpUnauthorizedResult();
     }
 }
コード例 #27
0
        public void OnAuthentication(System.Web.Mvc.Filters.AuthenticationContext filterContext)
        {
            SessionSecurityToken sst = null;

            if (FederatedAuthentication.SessionAuthenticationModule.TryReadSessionTokenFromCookie(out sst))
            {
                filterContext.Principal = sst.ClaimsPrincipal;
            }
        }
コード例 #28
0
        private bool IsDefinedAllowAnonymous(AuthenticationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            return filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
                || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
        }
 public virtual void OnAuthentication(AuthenticationContext filterContext)
 {
     var ctx = filterContext.HttpContext.Request.GetOwinContext();
     var result = AsyncHelper.RunSync(() => ctx.Authentication.AuthenticateAsync(AuthenticationType));
     if (result != null &&
         result.Identity != null &&
         result.Identity.IsAuthenticated)
     {
         filterContext.Principal = new ClaimsPrincipal(result.Identity);
     }
 }
コード例 #30
0
 public void OnAuthentication(AuthenticationContext filterContext)
 {
     try
     {
         filterContext.Result = GetCodeResult(filterContext);
     }
     catch (Exception ex)
     {
         ErrorSignaler.SignalFromCurrentContext(ex);
         throw new BlogException(ex.Message, ex.InnerException);
     }
 }
コード例 #31
0
 public void OnAuthentication(AuthenticationContext filterContext)
 {
     IPrincipal user;
     if (this.IsAuthenticated(filterContext, out user))
     {
         filterContext.Principal = user;
     }
     else
     {
         this.ProcessUnauthenticatedRequest(filterContext);
     }
 }
コード例 #32
0
ファイル: DBSrvAuthAttribute.cs プロジェクト: naishan/SDDB
        //Methods--------------------------------------------------------------------------------------------------------------//

        public void OnAuthentication(AuthenticationContext context)
        {
            var filterResult = new DBResult
            {
                ActionName = context.RouteData.Values["action"].ToString(),
                ControllerName = context.RouteData.Values["controller"].ToString(),
                ServiceName = "DBSrvAuthAttribute",
                UserName = context.Principal.Identity.Name,
                UserHostAddress = context.HttpContext.Request.UserHostAddress
            };

            var dbRolesArray = dbRoles.Split(','); var isInRole = false;
            foreach (var dbRole in dbRolesArray)
            {
                if (context.Principal.IsInRole(dbRole)) 
                { 
                    isInRole = true; 
                    break;
                }
            }


            if (!context.HttpContext.Request.IsAuthenticated || (dbRoles != "" && !isInRole))
            {
                filterResult.StatusCode = HttpStatusCode.Conflict;
                filterResult.StatusDescription = 
                    "You are not logged in or request not authorized.\n" + 
                    "Try to log in again or contact SDDB administrator to obtain appropriate privileges.";
                Logger.LogResult(filterResult);
                context.HttpContext.Response.StatusCode = (int)filterResult.StatusCode;
                context.Result = new JsonResult()
                {
                    Data = new { Success = "False", responseText = filterResult.StatusDescription },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
                return;
            }

            if (ajaxRequired && !context.HttpContext.Request.IsAjaxRequest())
            {
                filterResult.StatusCode = HttpStatusCode.Gone;
                filterResult.StatusDescription = "Error 0101: AJAX request allowed only.";
                Logger.LogResult(filterResult);
                context.HttpContext.Response.StatusCode = (int)filterResult.StatusCode;
                context.Result = new JsonResult()
                {
                    Data = new { Success = "False", responseText = filterResult.StatusDescription },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
                return;
            }
        }
コード例 #33
0
ファイル: BaseController.cs プロジェクト: eeroom/zl.zlgw
        protected override void OnAuthentication(System.Web.Mvc.Filters.AuthenticationContext filterContext)
        {
            if (!this.User.Identity.IsAuthenticated)
            {
                var loginurl = GetLoginPage(null, false);
                filterContext.Result = this.Redirect(loginurl);
                return;
            }
            string id = this.User.Identity.Name;
            //System.Web.Security.FormsAuthentication.SetAuthCookie(this.User.Identity.Name, true);
            var userInfo = this.Session.GetValue(SessionIndex.UserInfo) as Model.UserInfo;

            if (userInfo == null)//session丢失或者过期,重新从数据库取
            {
                userInfo = this.BllUserInfo.GetById(Guid.Parse(id));
                this.Session.SetValue(SessionIndex.UserInfo, userInfo);
            }
            var lstMenu = Model.DTO.MenuInfo.GetList();

            this.ViewData["lstMenu"] = lstMenu;
        }
コード例 #34
-1
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                string WFCEOHeaderToken = "RF_USER";
                string userSSO = null;
                if (filterContext.HttpContext.Request.Headers[WFCEOHeaderToken] != null)
                    userSSO = HttpContext.Current.Request.Headers[WFCEOHeaderToken];

                if (!string.IsNullOrWhiteSpace(userSSO))
                    RFAuthHelper.SetRFAuthToken(userSSO, "RF_CEO");
            }
        }