Asp.net Web Application Role based authentication - c#

I am kinda new at Asp.net and I have been trying to create a simple Transaction based system wherein users with different roles will have different menus and categories available for them. Currently, I am using this tutorial for my authenticated based login.
The code is working but I have noticed that the database being used is the default connection. What I wanted to do was create my own database and use it as the default connection (MyOwnConnectionString). How can I do that?
I am using VS 2015 and Sql Server 2016. I have a two tables namely Tbl_User and Tbl_Roles where the two tables are linked with the role_id
UPDATE
The tutorial above is about using the default registration of Asp.net wherein if the username to be used for registration matches the declared variable (in this case Admin), the user is given the role of Administrator in the Default Connection under tables AspNetUser, AspNetUserRoles, AspNetRoles.
I have a table named Tbl_User with columns "Name, Username, Password, Role"
Whenever I try to login, the database to be used is my created database(DB_Transaction) and not the default connect of Asp(DefaultConnection DB) and search for the corresponding roles in Tbl_Roles whether Admin or User then redirect them to their corresponding pages.
What should happen

If you want to use Asp.net Identity authentication and authorization then we need not to create table own self,the identity does it for us after user is registered.
And login is handelled along with the authorization.Just specify the database name in ConnectionString and for now you can use DefaultConnection as ConnectionString Key.Add the register a dummy user.You should see tables in your specified database.

Create database in SQL 2016 Add that connection string in WEB config file.
After pass that connection string to your SQL Connection Object or Database Context for Entity framework.here is reference link
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-WingtipToys;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="WingtipToys" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\wingtiptoys.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />

you can change the default connection from web.config file open it an go to connection string and remove the default connection and copy your server name connection at SQL and paste in the connection string and u can change the database name
as u can see in this image start remove the default connection from the local word
enter image description here
enter image description here
this is the server name connection

You can use the web.config file to update your connection string
or
use it in your code as well
using System.Data.SqlClient;
SqlConnection connection = new SqlConnection();
connection.ConnectionString ="Data Source=ServerName;" +"InitialCatalog=DataBaseName;" +
"Integrated Security=SSPI;";
connection.Open();

Related

ASP.NET Web Api the underlying provider failed to open mdf already exists

This is my solution structure:
Application
This is an ASP.NET MVC application. It has this connection string in web.config:
Data Source=.\SQLEXPRESS;
Initial Catalog=aspnet-Application-5cb5b1db-6c48-49c7-93b2-ba81ded39c1c;
Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|\aspnet-Application-5cb5b1db-6c48-49c7-93b2-ba81ded39c1c.mdf
providerName="System.Data.SqlClient"
It references ApplicationClassLibrary.
ApplicationApi
This is a Web API application, with this connection string in app.config:
Data Source=.\SQLEXPRESS;
Initial Catalog=aspnet-Application-5cb5b1db-6c48-49c7-93b2-ba81ded39c1c;
Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|\aspnet-Application-5cb5b1db-6c48-49c7-93b2-ba81ded39c1c.mdf"
providerName="System.Data.SqlClient"
It references ApplicationClassLibrary
ApplicationClassLibrary
This project contains dbContext and IdentityModel, and migrations are run from here.
The issue is that when I run my ApplicationApi and call this code using Postman:
public String CheckUser(string username, string password)
{
var user = dbContext.Users.SingleOrDefault(u => u.UserName == username);
return user.UserName;
}
I get this error:
Database 'C:\Users\uuu\source\repos\Application\Application\App_Data\aspnet-Application-5cb5b1db-6c48-49c7-93b2-ba81ded39c1c.mdf' already exists. Choose a different database name.
Cannot attach the file 'C:\Users\uuu\source\repos\Application\ApplicationApi\bin\Debug\aspnet-Application-5cb5b1db-6c48-49c7-93b2-ba81ded39c1c.mdf' as database 'aspnet-Application-5cb5b1db-6c48-49c7-93b2-ba81ded39c1c'
So basically for some reason, my ApplicationApi is trying to create or use an existing .mdf file? How can I solve this issue?
I found a solution that worked for me. It came from this link https://social.msdn.microsoft.com/Forums/sqlserver/en-US/6dfdcc22-7a81-4e8f-a947-c1ce6982d4b3/flustered-a-database-with-the-same-name-exists-or-specified-file-cannot-be-opened-or-it-is?forum=sqlexpress
What its saying is because I already have a parent connection string that created the db file, I should reference it only. So instead, my connection string for any other project that relies on the same database should be simple like this:
<add name="DefaultConnection"
connectionString="Data Source=.\SQLEXPRESS;Database=aspnet-Application-5cb5b1db-6c48-49c7-93b2-ba81ded39c1c;Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />

Connect MVC C# App to SQL Server DataBase

