• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 863
  • Last Modified:

ASP page - read login cookies form ASPX page

I need to read login cookies at ASP page which were created in ASPX logon page.
Global.asax.cs file working with cookies is attached below.

I tried to put these lines to my ASp page, but it does not work:
<%= Request.Cookies("authCookie") %>
<%= Request.Cookies("authTicket") %>

What I need to insert to my ASP pages to be able read credentials from logon page created using ASP.NET?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using System.Web.SessionState;

namespace FormsAuthAd
{
    public class Global : System.Web.HttpApplication
    {

        void Application_Start(object sender, EventArgs e)
        {
            // Kód spouštený pri spuštení aplikace

        }

        void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            String cookieName = FormsAuthentication.FormsCookieName;
            HttpCookie authCookie = Context.Request.Cookies[cookieName];

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

            FormsAuthenticationTicket authTicket = null;

            try
            {
                authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            }
            catch (Exception ex)
            {
                //Write the exception to the Event Log.
                return;
            }

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

            //When the ticket was created, the UserData property was assigned a
            //pipe-delimited string of group names.
            String[] groups = authTicket.UserData.Split(new char[] { '|' });

            //Create an Identity.
            GenericIdentity id = new GenericIdentity(authTicket.Name, "LdapAuthentication");

            //This principal flows throughout the request.
            GenericPrincipal principal = new GenericPrincipal(id, groups);

            Context.User = principal;

        }

        void Application_End(object sender, EventArgs e)
        {
            //  Kód spouštený pri ukoncení aplikace

        }

        void Application_Error(object sender, EventArgs e)
        {
            // Kód spouštený pri výskytu neošetrené výjimky

        }

        void Session_Start(object sender, EventArgs e)
        {
            // Kód spouštený pri spuštení nové relace

        }

        void Session_End(object sender, EventArgs e)
        {
            // Kód spouštený pri ukoncení relace. 
            // Poznámka: Tato událost je vyvolána, pouze pokud je mód oddílu sessionstate
            // nastaven na InProc v souboru Web.config. Jestliže je mód relace nastaven na StateServer 
            // nebo SQLServer, událost nebude vyvolána.

        }

    }
}

Open in new window

0
pospichalales
Asked:
pospichalales
  • 25
  • 21
5 Solutions
 
RouchieCommented:
The MS documentation at
  http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.formscookiename.aspx

says you could use
  <%= Request.Cookies(".ASPXAUTH") %>
 
except the cookie values are encrypted so ASP might not be able to read them correctly at all.
0
 
pospichalalesAuthor Commented:
Cookies are encrypted and this does not work for me.
0
 
RouchieCommented:
In that case you will have to stop using the FormsAuthentication ticket and simply set your own cookie.
That way it can be shared.

If you are worried about security then put the data in a Session variable instead of a cookie.
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
pospichalalesAuthor Commented:
How can I make session variable and which code must I put to my ASP and ASPX page?
If you will be able to answer, I will be very, very happy. I am trying to do it a few days without success.
0
 
pospichalalesAuthor Commented:
Here is code of my logon.aspx page, if you need.
<%@ Page language="c#" AutoEventWireup="true" %>
<%@ Import Namespace="FormsAuth" %>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="cs" lang="cs">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-language" content="cs" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="pragma" content="no-cache" />
<link rel="stylesheet" type="text/css" media="screen" href="css/login.css" />
<link rel="shortcut icon" href="img/login/favicon.ico" />
<title>ZŠ Šlapanov - Prihlášení</title>
</head>
<body>
<div id="content">
<h1>Administrace</h1>
<p style="text-align:center;">Verze 2.0</p>	
    <form id="Login" method="post" runat="server">
    <h2>Prihlášení</h2>
      <p style="text-align:center;">Vítejte ve webovém modulu pro práci s uživateli. Prosíme, prihlaste se.</p><table align="center"><tr><td><asp:Label ID="Label1" Runat="server" >Doména:</asp:Label></td>
      <td><asp:TextBox ID="txtDomain" Runat="server" class="text" value="TEST" ></asp:TextBox></td></tr>    
      <tr><td><asp:Label ID="Label2" Runat="server" >Uživatel: </asp:Label></td>
      <td><asp:TextBox ID="txtUsername" Runat="server" class="text" ></asp:TextBox></td></tr>
      <tr><td><asp:Label ID="Label3" Runat="server" >Heslo: </asp:Label></td>
      <td><asp:TextBox ID="txtPassword" class="password" Runat="server" TextMode="Password"></asp:TextBox></td></tr></table>
      <p style="text-align:center;"><asp:Button ID="btnLogin" class="button" Runat="server" Text="Prihlásit" OnClick="Login_Click"></asp:Button></p>
      <p style="text-align:center;"><asp:Label ID="errorLabel" Runat="server" ForeColor="#ff3300"></asp:Label></p>
      <p style="text-align:center;"><asp:CheckBox ID="chkPersist" Runat="server" Text="Zachovat soubory cookies - Není doporuceno" /></p>
      <p style="text-align:center;">Po odhlášení je doporuceno zavrít okno prohlížece.</p>
    <div class="footer"></div>
    </form>
