I would like to register new user from client app, by calling webapi, where dapper will execute procedure to create new db user and store credentials in table (without password). After registration, I will change connection string with user credentials to log in.
Is it possible to dynamically create db users by executing stored procedure on Azure sql db?
I've made such query:
CREATE PROCEDURE [dbo].[AddDbUser]
@Login nvarchar(50),
@Password nvarchar(50),
@Mail nvarchar(70),
@Phone nvarchar(9),
@SQL nvarchar(1000)
AS
BEGIN
SET @SQL = 'USE [testdb] '
+ 'CREATE LOGIN '+quotename(@Login)+' WITH PASSWORD =
'+quotename(@Password,'''')+'; '
+ 'CREATE USER '+@Login +'; '
+ 'EXEC [sys].[sp_addrolemember] ''db_datareader'', '+@Login+'; '
+ 'EXEC [sys].[sp_addrolemember] ''db_datawriter'', '+@Login+'; '
+ 'GRANT EXECUTE ON SCHEMA :: [dbo] TO '+@Login+'; '
+ 'INSERT INTO [dbo].[Users] (Login, Mail, Phone) '
+ 'VALUES ('+quotename(@Login,'''')+', '+quotename(@Mail,'''')+',
'+quotename(@Phone,'''')+');'
EXEC (@SQL)
END
GO
exec [dbo].[AddDbUser] 'dawidtest', 'password', '[email protected]', '123123123', null results in message: "User must be in the master database.", but when I add USE [master] instead of USE [testdb] I get message: "USE statement is not supported to switch between databases. Use a new connection to connect to a different database.".
Anybody could provide me some tips how to solve my problem or maybe there is some other more elegant solution?
Thank you in advance!