How-to configure DB security for ASP.NET applications?
answer is simple. You have to grant access to the DB for MACHINENAME\ASPNET user. This can be done in several ways, but easiest is to use this simple script written below. Place code into
*.cmd file and enjoy. Script is well configurable by variables: OSQL, SQL_USER, SQL_PWD, SQL_DB;
OSQL - location of the command line utility for SQL Server (2000 and 2005 known by script - look carefully on comments)
SQL_USER and SQL_PWD - place login and password if you server used mixed security model
SQL_DB - place here name of the DB that must be accessible for ASPNET user.
@echo off
:: for MS SQL Server 2005 command line utility is "%ProgramFiles%\Microsoft SQL Server\90\Tools\Binn\sqlcmd.exe"
set OSQL="%ProgramFiles%\Microsoft SQL Server\90\Tools\Binn\sqlcmd.exe"
::set OSQL="%ProgramFiles%\Microsoft SQL Server\80\Tools\Binn\osql.exe"
set SQL_SRV=(local)\SQLEXPRESS
::set SQL_SRV=(local)
set SQL_USER=
set SQL_PSWD=
set SQL_DB=master
if not exist %OSQL% (
goto :error
goto :EOF
)
:: detect what kind of connection required for server
set _TRUST=-E
set _IN_ACC=-U %SQL_USER% -P %SQL_PSWD%
if "%SQl_USER%"=="" (
if "%SQl_PSWD%"=="" (
set _IN=%_TRUST%
) else (
set _IN=%_IN_ACC%
)
) else (
set _IN=%_IN_ACC%
)
:: declare @login nvarchar(100)
:: set @login = HOST_NAME() + N'\ASPNET'
:: IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = @login)
:: exec sp_grantlogin @login
:: -- Grant the login access to the membership database
:: exec sp_grantdbaccess @login
:: -- Add user to database role
:: exec sp_addrolemember 'db_owner', @login
call :runSQL2 "IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = '%COMPUTERNAME%\ASPNET') exec sp_grantlogin '%COMPUTERNAME%\ASPNET'"
call :runSQL2 "exec sp_grantdbaccess '%COMPUTERNAME%\ASPNET'"
call :runSQL2 "exec sp_addrolemember 'db_owner', '%COMPUTERNAME%\ASPNET'"
goto :EOF
:: error message echo
:error
echo -= ERROR:
echo -= Can not find OSQL.EXE utility required for TSQL scripts execution
echo -= please check SQL Server Instance installation path and modify
echo -= in CMD file OSQL variable if needed
goto :EOF
:: method execute TSQL script on server
:runSQL2
%OSQL% -S %SQL_SRV% %_IN% -d %SQL_DB% -Q %1 >>configure_db.log
goto :EOF
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5