0

I have a business logic layer and 2 applications which use this, a MVC UI and a Web API project.

One of the properties on my classes is CreatedBy and UpdatedBy, which should hold the userid.

    public Nullable<System.DateTime> CreatedTS { get; set; }
    public string CreatedBy { get; set; }
    public Nullable<System.DateTime> UpdatedTS { get; set; }
    public string UpdatedBy { get; set; }

Given there are multiple consumers of the BLL what is the best way to capture the userId?

A) - Set this within the BLL using Environment.UserName?

B) - Ask the client to set it and use model data annotation to make this Required

C) - Ask the client to pass this into any Create or Update methods in the BLL.

JackRussell
  • 40
  • 1
  • 6

2 Answers2

3

I would generally use Thread.CurrentPrincipal.Identity.Name.

To do so, you must ensure that Thread.CurrentPrincipal is set to a principal representing the current user. This is done in the UI tier, and will happen automagically if you:

Joe
  • 122,218
  • 32
  • 205
  • 338
1

If you're using FormsAuthentication in both MVC and WebApi, you can access properties User.Identity.Name.

int userId = db.Users.Single(r=>r.Name == User.Identity.Name);

In WebApi it will be HttpContext.Current.User.Identity.Name

This approach is quite secure. If you store userId on client-side, user will be able to modify it.

opewix
  • 4,993
  • 1
  • 20
  • 42
  • The authentication mode is none ``. We have an external service that runs on top of IIS that provides our authentication service. I just need help with the design of where to set the userid. BLL or client? – JackRussell Dec 24 '14 at 12:07
  • How are you determining current user if he is not authorized? – opewix Dec 24 '14 at 12:09
  • We have an external service that runs on top of IIS that provides our authentication service. I just need help with the design of where to set the userid. BLL or client? – JackRussell Dec 24 '14 at 12:11
  • BLL should keep `userId` and `authToken` dictionary. Each client should receive `authToken` and pass it to every request. – opewix Dec 24 '14 at 12:14
  • 1
    And the BLL should read the userID property and set this internally, so that the client is unaware? – JackRussell Dec 24 '14 at 12:19
  • 1
    Your authentication service should determine `userId` and pass it further to BLL. – opewix Dec 24 '14 at 12:29