How do I create a new user in a SQL Azure database? - sql-server

I am trying to use the following template:
-- =================================================
-- Create User as DBO template for SQL Azure Database
-- =================================================
-- For login <login_name, sysname, login_name>, create a user in the database
CREATE USER <user_name, sysname, user_name>
FOR LOGIN <login_name, sysname, login_name>
WITH DEFAULT_SCHEMA = <default_schema, sysname, dbo>
GO
-- Add user to the database owner role
EXEC sp_addrolemember N'db_owner', N'<user_name, sysname, user_name>'
GO
I would like to create a user called user1 with a password of 'user1pass'. I connected with my default database 'authentication' and I have a query window open.
But the template does not make sense for me. For example what's sysname, where do I supply the password and what should I use as the default_schema?
The particular user needs to have the power to do everything. But how do I set it up so he can do everything, is that done if I make the user a database owner?
So far I have tried:
CREATE USER user1, sysname, user1
FOR LOGIN user1, sysname, user1
WITH DEFAULT_SCHEMA = dbo, sysname, dbo
GO
Giving:
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ','.
and:
CREATE USER user1
FOR LOGIN user1
WITH DEFAULT_SCHEMA = dbo
GO
Giving:
Msg 15007, Level 16, State 1, Line 1 'user1' i
s not a valid login or you do not have permission.