I have a DataBase in SQLSever. Into the webConfig file of my MVC project, when i configure the connectionString by giving the user and the password, it's correct:
<connectionStrings> <add name="jcConn" connectionString="Data Source=LAPTOP\MSSQLSERVERAXVAL;Initial Catalog=bd_school;Persist Security Info=True;User ID=sa;Password=namin"/> </connectionStrings>
But I dont want to specify the user and the password. So by trying to do this, it doesn't work:
<add name="jcConn" connectionString="Data Source=LAPTOP\MSSQLSERVERAXVAL;Initial Catalog=bd_school;Integrated Security=True;" providerName="System.Data.SqlClient" />
How can i do that ?
Thank you.
First: Does the user you're logged in as have access to the database you're trying to connect to? If you're running in IIS express then that's the user you're logged into the machine with and if you're hosting in IIS then the user the application pool is running as (assuming you're not impersonating).
Secondly: Integrated Security=true;
If you do not want to put your SQL User Id and Password in connection string then you must use Windows Authentication to login in SQL. And use your Database in Windows user in SQL. use this
Integrated Security=true;
If you use SQL login, then you need to specify the username and password in your connection string.
If you don't want that, you need to use Windows Authentication. Check this answer in that case.

How to create Sql Server database users from ASP.NET code

I run an Admin site that manages client machines. Each client machine is assigned a specific Sql Server database user. Up to this point I've had to go into Management Studio and create the users. I'd like to do this automatically when I setup a client machine on the Admin site.
Any suggestions on the best way to do this? I'm using ASP.NET MVC 2(old, I know) and Entity Framework 6.
You can set up a feed that automatically imports the credentials to the existing user table in SQL if you have write-back capabilites.
create a SQL connection to the server and create the users via TSQL
Web.Config
<connectionStrings>
<add name="ConnStringDb1" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
C#
CreateUser()
{
using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStringDb1"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "tsql to create users here";
cmd.ExecuteNonQuery();
}
}
}
You could do this via SQL directly when the client machine is set up by using the CREATE USER / CREATE LOGIN statement (and assigning its privileges accordingly). You can get the SQL to guide you in doing so if you start adding the user in management studio then hit the script button at the top left of the dialog it will show you the SQL script to dynamically create the user account. Create User SQL Docs Create Login SQL Docs

How to make a remote connection with SQL Server 2008 with ADO.NET entity Data model from C# winform

I have built a window form application and I use ADO.NET entity Data model to make connection with my local database and it work good with my own PC (the database and application in one PC).
Now I need the application to be used by many users 3 or 4. I have no idea how to install my database on the server and whether ADO.NET entity Data model will work again. I use SQL Server 2008 and C# window Form. Please I am waiting to hear what your suggestion will be.
all you need to do is just change the Data Source value in your connection string.
Follow the below Steps:
Step 1: Install and Maintain Your Database in your server machine.
Step 2 : Specify your databse Server HostName/IP Address in your Connection String as below:
String connectionString="Data Source=ServerName;Intial Catalog=DatabaseName;UID=userID;Password=password;Integrated Security=True;"
Add app.config file to your project and specify the connection string in there. Then access the config file using c#
<connectionStrings>
<add name="MyDBConnectionString" providerName="System.Data.SqlClient"
connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB; Integrated Security=true" />
</connectionStrings>
in c#
System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
Source Accessing database connection string using app.config in C# winform
You have host your database on server
Get server ip,username,password for the database
change your connection string
replace server name ,username,password
Data Source=serverip;Initial Catalog=dbname;Persist Security Info=True;User ID=username;Password=password
then this will be goto server database

how to connect a remote SQLserver using widows authentication from a .net application, if possible

currently I am using this connection string inside the app.config file of the application
add name="LightSailEntities" connectionString="metadata=res://*/LightSailEntities.csdl|res://*/LightSailEntities.ssdl|res://*/LightSailEntities.msl;provider=System.Data.SqlClient;provider connection string='data source=abc.xyz.com;initial catalog=LightSail;user id=LightSail; password=yourpasswordhere;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient"
The domain of .Net application and the domain of client, using .Net application, is different from domain of SQL server. I mentioned "using widows authentication" only because of, I have the access of the server machine(means I can use Remote Desktop Connection) on which the SQL server is installed.
For Windows Auth you don't need to set the User Id and Password but you do need to include 'Integrated Security=SSPI;'
Try:
add name="LightSailEntities" connectionString="metadata=res://*/LightSailEntities.csdl|res://*/LightSailEntities.ssdl|res://*/LightSailEntities.msl;provider=System.Data.SqlClient;provider connection string='data source=dev.shopcube.com;initial catalog=LightSail;Integrated Security=SSPI;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient"
There's a bit more info here:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(VS.71).aspx
You have to change ConnectionString to use Integrated Security=SSPI insetad of user and password
add name="LightSailEntities"
connectionString="metadata=res://*/LightSailEntities.csdl|res://*/LightSailEntities.ssdl|res://*/LightSailEntities.msl;
provider=System.Data.SqlClient;
provider connection string='data source=dev.shopcube.com;initial catalog=LightSail;Integrated Security=SSPI;MultipleActiveResultSets=True;App=EntityFramework'"
providerName="System.Data.EntityClient"
After that, look at the Identity set for the Application Pool of you application.
That user must be authorized to access your DB using Security\Logins inside Object Explorer pan of Management Studio.
Youo can use following code:
SqlConnection conn = new SqlConnection(Configuration.DBConn);
or if you use Linq2SQL:
DBContext ctx = new DBContext(Configuration.DBConn);
where in Configuration class DBConn string contains connection string to sql ie:
Data Source=XYZ\\DEV;Initial Catalog=YOURDB;Integrated Security=True;Connect Timeout=600;connection lifetime=600
Integrated Security=True tells that you want to use windows auth.

Categories