</div>
<p style="text-align:center;">Copyright &copy; 2010 Aleš Pospíchal</p>
<p style="text-align:center;">Webové rozhraní: <b>x</b>admin.cz</p>	
</body>
</html>
<script runat="server">
void Login_Click(Object sender, EventArgs e)
{
  String adPath = "LDAP://localhost"; //Fully-qualified Domain Name
  LdapAuthentication adAuth = new LdapAuthentication(adPath);
  try
  {
    if(true == adAuth.IsAuthenticated(txtDomain.Text, txtUsername.Text, txtPassword.Text))
    {
      String groups = adAuth.GetGroups();

      //Create the ticket, and add the groups.
      bool isCookiePersistent = chkPersist.Checked;
      FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,  txtUsername.Text,
	DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups);
	
      //Encrypt the ticket.
      String encryptedTicket = FormsAuthentication.Encrypt(authTicket);
		
      //Create a cookie, and then add the encrypted ticket to the cookie as data.
      HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

      if(true == isCookiePersistent)
	authCookie.Expires = authTicket.Expiration;
				
      //Add the cookie to the outgoing cookies collection.
      Response.Cookies.Add(authCookie);		

      //You can redirect now.
      Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, false));
    }
    else
    {
      errorLabel.Text = "Autorizace se nezdarila. Zkontrolujte uživatelské jméno a heslo.";
    }
  }
  catch(Exception ex)
  {
    errorLabel.Text = "Chyba autorizace. " + ex.Message;
  }
}
</script>

Open in new window

0
 
pospichalalesAuthor Commented:
And here is classic ASP page:
<%
Dim strName, strSurname, strUser, strOU, authuser, authpass, domainname, objFSO
strName = request.form("name")
strSurname = request.form("surname")
strUser = request.form("username")
strOU = request.form("orgunit")
authuser = Request.ServerVariables("auth_user")
authpass = Request.ServerVariables("auth_password")
domainname="ZSSLAPANOV"

if strUser="" then
	response.write "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>"
	response.write "<html xmlns=http://www.w3.org/1999/xhtml xml:lang=cs lang=cs>"
	response.write "<head>"
	response.write "<meta http-equiv=Content-Type content='text/html; charset=utf-8' />"
	response.write "<meta http-equiv=Content-language content=cs />"
	response.write "<link rel=stylesheet type=text/css media=screen href=css/login.css />"
	response.write "<link rel='shortcut icon' href=img/login/favicon.ico />"
	response.write "<title>ZŠ Šlapanov - Nový uživatel</title>"
	response.write "</head><body>"
	response.write "<div id=content>"
	response.write "<h1>Administrace</h1>"
	response.write "<p style=text-align:center;>Verze 2.0</p>"
    response.write "<form method=post action=user_zak.asp>"
    response.write "<a href=logout.asp class=forgotten>Odhlásit</a>"
    response.write "<h2>Nový uživatel (žák)</h2>"
    response.write "<div class=left><label for=name>Jméno:</label><input type=text name=name class=text /></div>"
    response.write "<div class=right><label for=surname>Príjmení:</label><input type=text name=surname class=text /></div>"
    response.write "<div class=left><label for=username>Uživatelské jméno:</label><input type=text name=username class=text /></div>"
    response.write "<div class=right><label for=orgunit>Organizacní jednotka:</label><select name=orgunit><option>1.trida</option><option>2.trida</option><option>3.trida</option><option>4.trida</option><option>5.trida</option><option>6.trida</option><option>7.trida</option><option>8.trida</option><option>9.trida</option></select></div>"
    response.write "<div class=left>Uživatelské jméno by melo být ve tvaru j.novak nebo u ucitelu tvar novak</div>"
    response.write "<div class=left>Všechna pole musí být vyplnena. Pozor na shody uživatelských jmen.</div>"
    response.write "<div class=submit><input type=submit class=button value=Vytvorit /></div>"
    response.write "<div class=footer></div>"
    response.write "</form></div>"
    response.write "<p style=text-align:center;>Copyright &copy; 2010 Aleš Pospíchal</p>"
    response.write "<p style=text-align:center;>Webové rozhraní: <b>x</b>admin.cz</p>"
    response.write "</body></html>"
    response.end