Edit - Contained User (v12 and later)
As of Sql Azure 12, databases will be created as Contained Databases which will allow users to be created directly in your database, without the need for a server login via master.
Sql (standard) User
CREATE USER [MyUser] WITH PASSWORD = 'Secret';
ALTER ROLE [db_datareader] ADD MEMBER [MyUser]; -- or sp_addrolemember
AAD linked User
CREATE USER [SomeUser#mydomain.com] FROM EXTERNAL PROVIDER;
EXEC sp_addrolemember 'db_datareader' , N'SomeUser#mydomain.com'
AAD linked Group
CREATE USER [SomeGroup] FROM EXTERNAL PROVIDER;
EXEC sp_addrolemember 'db_datareader' , N'SomeGroup'
NB! when connecting to the database when using a contained user that you must always specify the database in the connection string.
Traditional Server Login - Database User (Pre v 12)
Just to add to #Igorek's answer, you can do the following in Sql Server Management Studio:
Create the new Login on the server
In master (via the Available databases drop down in SSMS - this is because USE master doesn't work in Azure):
create the login:
CREATE LOGIN username WITH password=N'password';
Create the new User in the database
Switch to the actual database (again via the available databases drop down, or a new connection)
CREATE USER username FROM LOGIN username;
(I've assumed that you want the user and logins to tie up as username, but change if this isn't the case.)
Now add the user to the relevant security roles
EXEC sp_addrolemember N'db_owner', N'username'
GO
(Obviously an app user should have less privileges than dbo.)

Check out this link for all of the information : https://azure.microsoft.com/en-us/blog/adding-users-to-your-sql-azure-database/
First you need to create a login for SQL Azure, its syntax is as follows:
CREATE LOGIN username WITH password='password';
This command needs to run in master db. Only afterwards can you run commands to create a user in the database. The way SQL Azure or SQL Server works is that there is a login created first at the server level and then it is mapped to a user in every database.
HTH

I followed the answers here but when I tried to connect with my new user, I got an error message stating "The server principal 'newuser' is not able to access the database 'master' under the current security context".
I had to also create a new user in the master table to successfully log in with SSMS.
USE [master]
GO
CREATE LOGIN [newuser] WITH PASSWORD=N'blahpw'
GO
CREATE USER [newuser] FOR LOGIN [newuser] WITH DEFAULT_SCHEMA=[dbo]
GO
USE [MyDatabase]
CREATE USER newuser FOR LOGIN newuser WITH DEFAULT_SCHEMA = dbo
GO
EXEC sp_addrolemember N'db_owner', N'newuser'
GO

You can simply create a contained user in SQL DB V12.
Create user containeduser with password = 'Password'
Contained user login is more efficient than login to the database using the login created by master. You can find more details # http://www.sqlindepth.com/contained-users-in-sql-azure-db-v12/

I use the Azure Management console tool of CodePlex, with a very useful GUI, try it. You can save type some code.

1 Create login while connecting to the master db
(in your databaseclient open a connection to the master db)
CREATE LOGIN 'testUserLogin' WITH password='1231!#ASDF!a';
2 Create a user while connecting to your db (in your db client open a connection to your database)
CREATE USER testUserLoginFROM LOGIN testUserLogin;
Please, note, user name is the same as login. It did not work for me when I had a different username and login.
3 Add required permissions
EXEC sp_addrolemember db_datawriter, 'testUser';
You may want to add 'db_datareader' as well.
list of the roles:
https://learn.microsoft.com/en-us/sql/relational-databases/security/authentication-access/database-level-roles?view=sql-server-ver15
I was inspired by #nthpixel answer, but it did not work for my db client DBeaver.
It did not allow me to run USE [master] and use [my-db] statements.
https://azure.microsoft.com/en-us/blog/adding-users-to-your-sql-azure-database/
How to test your user?
Run the query bellow in the master database connection.
SELECT A.name as userName, B.name as login, B.Type_desc, default_database_name, B.*
FROM sys.sysusers A
FULL OUTER JOIN sys.sql_logins B
ON A.sid = B.sid
WHERE islogin = 1 and A.sid is not null
List of all users in Azure SQL

create a user and then add user to a specific role:
CREATE USER [test] WITH PASSWORD=N'<strong password>'
go
ALTER ROLE [db_datareader] ADD MEMBER [test]
go

I found this link very helpful:
https://azure.microsoft.com/en-gb/documentation/articles/sql-database-manage-logins/
It details things like:
- Azure SQL Database subscriber account
- Using Azure Active Directory users to access the database
- Server-level principal accounts (unrestricted access)
- Adding users to the dbmanager database role
I used this and Stuart's answer to do the following:
On the master database (see link as to who has permissions on this):
CREATE LOGIN [MyAdmin] with password='ReallySecurePassword'
And then on the database in question:
CREATE USER [MyAdmin] FROM LOGIN [MyAdmin]
ALTER ROLE db_owner ADD MEMBER [MyAdmin]
You can also create users like this, according to the link:
CREATE USER [mike#contoso.com] FROM EXTERNAL PROVIDER;

I think the templates use the following notation: variable name, variable type, default value.
Sysname is a built-in data type which can hold the names of system objects.
It is limited to 128 Unicode character.
-- same as sysname type
declare #my_sysname nvarchar(128);

Related

User can't connect to Azure SQL Instance

I created my first database (let's call it MyDB) on Azure and created a user that I want to use to query the DB from my applications. I only wanted to give that user db_datawriter and db_datareader because I think that is all this user needs to do from the application.
When I run this on MyDB:
SELECT DP1.name AS DatabaseRoleName,
isnull (DP2.name, 'No members') AS DatabaseUserName
FROM sys.database_role_members AS DRM
RIGHT OUTER JOIN sys.database_principals AS DP1
ON DRM.role_principal_id = DP1.principal_id
LEFT OUTER JOIN sys.database_principals AS DP2
ON DRM.member_principal_id = DP2.principal_id
WHERE DP1.type = 'R'
ORDER BY DP1.name;
I get this back:
db_accessadmin No members
db_backupoperator No members
db_datareader MyDBUser
db_datawriter MyDBUser
db_ddladmin No members
db_denydatareader No members
db_denydatawriter No members
db_owner dbo
db_securityadmin No members
public No members
so that seemed to work. The problem is - I have to give this user also Permission to connect to the DB in the first place, because when I try to connect to the server, I get this:
===================================
Cannot connect to abc.database.windows.net.
===================================
The server principal "MyDBUser" is not able to access the database "master" under the current security context.
Cannot open user default database. Login failed.
Login failed for user 'MyDBUser'. (.Net SqlClient Data Provider)
I think this is probably, because my new user can't connect to master DB, as the errormessage suggests. However, when I look at the properties of MyDB, "Connect" was granted for the user by dbo
How can I let my user connect to the Azure DB Instance, preferably with as less permission as possible, I would only like for him to select, update, insert etc. on MyDB
I tried to change default DB with this command, so I don't need to do anything on masterDB, but the stored procedure wasn't found:
Exec sp_defaultdb #loginame='MyDBUser', #defdb='MyDB'
Edit: That's how I created the Login / User in SSMS
First (on instance):
CREATE LOGIN MyDBUser
WITH PASSWORD = '******'
GO
Then (on MyDB):
CREATE USER MyDBUser
FOR LOGIN MyDBUser
WITH DEFAULT_SCHEMA = dbo
GO
-- Add user to the database owner role
EXEC sp_addrolemember N'db_datawriter', N'MyDBUser'
GO
You have created a LOGIN and then created a USER for the LOGIN but only in the database you want them to connect to but not in master.
SQL Azure Databases are contained databases, so there is no need to create a LOGIN; the databases use their own scoped credentials.
First DROP the USER and LOGIN you created. Connect to MyDB and DROP the user first:
DROP USER MyDBUser;
Then connect to master and DROP the LOGIN:
DROP LOGIN MyDBUser;
Now connect to MyDB again and CREATE the USER with the needed credentials:
CREATE USER MyDBUser WITH PASSWORD = N'Your Secure Password', DEFAULT_SCHEMA = N'dbo';
Then you can give it the needed database roles. Don't use sp_addrolemember; it has been deprecated for ~10 years.
ALTER ROLE db_datareader ADD MEMBER MyDBUser;
ALTER ROLE db_datawriter ADD MEMBER MyDBUser;
I've had a similar error message when connecting to Azure SQL DB with SSMS. The solution there was to identify the database, hence the message "access the database "master"". You probably have entered the DB server name already.
You do not mention how you are trying to connect to the DB, but in case of SSMS, enter the name of the database on the tab "Connection properties" (available behind the "Options>>>" button on "Connect to Server" screen).

Can create user but then cannot alter it?

I am trying to create a user and then alter it in SQL Server. So far I have:
CREATE LOGIN bob1 WITH PASSWORD = '!abcd1234'
GO
ALTER USER bob1 WITH DEFAULT_SCHEMA = dbo;
GO
The first statement works, but then for the second I get:
Msg 15151, Level 16, State 1, Line 6
Cannot alter the user 'bob1', because it does not exist or you do not have permission.
What does that mean exactly? And why would I be able to create a user and then not be able to modify it?
It seems I'm mixing up LOGIN and USER. What is the difference between these two items?
In Azure, Login is not a user, it's used to login the Azure SQL database, you need create the user for login: CREATE USER BOB1 FOR LOGIN bob1, then run ALTER USER bob1 WITH DEFAULT_SCHEMA = dbo;. But it's not necessary, the default schema is dbo, we could not specify it.
Create login to log in the Server/database, then mapping the user to login.
After that you need alter the user enough permission/role to access the database, for example:
ALTER ROLE db_owner ADD MEMBER 'bob1'
Please ref here: Authorize database access to SQL Database, SQL Managed Instance, and Azure Synapse Analytics

Azure user GRANTs for SQL Database

I've been struggling my way through create a new DB user for an Azure SQL database. Here are the three statements I'm doing:
Create a new Azure login:
CREATE LOGIN [bobby] WITH PASSWORD = 'Password1'
Create a new DB user within the Azure login:
CREATE USER bobby FOR LOGIN bobby;
ALTER USER bobby with DEFAULT_SCHEMA = 'newschema';
To add a user to a DB group for that database — note, it is only for that database (whatever is in the current USE command):
EXEC sp_addrolemember 'db_owner', 'bobby'
For the life of me I couldn't figure out how to do GRANTs for step three. Every time I would try a statement it would give me some flavor of "permission denied" even though I am the one (and only) admin user in Azure. Is this the only way to add roles in Azure? Or am I totally missing something here?
In Azure SQL database, the whole step should be this:
1. Run the command in master DB:
CREATE LOGIN [bobby] WITH PASSWORD = 'Password1'
2. Go to the user database, run the command bellow:
CREATE USER bobby FOR LOGIN bobby;
ALTER USER bobby with DEFAULT_SCHEMA = 'newschema';
ALTER ROLE db_owner ADD MEMBER [bobby];
Please use server admin to create the login or user firstly.
Ref document here: ALTER ROLE (Transact-SQL)

Create User failed by master db on Azure

I create a db on azure portal. After this I connect to the azure db with my own application which i programming in dotnet. What i want is to create a new login which have the permission to also create new logins. So i connect to master db, then i create a new SQL login, then i create a new user from the login and add them to the loginmanager role. So know i can create new logins with the user but when i want create also user from login then i get an error that i have no permission to alter the the login. So what can i do?
Thanks for helping
Daniel
The problem is that the loginmanager role doesn't have the necessary permissions to create or alter users. The 'CREATE USER' statement requires the 'ALTER ANY USER' permission (details here).
So, in the first step you create a login and user in the master database that has the 'loginmanager' role.
-- connect to the master database with your 'sa' account
CREATE LOGIN login1 WITH PASSWORD='<your password>';
CREATE USER login1user FROM LOGIN login1;
EXEC sp_addrolemember 'loginmanager', 'login1user';
In the second step you need to grant this user the 'ALTER ANY USER' permission. Note that this needs to be done in the application database in which you want to have the user accounts.
-- connect to the application database with your 'sa' account
CREATE USER login1user FROM LOGIN login1;
GRANT ALTER ANY USER TO login1user;
You should now be able to create new logins and the associated users. Note that you create the logins in the master database, and you create the user in the application database.

Create a new db user in SQL Server 2005

how do you create a new database user with password in sql server 2005?
i will need this user/password to use in the connection string eg:
uid=*user*;pwd=*password*;
CREATE LOGIN [user] WITH PASSWORD='password',
DEFAULT_DATABASE=[your_db], CHECK_POLICY=OFF
GO
CREATE USER [user] FOR LOGIN [user]
EXEC sp_addrolemember N'db_datareader', N'your_db'
EXEC sp_addrolemember N'db_datawriter', N'your_db'
GO
Where CHECK_POLICY=OFF switches off password complexity check, etc
As of SQL Server 2005, you should basically create users in two steps:
create a "login" to your SQL Server as a whole
create users for this login in each database needed
You'd go about doing this like so:
CREATE LOGIN MyNewUser WITH PASSWORD = 'top$secret';
And the "USE" your database and create a user for that login:
USE AdventureWorks;
CREATE USER MyNewUser FOR LOGIN MyNewUser
As indicated, use the CREATE LOGIN to create the ability to connect to SQL Server as that account. Then use CREATE USER within the database to give that login the ability to access the database in question.
However, a few security points based on some of these comments:
If at all possible, you want to use Windows authentication, not a SQL Server based login (which is what you are doing when you use user/pwd in this manner). If you are running from a computer on the same domain as SQL Server, you can use a service account that is a Windows user account. This ensures the domain is the single source for security.
You didn't say what rights the user needed. Avoid using db_datareader and db_datawriter roles whenever possible. They give IMPLICIT access to tables and views and if someone is performing a quick permissions check on the database, they may not think to check the membership in these roles. That means your reporting on security is using. Best practices say to create your own database role, assign permissions to it, and make the user a member of that role.
Whenever possible, use a strong password. One example had the password policies turned off. SQL Server will use the password policy from the local server (which is usually set at the domain level). You want to maintain that strong password policy, if possible.
You'll have to create it first as a user, and then set up the correct permissions for the user.
you'll have to ensure that your DB is configured with both User auth and SQL auth
If using the Management Studio: right-click on the Server, select "Security" ensure that server authentication is "SQL Server and Windows Authentication mode"
in Security-logins, right click and select "New Login", select SQL Authentication, use the username and password you like.
USE [master]
GO
CREATE LOGIN [ test] WITH PASSWORD=N'test', DEFAULT_DATABASE=[MY_DATABASE], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
GO
on the DB you want, in security, users, select new User. Select a username, and attach the login name you've just created, and select the roles you want to apply to this user (i.e. db_datareader, db_datawriter):
USE [MY_DATABASE]
GO
CREATE USER [myDefaultUser] FOR LOGIN [ test]
GO
USE [MY_DATABASE]
GO
EXEC sp_addrolemember N'db_datareader', N'myDefaultUser'
GO
USE [MY_DATABASE]
GO
EXEC sp_addrolemember N'db_datawriter', N'myDefaultUser'
GO
That is it. Now you can create your connection string using this password.
CREATE LOGIN MyNewUser WITH PASSWORD = 'top$secret'
USE AdventureWorks
CREATE USER MyNewUser FOR LOGIN MyNewUser
GO
USE [MASTER]
EXEC master.dbo.sp_addlogin #loginame = N'USERNAME', #passwd = 'THEPASS' #defdb = N'master', #deflanguage = N'us_english'
USE [YOUR_DB]
EXEC dbo.sp_grantdbaccess #loginame = N'USERNAME', #name_in_db = N'USERNAME'

Resources