Authentication based on roles

时间:2015-10-06 08:16:35

标签: c# asp.net sql-server tsql stored-procedures

I'm trying to create authentication with roles. I've create a table Users in SQL Server and a stored procedure to return UserId and UserRole if user is valid as following.

CREATE TABLE [dbo].[Users]
([UserID] [int] IDENTITY(1,1) NOT NULL,
[Username] [nvarchar](20) NOT NULL,
[Password] [nvarchar](20) NOT NULL,
[Email] [nvarchar](30) NOT NULL,
[CreatedDate] [datetime] NOT NULL,
[LastLoginDate] [datetime] NULL,
[UserRole] [nvarchar](20) NULL
)



CREATE PROCEDURE [dbo].[Validate_User]
@Username NVARCHAR(20),
@Password NVARCHAR(20),
@UserRole NVARCHAR(20) OUTPUT,
@UserId INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @LastLoginDate DATETIME 
SELECT @UserId = UserId, @LastLoginDate = LastLoginDate, @UserRole=UserRole
FROM Users WHERE Username = @Username AND [Password] = @Password
IF @UserId IS NOT NULL
BEGIN
UPDATE Users
SET LastLoginDate = GETDATE()
WHERE UserId = @UserId
SELECT @UserId [UserId], @UserRole [UserRole] 
END
ELSE
BEGIN
SELECT @UserId=-1 
END
END

This is the code in asp.net for validating the user:

protected void ValidateUser(object sender, EventArgs e)
{
int userId = 0;
string constr = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Validate_User"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username", Login1.UserName);
cmd.Parameters.AddWithValue("@Password", Login1.Password);
cmd.Parameters.Add("@UserRole", SqlDbType.NVarChar);
cmd.Parameters["@UserRole"].Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@UserId", SqlDbType.Int);
cmd.Parameters["@UserId"].Direction = ParameterDirection.Output;
cmd.Connection = con;
con.Open();
userId = Convert.ToInt32(cmd.Parameters["@UserId"].Value);
Session["userRole"] = Convert.ToString(cmd.Parameters["@UserRole"].Value);
Session["userId"]=Convert.ToInt32(cmd.Parameters["@UserId"].Value);
con.Close();
}
switch (userId)
{
case -1:
Login1.FailureText = "Username and/or password is incorrect.";
break;
default:
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet);
break;
}
}
}

The problem is that UserRole is always returned as null and UserId returns an identity that is not valid (for example UserID =1 on db is returned as UserId=8) Note that when i execute the stored procedure I get the correct results.

Thank you in advance.

1 个答案:

答案 0 :(得分:0)

execute the stored procedure using the below command before reading the output parameters :

cmd.ExecuteNonQuery();