else

if strName = "" or strSurname = "" or strUser = "" then

    response.write "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>"
    response.write "<html xmlns=http://www.w3.org/1999/xhtml xml:lang=cs lang=cs>"
	response.write "<head>"
	response.write "<meta http-equiv=Content-Type content='text/html; charset=utf-8' />"
	response.write "<meta http-equiv=Content-language content=cs />"
	response.write "<link rel=stylesheet type=text/css media=screen href=css/login.css />"
	response.write "<link rel='shortcut icon' href=img/login/favicon.ico />"
	response.write "<title>ZŠ Šlapanov - Nový uživatel</title>"
	response.write "</head><body>"
	response.write "<div class='flash error'>Kliknete <a href=default.aspx>zde</a> pro návrat na hlavní stránku.</div>"
	response.write "<div id=content>"
	response.write "<h1>Administrace</h1>"
	response.write "<p style=text-align:center;>Verze 2.0</p>"
	response.write "<form action= method=get>"
    response.write "<a href=logout.asp class=forgotten>Odhlásit</a>"
    response.write "<h2>Nový uživatel (žák)</h2>"
    response.write "<p style=text-align:center;><b>Nastala chyba!</b></p>"
    response.write "<p>&nbsp;</p>"
    response.write "<p style=text-align:center;>Tohoto uživatele nelze vytvorit nebo nekteré pole zustalo prázdné. Zkuste to znovu.</p>"
    response.write "<div class=footer></div>"
    response.write "</form></div>"
    response.write "<p style=text-align:center;>Copyright &copy; 2010 Aleš Pospíchal</p>"
    response.write "<p style=text-align:center;>Webové rozhraní: <b>x</b>admin.cz</p>"
	response.write "</body></html>"
    response.end

else
 
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
 
objConnection.Properties("User ID") = domainname+"\" + authuser
objConnection.Properties("Password") = authpass
objConnection.Properties("Encrypt Password") = TRUE
objConnection.Properties("ADSI Flag") = 3
 
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection 
 
Set objOU = GetObject("LDAP://OU=" & strOU & ",dc=test,dc=local")
Set objUser = objOU.Create("User", "cn=" & strName+" " + StrSurname & "")
objUser.Put "sAMAccountName", StrUser
objUser.SetInfo
Set objUser = GetObject _
  ("LDAP://cn=" & strName+" " +StrSurname &",ou=" & strOU & ",dc=test,dc=local")
objUser.Put "userPrincipalName", "" & strUser & "@test.local"
objUser.Put "givenName", strName
objUser.Put "SN", strSurname
objUser.Put "displayName", strName+" " + strSurname 
objUser.Put "profilePath", "\\WIN-7SLGU4B55R1\Profiles\" & strUser & "" 
objUser.AccountDisabled = False
objUser.SetPassword "abc123"
objUser.Put "pwdLastSet", "0"
objUser.SetInfo

Set objUser = GetObject("LDAP://cn=" & strName+" " + strSurname &",ou=" & strOU & ",dc=test,dc=local")
Set objGroup = GetObject("LDAP://cn=Zaci,cn=Users,dc=test,dc=local")
objGroup.add(objUser.ADsPath)
 
