protected void Application_AuthenticateRequest(Object sender, EventArgs e) { if (Request.IsAuthenticated == true) { HttpCookie authenCookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName); if (authenCookie == null) { FormsAuthentication.SignOut(); HttpContext.Current.User = null; return; } FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authenCookie.Value); FormsIdentity id = new FormsIdentity(ticket); UserToken token = SiteSecurity.GetToken(ticket.Name); if (token != null) { GenericPrincipal principal = new GenericPrincipal(id, new string[] {token.Role}); HttpContext.Current.User = principal; } else { FormsAuthentication.SignOut(); HttpContext.Current.User = null; } } }
/// <summary> /// Handles the AuthenticateRequest event of the context control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void context_AuthenticateRequest(object sender, EventArgs e) { HttpApplication context = sender as HttpApplication; if (IsRequestingBasic(context)) { HttpCookie cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie != null) { FormsIdentity fi = new FormsIdentity(FormsAuthentication.Decrypt(cookie.Value)); context.Context.User = new RolePrincipal(fi); // Already authenticated with FormsAuth } else { string authHeader = GetAuthHeader(context); if (!string.IsNullOrEmpty(authHeader)) { if (authHeader.StartsWith("basic ", StringComparison.InvariantCultureIgnoreCase)) { string userNameAndPassword = Encoding.Default.GetString( Convert.FromBase64String(authHeader.Substring(6))); string[] parts = userNameAndPassword.Split(':'); DoAuth(context, parts[0], parts[1]); } } } } //else if (IsRequestingPostAuth(context)) //{ // DoAuth(context, context.Request.Form["_username"], context.Request.Form["_password"]); //} }
protected void Application_AuthenticateRequest(object sender, EventArgs e) { string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = Context.Request.Cookies[cookieName]; if (authCookie == null) { return; } FormsAuthenticationTicket authTicket; try { authTicket = FormsAuthentication.Decrypt(authCookie.Value); } catch (Exception) { return; } if (authTicket == null) { return; } string[] roles = authTicket.UserData.Split(new [] { '|' }); var id = new FormsIdentity(authTicket); Context.User = new GenericPrincipal(id, roles); }
/// <summary> /// 创建登录用户的票据信息 /// </summary> /// <param name="strUserName"></param> public static string CreateLoginUserTicket(string userId) { DateTime loginTime = DateTime.Now;//用户的登录时间 //构造Form验证的票据信息 ///把登录时间和用户ID写进Cookie中,后面可以用于判断用户的登录时间间隔 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userId, DateTime.Now, DateTime.Now.AddMinutes(90), true, string.Format("{0}:{1}", userId, loginTime), FormsAuthentication.FormsCookiePath); string ticString = FormsAuthentication.Encrypt(ticket); //把票据信息写入Cookie和Session //SetAuthCookie方法用于标识用户的Identity状态为true HttpContext.Current.Response.Cookies.Add(new HttpCookie("UserLoginCookieToken", ticString)); FormsAuthentication.SetAuthCookie(userId, true); HttpContext.Current.Session["USER_LOGON_TICKET"] = ticString; //重写HttpContext中的用户身份,可以封装自定义角色数据; //判断是否合法用户,可以检查:HttpContext.User.Identity.IsAuthenticated的属性值 string[] roles = ticket.UserData.Split(','); IIdentity identity = new FormsIdentity(ticket); IPrincipal principal = new GenericPrincipal(identity, roles); HttpContext.Current.User = principal; return ticString;//返回票据 }
protected void Application_PostAuthenticateRequest(object sender, EventArgs e) { var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie == null) { HttpContext.Current.Request.Cookies.Remove(".ASPXTOKEN"); HttpContext.Current.Request.Cookies.Remove(".ASPXROLES"); return; } var ticket = FormsAuthentication.Decrypt(authCookie.Value); if (ticket == null) { return; } var formsIdentity = new FormsIdentity(ticket); var claimsIdentity = new ClaimsIdentity(formsIdentity); var rolesCookie = HttpContext.Current.Request.Cookies[".ASPXROLES"]; if (rolesCookie != null) { var ticketRoles = FormsAuthentication.Decrypt(rolesCookie.Value); if (ticketRoles != null) { var roles = JsonConvert.DeserializeObject<string[]>(ticketRoles.UserData); foreach (var role in roles) { claimsIdentity.AddClaim( new Claim(ClaimTypes.Role, role)); } } } var principal = new ClaimsPrincipal(claimsIdentity); HttpContext.Current.User = principal; }
void context_AuthenticateRequest(object sender, EventArgs e) { //判断是否已经登录,即有authTicket if (!HttpContext.Current.Request.IsAuthenticated) { return; } FormsAuthenticationTicket formsAuthTicket = UserInfo.FormsAuthTicket; //角色 string roleValue = UserInfo.FormsAuthUserData(formsAuthTicket).First(); string[] roles = new string[1]; switch (roleValue) { case "0": roles[0] = "考生"; break; case "1": roles[0] = "考官"; break; case "2": roles[0] = "管理员"; break; default: roles[0] = "匿名用户"; break; } // Create an Identity object var id = new FormsIdentity(formsAuthTicket); // This principal will flow throughout the request. var principal = new GenericPrincipal(id, roles); // Attach the new principal object to the current HttpContext object HttpContext.Current.User = principal; }
public void Null () { FormsIdentity identity = new FormsIdentity (null); Assert.AreEqual ("Forms", identity.AuthenticationType, "AuthenticationType"); Assert.IsTrue (identity.IsAuthenticated, "IsAuthenticated"); Assert.IsNull (identity.Ticket, "Ticket"); }
protected void Application_AuthenticateRequest(Object sender, EventArgs e) { // Extract the forms authentication cookie string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = Context.Request.Cookies[cookieName]; //if(authCookie.Name == "gigs") if(null == authCookie) { // There is no authentication cookie. return; } FormsAuthenticationTicket authTicket = null; try { authTicket = FormsAuthentication.Decrypt(authCookie.Value); } catch(Exception ex) { // Log exception details (omitted for simplicity) return; } if (null == authTicket) { // Cookie failed to decrypt. return; } // When the ticket was created, the UserData property was assigned // a pipe delimited string of role names. string[] roles = new string[2]; roles[0] = "user"; // Create an Identity object FormsIdentity id = new FormsIdentity( authTicket ); // This principal will flow throughout the request. GenericPrincipal principal = new GenericPrincipal(id, roles); // Attach the new principal object to the current HttpContext object Context.User = principal; }
protected void Application_AuthenticateRequest(object sender, EventArgs e) { if (HttpContext.Current.User != null) { if (HttpContext.Current.User.Identity.AuthenticationType == "Forms") { //--get the ticket System.Web.Security.FormsIdentity id = (System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity; FormsAuthenticationTicket ticket = id.Ticket; //--get the stored user data spliced (User Id|User Role) string[] userData = ticket.UserData.Split('|'); string userId = userData[0]; string userName = userData[1]; string userFirst = userData[2]; string userLast = userData[3]; string userEmail = userData[4]; if (userData.Length >= 6) { GroupRoleEnum userRole = GroupRoleEnum.member; try { userRole = EnumExtensions.EnumParse <GroupRoleEnum>(userData[5]); } catch (Exception) { } RaceDayUser user = new RaceDayUser(id, userId, userRole, userName, userFirst, userLast, userEmail, ticket.IsPersistent); HttpContext.Current.User = user; } } } }
protected void Application_AuthenticateRequest(object sender, EventArgs e) { var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { try { var ticket = FormsAuthentication.Decrypt(authCookie.Value); //var indexOfRole = ticket.Name.LastIndexOf('_') + 1; //var arr = ticket.Name.Split('|'); // string name = arr[0]; //ticket.Name.Substring(indexOfRole, ticket.Name.Length - indexOfRole); string role = ticket.UserData; // ticket.Name.Substring(0, indexOfRole - 1); //foreach (var role in user.Roles) //{ // claimsIdentity.AddClaim( // new Claim(ClaimTypes.Role, role)); //} // ticket.Name = name; FormsIdentity formsIdentity = new FormsIdentity(ticket); ClaimsIdentity claimsIdentity = new ClaimsIdentity(formsIdentity); claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, role)); ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity); HttpContext.Current.User = claimsPrincipal; } catch { HttpContext.Current.User = null; } } }
protected void Application_AuthenticateRequest(object sender, EventArgs e) { HttpCookie cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie == null) { return; } FormsAuthenticationTicket ticket = null; try { ticket = FormsAuthentication.Decrypt(cookie.Value); } catch (Exception) { return; } if (ticket == null) { return; } string role = ticket.UserData; Trace.Write("Role: " + role); FormsIdentity id = new FormsIdentity(ticket); GenericPrincipal principal = new GenericPrincipal(id, new string[] { role }); Context.User = principal; }
public void Identity () { FormsIdentity identity = new FormsIdentity (ticket); Assert.AreEqual ("Forms", identity.AuthenticationType, "AuthenticationType"); Assert.IsTrue (identity.IsAuthenticated, "IsAuthenticated"); Assert.AreEqual ("mine", identity.Name, "Name"); Assert.IsTrue (Object.ReferenceEquals (ticket, identity.Ticket), "Ticket"); }
public ActionResult InsertPicture(string authToken, HttpPostedFileBase httpPostedFile) { //Workaround for flash cookie bug //http://stackoverflow.com/questions/1729179/uploadify-session-and-authentication-with-asp-net-mvc //http://geekswithblogs.net/apopovsky/archive/2009/05/06/working-around-flash-cookie-bug-in-asp.net-mvc.aspx var ticket = FormsAuthentication.Decrypt(authToken); if (ticket == null) return Json(new { success = false, error = "No token provided"}); var identity = new FormsIdentity(ticket); if (!identity.IsAuthenticated) return Json(new { success = false, error = "User is not authenticated" }); var customer = ((FormsAuthenticationService)_authenticationService).GetAuthenticatedCustomerFromTicket(ticket); if (!_permissionService.Authorize(StandardPermissionProvider.UploadPictures, customer)) return Json(new { success = false, error = "User doesn't have required permissions" }); byte[] pictureBinary = httpPostedFile.GetPictureBits(); //TODO: find a better solution: little hack here //'Uploadify' component uploads all files with "application/octet-stream" mime type //that's why we manually update it here //http://www.sfsu.edu/training/mimetype.htm string contentType = httpPostedFile.ContentType; string fileExtension = Path.GetExtension(httpPostedFile.FileName); if (!String.IsNullOrEmpty(fileExtension)) fileExtension = fileExtension.ToLowerInvariant(); switch (fileExtension) { case ".bmp": contentType = "image/bmp"; break; case ".gif": contentType = "image/gif"; break; case ".jpeg": case ".jpg": case ".jpe": case ".jfif": case ".pjpeg": case ".pjp": contentType = "image/jpeg"; break; case ".png": contentType = "image/png"; break; case ".tiff": case ".tif": contentType = "image/tiff"; break; default: break; } var picture = _pictureService.InsertPicture(pictureBinary, contentType, null, true); return Json(new { success = true, pictureId = picture.Id, imageUrl = _pictureService.GetPictureUrl(picture, 100) }); }
public string GetUserLogin(FormsIdentity identity) { if (identity == null) { throw new ArgumentNullException("identity"); } return identity.Ticket.Name; }
public void SetRoles_ShouldTransferRolesOnUserDataToGenericPrincipal() { var identity = new FormsIdentity(new FormsAuthenticationTicket(1, ObjectId.GenerateNewId().ToString(), DateTime.Now, DateTime.Now.AddMinutes(20), false, Role.Admin)); SetupMockParameters(identity); _autoMoqer.Resolve<SessionAuthentication>().SetRoles(); _autoMoqer.GetMock<HttpContextBase>().VerifySet(x => x.User = It.Is<GenericPrincipal>(c => c.Identity == identity && c.IsInRole(Role.Admin)), Times.Once()); }
public void Ticket () { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (3, "mine", DateTime.MinValue, DateTime.Now.AddSeconds (-1), false, "data", "path"); FormsIdentity identity = new FormsIdentity (ticket); Assert.AreEqual ("Forms", identity.AuthenticationType, "AuthenticationType"); Assert.IsTrue (identity.IsAuthenticated, "IsAuthenticated"); Assert.AreEqual ("mine", identity.Name, "Name"); Assert.IsNotNull (identity.Ticket, "Ticket"); }
protected void Application_AuthenticateRequest(Object sender, EventArgs e) { if (Csla.ApplicationContext.User != null && Csla.ApplicationContext.User.Identity.IsAuthenticated && Csla.ApplicationContext.User.Identity is FormsIdentity) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Request.Cookies.Get(FormsAuthentication.FormsCookieName).Value); FormsIdentity id = new FormsIdentity(ticket); var principal = new SamplePrincipal(id.Name, id.Ticket.UserData); Csla.ApplicationContext.User = principal; } }
protected void Application_AuthenticateRequest(object sender, EventArgs e) { HttpCookie authenticationCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authenticationCookie != null) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authenticationCookie.Value); FormsIdentity identity = new FormsIdentity(ticket); HttpContext.Current.User = new GenericPrincipal(identity, ticket.UserData.Split(',')); } }
// public UsuarioAutenticado(System.Web.Security.FormsIdentity fIdentity) { string[] usuarioData = fIdentity.Ticket.Name.Split('|'); UsuarioID = usuarioData[0]; Nombre = usuarioData[1]; SucursalID = usuarioData[2]; ClienteID = usuarioData[3]; PlanID = usuarioData[4]; RolID = fIdentity.Ticket.UserData; //int.Parse( }
protected void Application_AuthenticateRequest(Object sender, EventArgs e) { var authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie == null || authCookie.Value == "") return; var authTicket = FormsAuthentication.Decrypt(authCookie.Value); var formsIdentity = new FormsIdentity(authTicket); var roles = authTicket.UserData.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries); HttpContext.Current.User = new GenericPrincipal(formsIdentity, roles); }
public ActionResult Login(LoginViewModel model) { // FormsAuthentication.SetAuthCookie(model.Email, false, FormsAuthentication.FormsCookiePath); // HttpContext.User.Identity.Name = "sdf"; MyPrincipal principal = new MyPrincipal(model.Email,model.Password); if (!principal.Identity.IsAuthenticated) { } else { FormsAuthentication.SetAuthCookie(model.Email, false, FormsAuthentication.FormsCookiePath); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(model.Email, false, 5); FormsIdentity identy = new FormsIdentity(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); Response.Cookies.Add(cookie); //User.Identity. System.Web.HttpContext.Current.User = principal; // 如果用户通过验证,则将用户信息保存在缓存中,以备后用 // 在实际中,朋友们可以尝试使用用户验证票的方式来保存用户信息,这也是.NET内置的用户处理机制 // HttpContext.GetOwinContext().Authentication. // var Muser = User as principal; // User = principal; Hashtable userMessage = new Hashtable(); userMessage.Add("UserID", model.Email); userMessage.Add("UserPassword", model.Password); //Cache CA = new Cache(); //CA.Insert("UserMessage", userMessage); System.Web.HttpContext.Current.Cache.Insert("UserMessage", userMessage); //System.Web.HttpContext.Current.Cache.Insert() // Cache.Insert("UserMessage", userMessage); } // HttpContext.GetOwinContext().Authentication.User.Identity.IsAuthenticated // User.Identity.u UserB.InsertUser(new User { Name = "shens" }); //if (!ModelState.IsValid) //{ // return View(); //} return View("XuLogin"); // this.RedirectToAction("xulogin","account") }
/// <summary> /// Sets the current user for unit tests. /// </summary> /// <param name="userName">The user to become the current one.</param> /// <param name="roleNameList">The roles the current user will be in. The parameter is ignored by this security provider; /// the role provider set for the application (in <i>Web.Config</i>) will be used to retrieve roles.</param> public override void SetUser(string userName, string roleNameList) { HttpRequest request = new HttpRequest("", "http://www.bits4finance.com", ""); HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter())); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 2, userName, DateTime.Now, DateTime.Now.AddMinutes(30), false, "", "/TotalGiro"); IIdentity identity = new FormsIdentity(ticket); IPrincipal user = new RolePrincipal(identity); Thread.CurrentPrincipal = user; HttpContext.Current.User = user; }
public string GetUserRoleName(FormsIdentity identity) { if (identity == null) { throw new ArgumentNullException("identity"); } ParseData(identity.Ticket.UserData, out _userId, out _userRoleName); return _userRoleName; }
protected override bool AuthorizeCore(HttpContextBase httpContext) { //If not authenticated, it might be a request from flash in Firefox, so get the auth token passed in to create Identity if (!httpContext.Request.IsAuthenticated) { var token = httpContext.Request.Params[TokenKey]; if (token != null) { var ticket = FormsAuthentication.Decrypt(token); if (ticket != null) { var identity = new FormsIdentity(ticket); httpContext.User = new GenericPrincipal(identity, null); //this doesn't need to be a UserPrincipal, because that will happen below } } } if (!httpContext.Request.IsAuthenticated) return false; // If it's not a UserPrincipal, we need to create it (b/c this happens before BaseController.OnAuthorization) if (!(httpContext.User is UserPrincipal)) { User user = null; if (httpContext.User.Identity.IsAuthenticated && httpContext.User.Identity.AuthenticationType == "Forms") { using (var db = ObjectFactory.GetInstance<SqlConnection>()) { db.Open(); var userService = new UserService(db, Cache); user = userService.GetByUsername(httpContext.User.Identity.Name); } if (user == null || user.IsDeleted) return false; } else { user = new User(); } var identity = httpContext.User != null ? httpContext.User.Identity : new GenericIdentity(user.Username ?? string.Empty); httpContext.User = new UserPrincipal(user, identity); Thread.CurrentPrincipal = httpContext.User; } var userObject = httpContext.User as UserPrincipal; return !RequireAdmin || userObject.IsAdmin; }
public void GetIdentityIsAuthenticated() { // unauthenticated user FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, "cyberkruz", DateTime.Now, DateTime.Now.AddDays(30), true, "4", FormsAuthentication.FormsCookiePath); FormsIdentity ident = new FormsIdentity(ticket); HttpContext.Current.User = new GenericPrincipal(ident, new string[0]); var identity = CustomAuthentication.GetIdentity(); Assert.IsTrue(identity.IsAuthenticated); Assert.AreEqual(identity.Username, "cyberkruz"); Assert.AreEqual(identity.UserId, 4); }
protected void Application_AuthenticateRequest(Object sender, EventArgs e) { string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = Context.Request.Cookies[cookieName]; if (authCookie != null) { //用户,角色设置 FormsAuthenticationTicket authTicket = null; authTicket = FormsAuthentication.Decrypt(authCookie.Value); string[] roles = authTicket.UserData.Split(new char[] { ',' });//如果存取多个角色,我们把它分解 FormsIdentity id = new FormsIdentity(authTicket); GenericPrincipal principal = new GenericPrincipal(id, roles); Context.User = principal;//存到HttpContext.User中 } }
protected void Application_AuthenticateRequest(object sender, EventArgs e) { string cookie = FormsAuthentication.FormsCookieName; HttpCookie httpCookie = Context.Request.Cookies[cookie]; if (httpCookie == null) return; FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(httpCookie.Value); if (ticket == null || ticket.Expired) return; FormsIdentity identity = new FormsIdentity(ticket); UserData udata = UserData.CreateUserData(ticket.UserData); AuthenticationProjectPrincipal principal = new AuthenticationProjectPrincipal(identity, udata); Context.User = principal; }
protected void Application_AuthenticateRequest(object sender, EventArgs e) { if (HttpContext.Current.User != null) { if (HttpContext.Current.User.Identity.AuthenticationType == "Forms") { System.Web.Security.FormsIdentity id = (System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity; FormsAuthenticationTicket ticket = id.Ticket; // Get Facebook information // Facebook.FacebookConnection fb = new Facebook.FacebookConnection(id); HttpContext.Current.User = fb.GetFacebookUser(ticket.Name); } } }
public FormsIdentityWrapper(IIdentity identity) { if(identity == null) { throw new ArgumentNullException("identity"); } var formsIdentity = identity as FormsIdentity; if(formsIdentity == null) { throw new ArgumentException("identity"); } _identity = formsIdentity; }
/// <summary> /// This changes the behavior of AuthorizeCore so that it will only authorize /// users if a valid token is submitted with the request. /// </summary> protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { var token = httpContext.Request.Params[TokenKey]; if (token != null) { var ticket = FormsAuthentication.Decrypt(token); if (ticket != null) { var identity = new FormsIdentity(ticket); var roles = System.Web.Security.Roles.GetRolesForUser(identity.Name); var principal = new GenericPrincipal(identity, roles); httpContext.User = principal; } } return base.AuthorizeCore(httpContext); }
public void Application_AuthenticateRequest(Object sender, EventArgs e) { if (HttpContext.Current.User != null) { if (HttpContext.Current.User.Identity.IsAuthenticated) { string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = Context.Request.Cookies[cookieName]; if (null == authCookie) { return; } FormsAuthenticationTicket ticket = null; try { ticket = FormsAuthentication.Decrypt(authCookie.Value); } catch { return; } if (null == ticket) { return; } ApplicationModelRepositoy ApplicationService = new ApplicationModelRepositoy(); List<approles> listaRoles = ApplicationService.GetRolesForUser(HttpContext.Current.User.Identity.Name); string[] roles = new string[listaRoles.Count]; int i = 0; foreach (approles r in listaRoles) { roles[i] = r.rolename; i++; } FormsIdentity id = new FormsIdentity(ticket); CustomPrincipal p = new CustomPrincipal(id, roles); Context.User = p; } } }
void Application_AuthenticateRequest(object sender, EventArgs e) { HttpApplication app = (HttpApplication)sender; HttpContext ctx = app.Context; //获取本次Http请求的HttpContext对象 if (ctx.User != null) { if (ctx.Request.IsAuthenticated == true) //验证过的一般用户才能进行角色验证 { System.Web.Security.FormsIdentity fi = (System.Web.Security.FormsIdentity)ctx.User.Identity; System.Web.Security.FormsAuthenticationTicket ticket = fi.Ticket; //取得身份验证票 string userData = ticket.UserData; //从UserData中恢复role信息 string[] roles = userData.Split(','); //将角色数据转成字符串数组,得到相关的角色信息 ctx.User = new System.Security.Principal.GenericPrincipal(fi, roles); //这样当前用户就拥有角色信息了 } } }
public void CoockieParser_Test() { //Arange const string coockieData = "1,TestRole"; var parser = new CookieParser(); var indentity = new FormsIdentity( new FormsAuthenticationTicket( 1, "TestLogin", new DateTime(1,1,1), new DateTime(1,1,1), false, coockieData)); var badIdentity = new FormsIdentity( new FormsAuthenticationTicket( 1, "Test", new DateTime(1, 1, 1), new DateTime(1, 1, 1), false, "someBadCoockieData")); //Act var actualId = parser.GetUserId(indentity); var actualRoleName = parser.GetUserRoleName(indentity); var actualLogin = parser.GetUserLogin(indentity); //Assert Assert.Throws<ArgumentNullException>(() => parser.GetUserId(null)); Assert.Throws<ArgumentNullException>(() => parser.GetUserRoleName(null)); Assert.That(actualId == 1); Assert.That(actualRoleName == "TestRole"); Assert.That(actualLogin == "TestLogin"); Assert.Throws<CookieParserException>(() => parser.GetUserId(badIdentity)); Assert.Throws<CookieParserException>(() => parser.GetUserRoleName(badIdentity)); }
protected void Application_AuthenticateRequest(Object sender, EventArgs e) { if (HttpContext.Current.User != null) { if (Request.IsAuthenticated == true) { // Debug#1 FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies[FormsAuthentication.FormsCookieName].Value); // In this case, ticket.UserData = "Admin" string role = db.tbl_Users.SingleOrDefault(x => x.Username == Context.User.Identity.Name).tbl_Roles.RoleName; string[] roles = new string[1] { role }; FormsIdentity id = new FormsIdentity(ticket); Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles); // Debug#2 } } }
/// <summary> /// Authorize /// /// Required member of the IAuthorizationService provider returns true/false to indicate /// if user has been authorized /// </summary> /// <param name="httpContect"></param> /// <returns></returns> /// public bool Authorize(HttpContextBase httpContext) { if (!String.IsNullOrEmpty(RaceDayConfiguration.Instance.DebugUser)) { FormsAuthenticationTicket ticket = CreateFormsTicket(RaceDayConfiguration.Instance.DebugUser, "", Int32.MaxValue); System.Web.Security.FormsIdentity id = new System.Web.Security.FormsIdentity(ticket); FacebookUser fbUser = FacebookUser.Create(id, null); fbUser.id = ticket.Name; fbUser.first_name = "Johnny"; fbUser.last_name = "Test"; fbUser.email = "*****@*****.**"; httpContext.User = fbUser; return(true); } if (!String.IsNullOrEmpty(httpContext.Request.QueryString["code"])) { String redirectUrl = String.Concat(httpContext.Request.Url.Scheme, "://", httpContext.Request.Url.Host, (!httpContext.Request.Url.IsDefaultPort ? ":" + httpContext.Request.Url.Port : ""), httpContext.Request.Path); FacebookConnection fbObject = new FacebookConnection(); fbObject.GetFacebookAccessToken(redirectUrl, httpContext.Request.QueryString["code"]); fbObject.GetFacebookUserId(); FormsAuthenticationTicket ticket = CreateFormsTicket(fbObject.user_id, fbObject.access_token, fbObject.token_expires); System.Web.Security.FormsIdentity id = new System.Web.Security.FormsIdentity(ticket); FacebookConnection fb = new FacebookConnection(id); httpContext.User = fb.GetFacebookUser(ticket.Name); httpContext.Response.Redirect(httpContext.Request.Path); return(true); } return(IsFacebookAuthorized(httpContext)); }
/// <devdoc> /// Constructor. /// </devdoc> protected FormsIdentity(FormsIdentity identity) : base(identity) { _Ticket = identity._Ticket; }