Home Page
Articoli
Tips & Tricks
News
Forum
Archivio Forum
Blogs
Sondaggi
Rss
Video
Utenti
Chi Siamo
Contattaci
Username:
Password:
Login
Registrati ora!
Recupera Password
Home Page
Stanze Forum
ASP.NET 2.0 / 3.5 / 4.0
FormsAuthenticationTicket e persistenza
sabato 20 febbraio 2010 - 18.44
Elenco Threads
Stanze Forum
Aggiungi ai Preferiti
Cerca nel forum
volperubbia
Profilo
| Senior Member
375
messaggi | Data Invio:
sab 20 feb 2010 - 18:44
Ciao a tutti,
vorreri creare un ticket persistente, in ASP.NET 1.1 mi sembra non ci fossero problemi,
ma su 2.0 pare non funzionare ...
<authentication mode="Forms">
<forms name="TMP" loginUrl="Public/Login.aspx" protection="All" path="/" timeout="10080"></forms>
</authentication>
Dim UserData As String = "..."
Dim authTicket As New System.Web.Security.FormsAuthenticationTicket(1, Me.txtUsername.Text, Now, Now.AddDays(7), _
Me.chkRemember.Checked, UserData)
Dim sngEncTicket As String = System.Web.Security.FormsAuthentication.Encrypt(authTicket)
Dim authCookie As New System.Web.HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, sngEncTicket)
System.Web.HttpContext.Current.Response.Cookies.Add(authCookie)
Ottengo sempre un ticket persistente, indipendentemente dal valore di Me.chkRemember.Checked.
Qualche idea?
Davide
19018
Profilo
| Expert
502
messaggi | Data Invio:
lun 22 feb 2010 - 08:08
Ciao, io uso questo codice e funge alla perfezione:
<authentication mode="Forms">
<forms cookieless="UseCookies" loginUrl="~/login" name=".Hello" timeout="60"/>
</authentication>
if (Membership.ValidateUser(UsernameTextbox.Text, PasswordTextbox.Text))
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, UsernameTextbox.Text, DateTime.Now,
DateTime.Now.AddMonths(12), NotPublicCheckBox.Checked, "user");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (NotPublicCheckBox.Checked)
ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
}
ciao!
Stefano Passatordi
http://blogs.dotnethell.it/stem/
volperubbia
Profilo
| Senior Member
375
messaggi | Data Invio:
mer 24 feb 2010 - 13:05
1283_TestLogin.zip
Ciao Stefano
,
grazie per i consigli, in questi giorni ci ho lavorato su.
Ho creato un progettino di test, in allegato.
Devo verificare ancora dei passaggi per capire se regge
il giro con le varie possibilità cookieless.
Ho creato un metodo CreateCookieAndRedirect che gestisce
la cosa. Lo richiamo dal form di login e fin qui tutto ok.
Non sono sicuro però della seguente cosa: chiamarlo da Session_Start.
Vorrei, nel caso l'utente non sia ancora autenticato e solo nel caso non
abbia fatto appena il log out, creare io un utente di default e quindi
evitare il passaggio attraverso il login (ovviamente aggiungerò altre
condizioni, non voglio un accesso anonimo al sito).
Secondo te è possibile ottenere questo comportamento e il Session_Start
è il posto giusto dove implementare questa gestione?
Grazie,
Davide
19018
Profilo
| Expert
502
messaggi | Data Invio:
mer 24 feb 2010 - 14:38
Scusa ma non ho capito cosa cerchi di fare, potresti fare un caso d'uso?
Stefano Passatordi
http://blogs.dotnethell.it/stem/
volperubbia
Profilo
| Senior Member
375
messaggi | Data Invio:
mer 24 feb 2010 - 15:09
Hai ragione ... mi sono espresso male.
Con la form authentication persistente, vorrei gestire questi casi:
1) non c'è il cookie, parte la sessione, vado a testare delle informazioni
nel web.config e se l'esito è positivo, creo io un utente predefinito e autenticato
(l'utente salta il form di login).
2) stesso caso di prima, ma il test fallisce e l'utente arriva al form di login.
3) l'utente è già autenticato, fa il logout e, vista la sua volontà di uscire,
non faccio (1), ma gli propongo il login standard.
Davide
19018
Profilo
| Expert
502
messaggi | Data Invio:
mer 24 feb 2010 - 15:25
Ok, ora ho capito.
Credo che in Session_Start dovrebbe funzionare, se sei nel caso 1, semplicemente assegni la sessione all'utente autorizzato che hai inserito nel web.config altrimenti rientri nel caso 2 o 3.
Dovrebbe fungere
Stefano Passatordi
http://blogs.dotnethell.it/stem/
volperubbia
Profilo
| Senior Member
375
messaggi | Data Invio:
gio 25 feb 2010 - 10:51
1284_TestLogin_01.zip
Ciao Stefano,
ti confermo che funziona, ho fatto N prove (allegato).
L'unico caso che da problemi è cookieless="UseUri", qui devo lavorarci ancora.
Davide
19018
Profilo
| Expert
502
messaggi | Data Invio:
gio 25 feb 2010 - 10:53
Bene, purtroppo non riesco ad aprire la tua solution. Mi da sempre errore durante la conversione.
Stefano Passatordi
http://blogs.dotnethell.it/stem/
volperubbia
Profilo
| Senior Member
375
messaggi | Data Invio:
gio 25 feb 2010 - 13:55
Ciao,
ti giro il codice qui, non è molto.
Web.Config
--------------
<authentication mode="Forms">
<!-- "AutoDetect" ok, "UseCookies" ok, "UseDeviceProfile" ok, "UseUri" da rivedere -->
<forms name="TestLogin" cookieless="AutoDetect" loginUrl="Public/Login.aspx" protection="All" path="/" timeout="60"></forms>
</authentication>
Global.asax.vb
-----------------
Public Class Global_asax : Inherits System.Web.HttpApplication
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
If (System.Web.HttpContext.Current.User Is Nothing OrElse _
Not System.Web.HttpContext.Current.User.Identity.IsAuthenticated) AndAlso _
System.Web.HttpContext.Current.Request.QueryString("LogOut") Is Nothing AndAlso _
Not System.Web.HttpContext.Current.Request.QueryString("ReturnUrl") Is Nothing Then
' SE L'UTENTE NON E' AUTENTICATO E NON ARRIVA DA UN LOGOUT
Utility.CreateCookieAndRedirect(0, "Utente predefinito", False)
End If
End Sub
End Class
Public Class Utility
Shared Sub CreateCookieAndRedirect(ByVal UserID As Int64, _
ByVal Username As String, _
Optional ByVal blnLoginUser As Boolean = True)
Dim UserData As String = String.Empty
Dim RedirectUrl As String = String.Empty
Username &= " (" & Now.ToString & ")"c
UserData &= UserID.ToString & "|"c ' ID UTENTE
Dim authTicket As New System.Web.Security.FormsAuthenticationTicket(1, Username, Now, Now.AddDays(7), True, UserData)
Dim sngEncTicket As String = System.Web.Security.FormsAuthentication.Encrypt(authTicket)
Dim authCookie As New System.Web.HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, sngEncTicket)
authCookie.Expires = authTicket.Expiration
authCookie.Path = System.Web.Security.FormsAuthentication.FormsCookiePath
System.Web.HttpContext.Current.Response.Cookies.Add(authCookie)
If (blnLoginUser) Then ' UTENTE LOGGATO
If (System.Web.Security.FormsAuthentication.CookiesSupported) Then ' AUTENTICAZIONE BASATA SU FORM CON COOKIE
System.Web.Security.FormsAuthentication.RedirectFromLoginPage(Username, True)
Else ' AUTENTICAZIONE BASATA SU FORM SENZA COOKIE
RedirectUrl = System.Web.Security.FormsAuthentication.GetRedirectUrl(Username, True)
RedirectUrl &= "?"c & System.Web.Security.FormsAuthentication.FormsCookieName & "="c & sngEncTicket
System.Web.HttpContext.Current.Response.Redirect(RedirectUrl, False)
End If
Else ' UTENTE DI DEFAULT
If (System.Web.Security.FormsAuthentication.CookiesSupported) Then
' AUTENTICAZIONE BASATA SU FORM CON COOKIE
System.Web.Security.FormsAuthentication.RedirectFromLoginPage(Username, True)
Else ' AUTENTICAZIONE BASATA SU FORM SENZA COOKIE
Select Case System.Web.Security.FormsAuthentication.CookieMode
Case Web.HttpCookieMode.UseUri
System.Web.Security.FormsAuthentication.RedirectFromLoginPage(Username, True)
Case Else
RedirectUrl = System.Web.HttpContext.Current.Request.ApplicationPath.TrimEnd("/"c) & "/Protected/Default.aspx"
RedirectUrl &= "?"c & System.Web.Security.FormsAuthentication.FormsCookieName & "="c & sngEncTicket
System.Web.HttpContext.Current.Response.Redirect(RedirectUrl, False)
End Select
End If
End If
End Sub
End Class
Login.aspx.vb
-----------------
Partial Public Class Login : Inherits System.Web.UI.Page
Private Sub btnLogin_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Utility.CreateCookieAndRedirect(1, "Utente loggato", True)
End Sub
End Class
Davide
19018
Profilo
| Expert
502
messaggi | Data Invio:
gio 25 feb 2010 - 20:09
Sfortunatamente non riesco a fare il debug solo guardando
Quello che ti posso dire è che quando usi cookieless="UseUri" la maggior parte dei problemi sono causati dagli URL. Dovresti sempre usare gli URL relativi, magari usa sempre la "~". Questo perchè l'URL processato dal server passa da:
http://localhost/mysite/default.aspx
ad
http://localhost/mysite/<login ticket>/default.aspx
Fai questa prova
ciao
Stefano Passatordi
http://blogs.dotnethell.it/stem/
rocco979
Profilo
| Newbie
1
messaggi | Data Invio:
ven 27 apr 2012 - 17:49
buonasera mi aggancio a questo post perchè sto impazzendo con lo useUri.
Faccio il login su un sito e all'autenticazione faccio la redirect a un altro sito. Purtroppo (credo) non posso mettere un url relativo , quindi, quando faccio la login, cambio sito e puntualmente l'applicazione mi va in errore in quanto c' è un incongruenza fra l'url che scrivo nel sito dove mi loggo e in quello di destinazione in quanto useUri come sapete mi scrive il ticket all'interno dell'url e , come già detto, essendo due siti diversi non posso usare un url relativo.
dovendo usare assolutamente useUri per cambiare la sessione sapreste darmi qualche consiglio per arginare questo problema??
grazie mille
Torna su
Stanze Forum
Elenco Threads
Partecipa anche tu! Registrati!
Hai bisogno di aiuto ?
Perchè non ti registri subito?
Dopo esserti registrato potrai chiedere
aiuto sul nostro
Forum
oppure aiutare gli altri
Consulta le
Stanze
disponibili.
Registrati ora !