Set objFSO= Server.CreateObject("Scripting.FileSystemObject")
If Not objFSO.FolderExists("C:\" & strUser & "") then
  objFSO.CreateFolder("C:\" & strUser & "")
End If

Set objShell = CreateObject("Wscript.Shell")
objShell.Run("icacls c:\" & strUser & " /grant:r TEST\" & strUser & ":F /inheritance:r /T /C /L /Q")
objShell.Run("icacls c:\" & strUser & " /setowner TEST\" & strUser & " /T /C /L /Q")
WScript.Quit

response.write "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>"
	response.write "<html xmlns=http://www.w3.org/1999/xhtml xml:lang=cs lang=cs>"
	response.write "<head>"
	response.write "<meta http-equiv=Content-Type content='text/html; charset=utf-8' />"
	response.write "<meta http-equiv=Content-language content=cs />"
	response.write "<link rel=stylesheet type=text/css media=screen href=css/login.css />"
	response.write "<link rel='shortcut icon' href=img/login/favicon.ico />"
	response.write "<title>ZŠ Šlapanov - Nový uživatel</title>"
	response.write "</head><body>"
	response.write "<div class='flash error'>Kliknete <a href=default.aspx>zde</a> pro návrat na hlavní stránku.</div>"
	response.write "<div id=content>"
	response.write "<h1>Administrace</h1>"
	response.write "<p style=text-align:center;>Verze 2.0</p>"
	response.write "<form action= method=get>"
    response.write "<a href=logout.asp class=forgotten>Odhlásit</a>"
    response.write "<h2>Nový uživatel (žák)</h2>"
	response.write "<p style=text-align:center;><b>Uživatel byl vytvoren.</b> Heslo k úctu je <b>abc123</b>.</p>"
    response.write "<p style=text-align:center;>Heslo by melo být zmeneno co nejdríve.</p>"
	response.write "<div class=footer></div>"
    response.write "</form></div>"
	response.write "<p style=text-align:center;>Copyright &copy; 2010 Aleš Pospíchal</p>"
    response.write "<p style=text-align:center;>Webové rozhraní: <b>x</b>admin.cz</p>"
	response.write "</body></html>"
response.end

end if
end if
%>

Open in new window

0
 
RouchieCommented:
The method of authenticating users when they log in would have to be totally re-written because ASP cannot support ASP.NET's way of doing this.

You should post a new question in the ASP.NET topic area asking if it is possible to override the Authentication functionality to use a Session variable instead of the forms authentication cookie.  Unfortunately I have never done this so I cannot really help you out.
0
 
pospichalalesAuthor Commented:
Okay, and is there possibility to write forms authentication in ASP instead ASP.NET?
0
 
BanthorCommented:
My Medical records are available by a ASP Site. Interpol uses ASP as well. So the answer is yes.
You just have to write/steal/borrow/buy the code.
You need to evaluate your data for the following security requirements. HIPAA, SOX, PII, Proprietary, Public before determining the extent of your needs.
 
0
 
RouchieCommented:
It would be more suitable to migrate your ASP pages to use ASP.NET.   If you rewrite the forms authentication code yourself in ASP, then you are using older technology and there is a chance that you may miss security aspects.

Here is a page that provides sample code for writing ASP user authentication.

http://www.evolt.org/node/28652

 Note that you will need to alter all the ASP.NET pages to check for the session variable before they show their content.
0
 
pospichalalesAuthor Commented:
I used this code for LDAP authentication at ASP page:

What do I need to paste to other pages, what allows users to be authorised?
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="cs" lang="cs">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-language" content="cs" />
<link rel="stylesheet" type="text/css" media="screen" href="css/login.css" />
<link rel="shortcut icon" href="img/login/favicon.ico" />
<title>ZŠ Šlapanov - Prihlášení</title>
</head>
<body>
<div id="content">
<h1>Administrace</h1>
<p style="text-align:center;">Verze 2.0</p>

<%
dim submit
dim UserName
dim Password

UserName = ""
Password = ""
Domain = ""
submit = request.form("submit")

if submit = "Prihlásit" then
UserName = request.form("UserName")
Password = request.form("Password")
Domain = request.form("Domain")
result = AuthenticateUser(UserName, Password, Domain)
if result then
response.redirect("main.asp")
else
response.write "<h3>Autorizace selhala!</h3>"
end if
end if

response.write "<form method=post>"
response.write "<h2>Prihlášení</h2>"
response.write "<p style=text-align:center;>Vítejte ve webovém modulu pro práci s uživateli. Prosíme, prihlaste se.</p>"
response.write "<table align=center><tr><td><label for=domena>Doména:</label></td>"
response.write "<td><input type=text name=Domain class=text value=test.local /></td></tr>"
response.write "<tr><td><label for=username>Uživatel:</label></td>"
response.write "<td><input type=text name=UserName class=text /></td></tr>"
response.write "<tr><td><label for=password>Heslo:</label></td>"
response.write "<td><input type=password name=Password class=password /></td></tr></table>"
response.write "<p style=text-align:center;><input type=submit name=submit class=button value=Prihlásit /></p>"
response.write "<p style=text-align:center;>Po odhlášení je doporuceno zavrít okno prohlížece.</p>"
response.write "<div class=footer></div>"
response.write "</form>"
response.write "</div>"
response.write "<p style=text-align:center;>Copyright &copy; 2010 Aleš Pospíchal</p>"
response.write "<p style=text-align:center;>Webové rozhraní: <b>x</b>admin.cz</p>"	
response.write "</body></html>"
response.end

function AuthenticateUser(UserName, Password, Domain)
dim strUser, strPassword
AuthenticateUser = false

strUser = UserName
strPassword = Password

strQuery = "SELECT cn FROM 'LDAP://" & Domain & "' WHERE objectClass='*' "
set oConn = server.CreateObject("ADODB.Connection")
oConn.Provider = "ADsDSOOBJECT"
oConn.Properties("User ID") = strUser
oConn.Properties("Password") = strPassword
oConn.Properties("Encrypt Password") = true
oConn.Properties("ADSI Flag") = 3
oConn.open "DS Query", strUser, strPassword

set cmd = server.CreateObject("ADODB.Command")
set cmd.ActiveConnection = oConn
cmd.CommandText = strQuery
on error resume next
set oRS = cmd.Execute
if oRS.bof or oRS.eof then
AuthenticateUser = false
else
AuthenticateUser = true
end if
set oRS = nothing
set oConn = nothing

end function

%>

Open in new window

0
 
RouchieCommented:
Hi

You could try something like this...

if result then
   session("username") = UserName
   response.redirect("main.asp")
else
   response.write "<h3>Autorizace selhala!</h3>"
end if


And then on each page you would have to do something like this:

If Not Session("username") Is Nothing Then
   ' show page content here....
Else
   Response.Redirect("login.asp")
End If


As a final note, remember to clear the session value when the user logs out...
   Session("username") = Nothing
0
 
pospichalalesAuthor Commented:
It may work, I will try it.

Last thing - How can I put username and password typed in logon page to next pages for LDAP authentication.
Can it work with auth_user and auth_pass?
0
 
RouchieCommented:
I'm not an LDAP programmer, but it seems there is a way to program ASP directly for active directory.

Instead of using Session variables, have a read of these examples and see if they work for you:

http://stackoverflow.com/questions/702998/connecting-to-openldap-server-in-vbscript-via-opendsobject
0
 
pospichalalesAuthor Commented:
what about to store administrator password to asp page? If forms authentication is used and login page is in asp too, users cannot access this pages. Script runs at server, clients will receive clear Html only.
0
 
RouchieCommented:
The login page will be the only page that does not check if the user is logged in.  If you must store passwords, store them in Session variables.
0
 
pospichalalesAuthor Commented:
How can I store username and password to variables? It is last thing, I need to know. I am trying it, but it still wrotes Permissions denied.
0
 
RouchieCommented:
Have you modified your code to use the OpenDSObject that is used in the example page I posted?

To save the username and password, you can do:

Session("username") = request.form("username")
Session("password") = request.form("password")

and then to read those back you could do:

oConn.Properties("User ID") = Session("username")
oConn.Properties("Password") = Session("password")

I think you might have to perform the strQuery = "SELECT cn FROM 'LDAP://" & Domain & "' WHERE objectClass='*' " check on every single page, using the username and password stored in the Session variable.
0
 
pospichalalesAuthor Commented:
No, I have not.

I tried this, but it does not work for me.
0
 
pospichalalesAuthor Commented:
At simple page, it works, but if I am inserting this variable for LDAP connection at next page, it does not work.
0
 
pospichalalesAuthor Commented:
My second page code is:
<%
Dim strName, strSurname, strUser, strOU, domainname, authuser, authpass, objFSO
strName = request.form("name")
strSurname = request.form("surname")
strUser = request.form("username")
strOU = request.form("orgunit")
authuser = session("sessUser")
authpass = session("sessPass")
domainname="ZSSLAPANOV"

if strUser="" then
	response.write "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>"
	response.write "<html xmlns=http://www.w3.org/1999/xhtml xml:lang=cs lang=cs>"
	response.write "<head>"
	response.write "<meta http-equiv=Content-Type content='text/html; charset=utf-8' />"
	response.write "<meta http-equiv=Content-language content=cs />"
	response.write "<link rel=stylesheet type=text/css media=screen href=css/login.css />"
	response.write "<link rel='shortcut icon' href=img/login/favicon.ico />"
	response.write "<title>ZŠ Šlapanov - Nový uživatel</title>"
	response.write "</head><body>"
	response.write "<div id=content>"
	response.write "<h1>Administrace</h1>"
	response.write "<p style=text-align:center;>Verze 2.0</p>"
    response.write "<form method=post action=user_zak.asp>"
    response.write "<a href=logout.asp class=forgotten>Odhlásit</a>"
    response.write "<h2>Nový uživatel (žák)</h2>"
    response.write "<div class=left><label for=name>Jméno:</label><input type=text name=name class=text /></div>"
    response.write "<div class=right><label for=surname>Príjmení:</label><input type=text name=surname class=text /></div>"
    response.write "<div class=left><label for=username>Uživatelské jméno:</label><input type=text name=username class=text /></div>"
    response.write "<div class=right><label for=orgunit>Organizacní jednotka:</label><select name=orgunit><option>1.trida</option><option>2.trida</option><option>3.trida</option><option>4.trida</option><option>5.trida</option><option>6.trida</option><option>7.trida</option><option>8.trida</option><option>9.trida</option></select></div>"
    response.write "<div class=left>Uživatelské jméno by melo být ve tvaru j.novak nebo u ucitelu tvar novak</div>"
    response.write "<div class=left>Všechna pole musí být vyplnena. Pozor na shody uživatelských jmen.</div>"
    response.write "<div class=submit><input type=submit class=button value=Vytvorit /></div>"
    response.write "<div class=footer></div>"
    response.write "</form></div>"
    response.write "<p style=text-align:center;>Copyright &copy; 2010 Aleš Pospíchal</p>"
    response.write "<p style=text-align:center;>Webové rozhraní: <b>x</b>admin.cz</p>"
    response.write "</body></html>"
    response.end
else

if strName = "" or strSurname = "" or strUser = "" then

    response.write "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>"
    response.write "<html xmlns=http://www.w3.org/1999/xhtml xml:lang=cs lang=cs>"
	response.write "<head>"
	response.write "<meta http-equiv=Content-Type content='text/html; charset=utf-8' />"
	response.write "<meta http-equiv=Content-language content=cs />"
	response.write "<link rel=stylesheet type=text/css media=screen href=css/login.css />"
	response.write "<link rel='shortcut icon' href=img/login/favicon.ico />"
	response.write "<title>ZŠ Šlapanov - Nový uživatel</title>"
	response.write "</head><body>"
	response.write "<div class='flash error'>Kliknete <a href=default.asp>zde</a> pro návrat na hlavní stránku.</div>"
	response.write "<div id=content>"
	response.write "<h1>Administrace</h1>"
	response.write "<p style=text-align:center;>Verze 2.0</p>"
	response.write "<form action= method=get>"
    response.write "<a href=logout.asp class=forgotten>Odhlásit</a>"
    response.write "<h2>Nový uživatel (žák)</h2>"
    response.write "<p style=text-align:center;><b>Nastala chyba!</b></p>"
    response.write "<p>&nbsp;</p>"
    response.write "<p style=text-align:center;>Tohoto uživatele nelze vytvorit nebo nekteré pole zustalo prázdné. Zkuste to znovu.</p>"
    response.write "<div class=footer></div>"
    response.write "</form></div>"
    response.write "<p style=text-align:center;>Copyright &copy; 2010 Aleš Pospíchal</p>"
    response.write "<p style=text-align:center;>Webové rozhraní: <b>x</b>admin.cz</p>"
	response.write "</body></html>"
    response.end

else
 
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
 
objConnection.Properties("User ID") = authuser
objConnection.Properties("Password") = authpass
objConnection.Properties("Encrypt Password") = TRUE
objConnection.Properties("ADSI Flag") = 3
 
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection 
 
Set objOU = GetObject("LDAP://OU=" & strOU & ",dc=test,dc=local")
Set objUser = objOU.Create("User", "cn=" & strName+" " + StrSurname & "")
objUser.Put "sAMAccountName", StrUser
objUser.SetInfo
Set objUser = GetObject _
  ("LDAP://cn=" & strName+" " +StrSurname &",ou=" & strOU & ",dc=test,dc=local")
objUser.Put "userPrincipalName", "" & strUser & "@test.local"
objUser.Put "givenName", strName
objUser.Put "SN", strSurname
objUser.Put "displayName", strName+" " + strSurname 
objUser.Put "profilePath", "\\WIN-7SLGU4B55R1\Profiles\" & strUser & "" 
objUser.AccountDisabled = False
objUser.SetPassword "abc123"
objUser.Put "pwdLastSet", "0"
objUser.SetInfo

Set objUser = GetObject("LDAP://cn=" & strName+" " + strSurname &",ou=" & strOU & ",dc=test,dc=local")
Set objGroup = GetObject("LDAP://cn=Zaci,cn=Users,dc=test,dc=local")
objGroup.add(objUser.ADsPath)
 
Set objFSO= Server.CreateObject("Scripting.FileSystemObject")
If Not objFSO.FolderExists("C:\" & strUser & "") then
  objFSO.CreateFolder("C:\" & strUser & "")
End If
Set objFSO = Nothing

Dim oShell, sCommand1, sCommand2, sCommand3
sCommand1 = "icacls c:\" & strUser & " /grant:r TEST\" & strUser & ":F /inheritance:r /T /C /L /Q"
sCommand2 = "icacls c:\" & strUser & " /grant:r ""TEST\Domain Admins"":F /inheritance:r /T /C /L /Q"
sCommand3 = "icacls c:\" & strUser & " /setowner TEST\" & strUser & " /T /C /L /Q"
Set oShell = Server.CreateObject("WScript.Shell")
oShell.Run sCommand1, , True
oShell.Run sCommand2, , True
oShell.Run sCommand3, , True
Set oShell = Nothing

response.write "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>"
	response.write "<html xmlns=http://www.w3.org/1999/xhtml xml:lang=cs lang=cs>"
	response.write "<head>"
	response.write "<meta http-equiv=Content-Type content='text/html; charset=utf-8' />"
	response.write "<meta http-equiv=Content-language content=cs />"
	response.write "<link rel=stylesheet type=text/css media=screen href=css/login.css />"
	response.write "<link rel='shortcut icon' href=img/login/favicon.ico />"
	response.write "<title>ZŠ Šlapanov - Nový uživatel</title>"
	response.write "</head><body>"
	response.write "<div class='flash error'>Kliknete <a href=default.asp>zde</a> pro návrat na hlavní stránku.</div>"
	response.write "<div id=content>"
	response.write "<h1>Administrace</h1>"
	response.write "<p style=text-align:center;>Verze 2.0</p>"
	response.write "<form action= method=get>"
    response.write "<a href=logout.asp class=forgotten>Odhlásit</a>"
    response.write "<h2>Nový uživatel (žák)</h2>"
	response.write "<p style=text-align:center;>Uživatel byl vytvoren. Heslo k úctu je abc123.</p>"
    response.write "<p style=text-align:center;>Heslo by melo být zmeneno co nejdríve.</p>"
	response.write "<div class=footer></div>"
    response.write "</form></div>"
	response.write "<p style=text-align:center;>Copyright &copy; 2010 Aleš Pospíchal</p>"
    response.write "<p style=text-align:center;>Webové rozhraní: <b>x</b>admin.cz</p>"
	response.write "</body></html>"
response.end

end if
end if
%>

Open in new window

0
 
pospichalalesAuthor Commented:
It probably works, there is problem with IIS settings.
I will set it correctly, try it and write if it worked.
0
 
pospichalalesAuthor Commented:
It worked! There was problem with IIS settings at web.config file. Thank you very much.
I will accept your answers during few hours.
0
 
RouchieCommented:
Hi

Thanks for your feedback.  I'm glad you fixed the problem.  Could you please tell me what IIS setting was incorrect so anybody else who reads this in the future will see the answer?
0
 
pospichalalesAuthor Commented:
I reviewed this again and problem persists, because it always use authorised user to IIS to connect LDAP. It do not use credentials from previous login form. If I use anonymous authentication, it does not work.
0
 
RouchieCommented:
In that case you will have to perform your AuthenticateUser() function on EVERY page.

On the login page, if the authentication is successful, then save the username and password values into Session variables before using Response.Redirect().

You can then use those Session variable values to re-authenticate on all other pages.
 
0
 
pospichalalesAuthor Commented:
I tried to use what are you writing. Here is second page:

authuser = session("sessUser")
...
Function AuthenticateUser(authuser, authpass, domain)
// LDAP Connection
...
End Function
...

This does not return error, but it still does not work.

I also tried  - call AuthenticateUser(authuser, authpass, domain)
0
 
RouchieCommented:
Put this after the function is declared and tell me what shows up (using the correct variables as function arguments)...

response.write("<h3>" & AuthenticateUser(authuser, authpass, domain) & "</h3>")
0
 
pospichalalesAuthor Commented:
It writes: type mismatch.
0
 
RouchieCommented:
Okay please try

<%
Dim result
result = AuthenticateUser(authuser, authpass, domain)
%>

response.write("<h3>" & CStr(result) & "</h3>")
0
 
RouchieCommented:
<%
Dim result
result = AuthenticateUser(authuser, authpass, domain)
response.write("<h3>" & CStr(result) & "</h3>")
%>
0
 
pospichalalesAuthor Commented:
Now it writes:
Type mismatch: AuthenticateUser
0
 
RouchieCommented:
Make sure your function AuthenticateUser is passing back a Boolean TRUE/FALSE value
0
 
pospichalalesAuthor Commented:
If I put attached code of function from login page to my second page, it returns TRUE value.
function AuthenticateUser(authuser, authpass, domain)
AuthenticateUser = false

strQuery = "SELECT cn FROM 'LDAP://" & Domain & "' WHERE objectClass='*' "
set oConn = server.CreateObject("ADODB.Connection")
oConn.Provider = "ADsDSOOBJECT"
oConn.Properties("User ID") = authUser
oConn.Properties("Password") = authPass
oConn.Properties("Encrypt Password") = true
oConn.Properties("ADSI Flag") = 3
oConn.open "DS Query", authUser, authPass

set cmd = server.CreateObject("ADODB.Command")
set cmd.ActiveConnection = oConn
cmd.CommandText = strQuery
on error resume next
set oRS = cmd.Execute
if oRS.bof or oRS.eof then
AuthenticateUser = false
else
AuthenticateUser = true
end if
set oRS = nothing
set oConn = nothing

end function

Open in new window

0
 
RouchieCommented:
Please take out the line that reads

   on error resume next

This line stops errors showing that you should normally deal with.  Please remove the line and run the code again and see if you get any different messages.
0
 
pospichalalesAuthor Commented:
It does not write any error.
0
 
RouchieCommented:
Okay then please try this so that we can see if your function is working.  Don't forget to use this new code on every page:

function AuthenticateUser(authuser, authpass, domain)
strQuery = "SELECT cn FROM 'LDAP://" & Domain & "' WHERE objectClass='*' "
set oConn = server.CreateObject("ADODB.Connection")
oConn.Provider = "ADsDSOOBJECT"
oConn.Properties("User ID") = authUser
oConn.Properties("Password") = authPass
oConn.Properties("Encrypt Password") = true
oConn.Properties("ADSI Flag") = 3
oConn.open "DS Query", authUser, authPass
set cmd = server.CreateObject("ADODB.Command")
set cmd.ActiveConnection = oConn
cmd.CommandText = strQuery
set oRS = cmd.Execute
if oRS.bof or oRS.eof then
AuthenticateUser = false
response.write("<h3>Authentication has failed!</h3>")
else
AuthenticateUser = true
response.write("<h3>Authentication has succeeded!</h3>")
end if
set oRS = nothing
set oConn = nothing
end function
0
 
pospichalalesAuthor Commented:
It writes True and Authentication has succeeded!
I think that all is OK, but there must be something that will call or run this function.
0
 
RouchieCommented:
Right here's what you need to do.

On the login page, add the login form as you have done already.  When the login button is pressed, call AuthenticateUser to check the login details.

Dim u
Dim p
Dim d
u = trim(request.form("username"))
p = trim(request.form("password"))
d = ' you add the code for the domain here because i don't know what this is...

Dim checkuser
checkuser = AuthenticateUser(u, p, d)

if checkuser then
  ' user has logged in okay so save their details
  Session("username") = u
  Session("password") = p
  Session("domain") = d
  Response.Redirect("main.asp")
else
  ' login fails
  Session("username") = Nothing
  Session("password") = Nothing
  Session("domain") = Nothing
  Response.Redirect("login.asp")
end if

Now on every other page in your software, you can called the AuthenticateUser function like this:

Dim u
Dim p
Dim d
u = Session("username")
p = Session("password")
d = Session("domain")
Dim checkuser
checkuser = AuthenticateUser(u, p, d)
if checkuser then
  response.write("<h3>Logged in - show page contents here instead of this message</h3>")
else
  ' login fails
  Session("username") = Nothing
  Session("password") = Nothing
  Session("domain") = Nothing
  Response.Redirect("login.asp")
end if
0
 
pospichalalesAuthor Commented:
Page works great, but it still says Permissions denied after pressing button and trying to authorize at AD.
0
 
RouchieCommented:
Does this happen on the login page or pages after?

Can you post the full error message that you see?
0
 
pospichalalesAuthor Commented:
On the second page,if it is opening connection to LDAP and it tries add new user to AD, I am getting this error:
Active Directory error: 80070005
Access denied.
0
 
RouchieCommented:
Okay thanks.

Can you please let me know more detail about what you are doing when you say 'Add new user to AD' ?

Error 80070005 is a very general ASP error and can mean many different things.  This page shows some things to try and resolve it: http://www.computerperformance.co.uk/Logon/code/code_80070005.htm
0
 
pospichalalesAuthor Commented:
I am using Anonymous authentication at IIS. If I change user for anonymous authentication to for example TEST\Administrator, all is working perfectly.
But this problem - I think that I cannot set administrator accounts for anonymous authentication due to security reasons.
What do you think?
0
 
RouchieCommented:
Web pages are stateless, which means that you cannot automatically determine whether somebody is logged in automatically each time a page loads.  You have to check their authentication before showing page content.

Unfortunately I've never programmed against Active Directory.  I think you should post a detailed description of your problem in the AD topic area so you can get some more experienced people to solve the problem for you.  Post your question into the following zones:

http://www.experts-exchange.com/Software/Server_Software/File_Servers/Active_Directory/
http://www.experts-exchange.com/Database/LDAP/
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/ASP/

Sorry I can't help much more than that :-|
0
 
pospichalalesAuthor Commented:
Okay. Thank you very much.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

  • 25
  • 21
Tackle projects and never again get stuck behind a technical roadblock.
Join Now