本文整理汇总了C#中System.Web.Security.FormsAuthenticationTicket类的典型用法代码示例。如果您正苦于以下问题:C# FormsAuthenticationTicket类的具体用法?C# FormsAuthenticationTicket怎么用?C# FormsAuthenticationTicket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
FormsAuthenticationTicket类属于System.Web.Security命名空间,在下文中一共展示了FormsAuthenticationTicket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: LogOn
public ActionResult LogOn(LoginModel model, string returnUrl)
{
ViewBag.Message = "Please enter username and password for login.";
if (ModelState.IsValid)
{
User user = ValidateUser(model.username, model.password);
if (user != null)
{
var authTicket = new FormsAuthenticationTicket(1, model.username, DateTime.Now, DateTime.Now.AddMinutes(30), model.RememberMe,
"1");
string cookieContents = FormsAuthentication.Encrypt(authTicket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
{
Expires = authTicket.Expiration,
Path = FormsAuthentication.FormsCookiePath
};
Response.Cookies.Add(cookie);
if (!string.IsNullOrEmpty(returnUrl))
Response.Redirect(returnUrl);
return RedirectToAction("Index", "Dashboard");
}
else
{
ViewBag.Message = "The user name or password provided is incorrect. Please try again";
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
示例2: SignIn
public virtual void SignIn(Customer customer, bool createPersistentCookie)
{
var now = DateTime.UtcNow.ToLocalTime();
var ticket = new FormsAuthenticationTicket(
1 /*version*/,
_customerSettings.UsernamesEnabled ? customer.Username : customer.Email,
now,
now.Add(_expirationTimeSpan),
createPersistentCookie,
_customerSettings.UsernamesEnabled ? customer.Username : customer.Email,
FormsAuthentication.FormsCookiePath);
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.HttpOnly = true;
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
cookie.Secure = FormsAuthentication.RequireSSL;
cookie.Path = FormsAuthentication.FormsCookiePath;
if (FormsAuthentication.CookieDomain != null)
{
cookie.Domain = FormsAuthentication.CookieDomain;
}
_httpContext.Response.Cookies.Add(cookie);
_cachedCustomer = customer;
}
示例3: LogOn
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
Session["Notification"] = "";
if (ModelState.IsValid)
{
KIREIP.Core.Manager.UserManager CM = new KIREIP.Core.Manager.UserManager();
KIREIP.Core.DAL.Login usr = CM.LoginUser(model.UserName, model.Password);
if (usr != null)
{
FormsAuthentication.Initialize();
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, usr.UserName.ToString(), DateTime.Now, DateTime.Now.AddMinutes(30), model.RememberMe, FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
Response.Cookies.Add(cookie);
if ((!String.IsNullOrEmpty(returnUrl)) && returnUrl.Length > 1)
return Redirect(returnUrl);
else
{
return RedirectToAction("Index", "Message");
}
}
else
{
ModelState.AddModelError("", "Incorrect user name or password.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
示例4: login
private void login(string userName, string password)
{
Model.User userObj = Model.Repositories.UsersRepository.GetUserByCredentials(userName, password);
if (userObj == null)
return;
int userID = userObj.ID;
string userRoles = "";
foreach (Model.UserRole userRole in userObj.UserRoles)
{
if (userRoles == "")
userRoles = userRole.ID.ToString();
else
userRoles += "," + userRole.ID.ToString();
}
if (userRoles == "")
return;
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userID.ToString(), DateTime.Now,
DateTime.Now.AddMinutes(30), false,
userRoles,
FormsAuthentication.FormsCookiePath);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
Response.Cookies.Add(cookie);
string returnUrl = Request.QueryString["ReturnUrl"];
if (String.IsNullOrEmpty(returnUrl))
returnUrl = "Default.aspx";
Response.Redirect(returnUrl);
}
示例5: Login
/// <summary>
/// �û���¼����
/// </summary>
/// <param name="username">�û���</param>
/// <param name="roles">�û���ɫ</param>
/// <param name="isPersistent">�Ƿ�־�cookie</param>
public static void Login(string username, string roles, bool isPersistent)
{
DateTime dt = isPersistent ? DateTime.Now.AddMinutes(99999) : DateTime.Now.AddMinutes(60);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Ʊ�ݰ汾��
username, // Ʊ�ݳ�����
DateTime.Now, //����Ʊ�ݵ�ʱ��
dt, // ʧЧʱ��
isPersistent, // ��Ҫ�û��� cookie
roles, // �û����ݣ�������ʵ�����û��Ľ�ɫ
FormsAuthentication.FormsCookiePath);//cookie��׷��
//ʹ�û�����machine key����cookie��Ϊ�˰�ȫ����
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); //����֮���cookie
//��cookie��ʧЧʱ������Ϊ��Ʊ��tikets��ʧЧʱ��һ��
HttpCookie u_cookie = new HttpCookie("username", username);
if (ticket.IsPersistent)
{
u_cookie.Expires = ticket.Expiration;
cookie.Expires = ticket.Expiration;
}
//���cookie��ҳ��������Ӧ��
HttpContext.Current.Response.Cookies.Add(cookie);
HttpContext.Current.Response.Cookies.Add(u_cookie);
}
示例6: SignIn
public ActionResult SignIn(SignInViewModel logInViewModel)
{
if (ModelState.IsValid)
{
string errorMessage;
User user = _accountService.ValidateUser(logInViewModel.UserName, logInViewModel.Password, out errorMessage);
if (user != null)
{
SimpleSessionPersister.Username = user.Username;
SimpleSessionPersister.Roles = user.Roles.Select(x => x.Name).ToList();
if (logInViewModel.StayLoggedIn)
{
FormsAuthenticationTicket formsAuthenticationTicket = new FormsAuthenticationTicket(SimpleSessionPersister.Username, true, 10080);
string encrypt = FormsAuthentication.Encrypt(formsAuthenticationTicket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypt);
Response.Cookies.Add(cookie);
}
return RedirectToAction("Index", "Feed");
}
ModelState.AddModelError(string.Empty, errorMessage);
}
return View();
}
示例7: Authenticate
public HttpResponseMessage Authenticate()
{
var credentials = Request.Content.ReadAsStringAsync().Result;
var postData = JObject.Parse(credentials);
var username = postData["Username"].ToString().Trim();
var password = postData["Password"].ToString().Trim();
var match = DynamoDBConnection.Instance.GetUser(username);
if (match == null) {
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Unrecognized username or password");
}
var data = JObject.Parse(match["UserInfo"]);
var hashedPassword = data["Password"].ToString();
bool authenticated;
if (hashedPassword != "test") {
byte[] charArray = hashedPassword.Select(i => (byte)i).ToArray();
var passwordHash = new PasswordHash(charArray);
authenticated = passwordHash.Verify(password);
} else {
authenticated = true;
}
if (authenticated) {
var toReturn = new HttpResponseMessage(HttpStatusCode.OK);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(username, true, 525600);
var sessionKey = FormsAuthentication.Encrypt(ticket);
toReturn.Headers.Add("Set-Cookie", string.Format("session_id={0}; Path=/", sessionKey));
toReturn.Headers.Add("Set-Cookie", string.Format("user_id={0}; Path=/", username));
toReturn.Content = new StringContent(sessionKey.ToString());
return toReturn;
} else {
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Unrecognized username or password");
}
}
示例8: btnLogin_Click
protected void btnLogin_Click(object sender, EventArgs e)
{
Users _loginUser = _dal.VerifyPassword(txtUserName.Text, txtPassword.Text);
if (_loginUser == null)
lblerror.Text = "Invalid Login";
else
{
UserData userData = new UserData
{
fullName = _loginUser.firstName,
userName = _loginUser.LoweredUserName,
userId = _loginUser.UserId
};
string[] roles = new string[3];
if (_loginUser.canAdd == true)
roles[0] = "canAdd";
if (_loginUser.canDelete == true)
roles[1] = "canDelete";
if (_loginUser.canEdit == true)
roles[2] = "canEdit";
string _roles = String.Join(",", roles);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // ticket version
_loginUser.UserName, // authenticated username
DateTime.Now, // issueDate
DateTime.Now.AddMinutes(30), // expiryDate
true, // true to persist across browser sessions we want to be always for end user unless they log out.
_roles, // can be used to store additional user data
FormsAuthentication.FormsCookiePath); // the path for the cookie
// Encrypt the ticket using the machine key
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
// Add the cookie to the request to save it
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
lblerror.Text = "Success!";
// if its a player throw them into front end other wise fire them into the back end
if (_loginUser.accountType == Constants.playerGuid && _loginUser.accountType == Constants.adminGuid)
{
Response.Redirect("~/dashboard/dashboard.aspx");
}
else if (_loginUser.accountType == Constants.teamGuid && _loginUser.accountType == Constants.leagueGuid && _loginUser.accountType == Constants.clubGuid)
{
Response.Redirect("~/Backdoor/default.aspx");
}
}
}
示例9: Login
public ActionResult Login(LoginViewModel viewModel)
{
var apresentador = new LoginApresentador();
var requisicao = new LoginRequisicao
{
Email = viewModel.Email,
Senha = viewModel.Senha
};
this.loginExecutor.Apresentador = apresentador;
this.loginExecutor.Executar(requisicao);
if (apresentador.UsuarioExiste)
{
//create the authentication ticket
var authTicket = new FormsAuthenticationTicket(
1,
viewModel.Email, //user id
DateTime.Now,
DateTime.Now.AddMinutes(20), // expiry
true, //true to remember
"", //roles
"/"
);
//encrypt the ticket and add it to a cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);
return RedirectToAction("Index", "Blog");
}
return View();
}
示例10: Login
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var currentUser = clientService.GetClientByLoginAndPassword(model.Login, model.Password);
if(currentUser != null)
{
string name;
if (currentUser.FirstName != null)
name = currentUser.FirstName + " " + currentUser.LastName;
name = currentUser.Login;
var authTicket = new FormsAuthenticationTicket(
1,
currentUser.UserId.ToString(),
DateTime.Now,
DateTime.Now.AddMinutes(60),
true,
name
);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
HttpContext.Response.Cookies.Add(authCookie);
return RedirectToAction("Index", "Home");
}
}
return View(model);
}
示例11: Index
public ActionResult Index(BiscuitChief.Models.Login login, string ReturnUrl = "")
{
if (ModelState.IsValid)
{
bool isvalidlogin = Models.Login.ValidateLogin(login.UserName, login.Password);
if (isvalidlogin)
{
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, login.UserName, DateTime.Now, DateTime.Now.AddMinutes(30), true, "");
String cookiecontents = FormsAuthentication.Encrypt(authTicket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookiecontents) { Expires = authTicket.Expiration, Path = FormsAuthentication.FormsCookiePath };
Response.Cookies.Add(cookie);
if (!String.IsNullOrEmpty(ReturnUrl))
{ return Redirect(ReturnUrl); }
else
{ return Redirect("/"); }
}
else
{
FormsAuthentication.SignOut();
Session.Clear();
}
}
return View(login);
}
示例12: LogIn
public void LogIn(string username, string password)
{
if (username == "lvs" && password == "[email protected]")
{
FormsAuthentication.Initialize();
FormsAuthentication.SetAuthCookie(username, false);
var ticket = new FormsAuthenticationTicket(
1, // Ticket version
username, // Username associated with ticket
DateTime.Now, // Date/time issued
DateTime.Now.AddMinutes(30), // Date/time to expire
true, // "true" for a persistent user cookie
"", // User-data, in this case the roles
FormsAuthentication.FormsCookiePath);// Path cookie valid for
// Encrypt the cookie using the machine key for secure transport
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of auth cookie
hash); // Hashed ticket
// Set the cookie's expiration time to the tickets expiration time
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
// Add the cookie to the list for outgoing response
Response.Cookies.Add(cookie);
}
}
示例13: Index
public ActionResult Index(LoginViewModel login)
{
if (!ModelState.IsValid) return View();
if (!userRepo.ValidateUser(login))
{
ModelState.AddModelError("", "Incorrect username or password");
return View();
}
var authTicket = new FormsAuthenticationTicket(
1,
login.UserName,
DateTime.Now,
DateTime.Now.AddMinutes(20), // expiry
login.RememberMe,
"", //roles
"/"
);
//encrypt the ticket and add it to a cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);
return Redirect("UserHome");
}
示例14: AuthenticateUser
public static void AuthenticateUser(string userName, int userId, string firstName, bool createPersistenctCookie)
{
try
{
var userData = new WarehouseManagementUserData()
{
UserId = userId,
UserName = userName,
FirstName = firstName
};
var userDataString = WarehouseManagementUserData.Serialize(userData);
var authCookie = FormsAuthentication.GetAuthCookie(userName, createPersistenctCookie);
var ticket = FormsAuthentication.Decrypt(authCookie.Value);
var extendedTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userDataString);
authCookie.Value = FormsAuthentication.Encrypt(extendedTicket);
HttpContext.Current.Response.Cookies.Add(authCookie);
}
catch (Exception e)
{
throw new ProviderException(string.Format("Failed to authenticate user {0}.", userName), e);
}
}
示例15: OnPreSendRequestHeaders
private void OnPreSendRequestHeaders(object sender, EventArgs eventArgs)
{
var app = (HttpApplication)sender;
try
{
var ctx = ContextRegistry.GetContext();
var sessao = (Sessao)ctx.GetObject("Sessao");
if (!sessao.IsAutenticado)
{
FormsAuthentication.SignOut();
return;
}
var ticket = new FormsAuthenticationTicket(
1,
sessao.Usuario.UID.ToString(),
DateTime.Now,
DateTime.Now.AddMinutes(20),
false,
sessao.Organizacao.UID.ToString());
var cookie = FormsAuthentication.GetAuthCookie(sessao.Usuario.UID.ToString(), false);
cookie.Value = FormsAuthentication.Encrypt(ticket);
app.Context.Response.SetCookie(cookie);
}
finally
{
_log.Warn(app.Request.Path + " - " + app.Response.StatusCode);
}
}