Rope Terson
Rope Terson

Reputation: 19

How do I query and store user data after windows authentication asp.net

I'm writing a MVC3 application that uses windows authentication. Once authenticated I have a unique id value for the user.

I need to query an external database (with read-only access) to get more information (ex. Name, email, phone, Dept.).

Where do I execute this query and where should I store the information returned so I don't have to continually query to get it.

Upvotes: 0

Views: 624

Answers (3)

PhillyNJ
PhillyNJ

Reputation: 3902

On your asp:login control, there is an attribute called "OnAuthenticate", which expects the following signature:

 protected void (object sender, AuthenticateEventArgs e)

From there you can perform an action if they pass or fail authentication e.g. in a Session like @Yuiry suggest.

Upvotes: 0

Dominic Zukiewicz
Dominic Zukiewicz

Reputation: 8444

You know their username through User.Identity.Name.

You can use Session state, but there is a pattern to use ModelBinders to do this. An easy-option is just to use Session State to store it, if you are happy it won't change.

--

For your data access, you just build some DataAccess capabilities to hit the DB with that as a parameter. One example is to use ADO.NET, and assuming SQL Server:

public DAO.User GetUserBy(string userId)
{
   var connString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
   using(var da = new SqlDataAdapter(connString, "SELECT * FROM Users where UserId = @p0")
   {
      da.SelectCommand.Parameters.Add("@p0", userId);
      var dt = new DataTable();
      da.Fill(dt);

      DAO.User dbUser = ConvertToUsers(dt).FirstOrDefault();
      return dbUser;
   }
}

Helper function to convert DataTable rows to DAO.User objects

private IEnumerable<DAO.User> ConvertToUsers(DataTable dt)
{
  var users = new List<DAO.User>(dt.Rows.Count);

  foreach(var row in dt.AsEnumerable())
  {
     users.Add(new DAO.User()
     {
         Name = row.Field<string>("FULL_NAME"),
         Age = row.Field<int>("AGE")
     });
  }

  return users;
}

Then the class to store the user

public class DAOUser
{
   public int Id { get;set; }
   public string Name { get; set; }
   public int Age {get;set;}
}

Upvotes: 0

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68687

Store it in in the Session so it's available across requests. Although some who are more religious will say your application should be stateless and you should pull from that database on each request.

Upvotes: 1

Related Questions