@manhnguyenv

Welcome to my blog!

Exceptions

March 28, 2018 13:26

Question 1: Thread.CurrentPrincipal

In an ASP.net application I'm using a Login control with a custom membership provider that I wrote. What I want to do is to set Thread.CurrentPrincipal to my custom Principal object, just after the user is authenticated.

I'm using the setter: Thread.CurrentPrincipal and it sets the Principal object for me but, on all the consequent threads this CurrentPrincipal is overridden with the default one.

Here is my code for the Authenticate event of the Login control:

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)

    {

        string username = Login1.UserName;

        string password = Login1.Password;

 

        if (Membership.ValidateUser(username, password))

        {

            var login = sender as Login;

            var phoenixIdentity = new PhoenixIdentity("B", "Forms" , true);

            var principal = new PhoenixPrincipal(phoenixIdentity);

 

            Thread.CurrentPrincipal = principal;

            AppDomain.CurrentDomain.SetThreadPrincipal(principal);

 

            HttpContext.Current.User = principal;

 

            e.Authenticated = true;

        }

    }

For example, imagine that I login with the username A, everything goes well... Validation passes, but I hardcode the user with the username B in the Identity object which is set to the Principal object I set as the CurrentPrincipal object.

When I check which user is set to the CurrentPrincipal Identity at the end of this method it says it's user B. But when I load another page and then check what the Identity of the CurrentPrincipal is, it says it's user A.

So, how can I make my CurrentPrincipal object to be persistent across all other threads, and where/when does this Login control set the CurrentPrincipal object of the Thread?

 

You can handle FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs e) (in Global.asax) and set CurrentPrincipal here.

 void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs e){var phoenixIdentity = new PhoenixIdentity("B", "Forms" , true);var principal = new PhoenixPrincipal(phoenixIdentity);e.User = principal;}

Thread.CurrentPrincipal

http://jonkruger.com/blog/2009/04/13/hiding-threadcurrentprincipal-from-your-code/

Question 2: Claims

Please I need assistance in implementing a custom way of assigning claims to authenticated users. On successful login,

var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);        switch (result)        {            case SignInStatus.Success:                //Get the user                ApplicationUser user = UserManager.FindByEmail(model.Email);                //Ends here                ClaimsIdentity identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);                AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);

I use the userId to fetch the role and other information about the user from the datastore. Thereafter, I need to add claims about the user with those information such as email, role, firstName, Lastname, gender, etc. before redirecting to the user dashboard. This is the way I try to do it but the problem is that even after adding the claims at the login method, I am not able to retrieve it at the _loginPartial razor view

For instance when I want to display the email claim value at the login partial like this

var claims = ClaimsPrincipal.Current.Claims;    var principal = (ClaimsPrincipal)Thread.CurrentPrincipal;    var email = principal.Claims.Where(c => c.Type == ClaimTypes.Email).Select(c => c.Value).SingleOrDefault();

It returns null.

So, as a result, I can only access them on the same login method after adding them but I need to be able to access it from anywhere in the application. Please I will appreciate any assistance on how to be able to retrieve these claims anywhere else throughout the application.

Thank you.

Code sample

https://github.com/samfgl/TokenBasedAuthenticationSample

Token Based and Storageless Authentication With Microsoft Identity Sample

This simple ASP.NET MVC example shows how you can configure Microsoft Identity without existing of any persistence layer such as SQL Server or Entity Framework. To show how Identity is fully independent from storage layer.

Also this sample uses a simple string as a token to authorize users instead of username and password to demonstrate how we can use claim based authentication feature to configure Identity in such uncommon scenarios too.

Question 3: GenericPrincipal and GenericIdentity

https://docs.microsoft.com/en-us/dotnet/standard/security/how-to-create-genericprincipal-and-genericidentity-objects

https://msdn.microsoft.com/en-us/library/system.security.principal.genericprincipal(v=vs.110).aspx

https://stackoverflow.com/questions/16183217/how-to-get-custom-data-out-of-generic-principal-inside-an-aspx-code-behind

https://msdn.microsoft.com/en-us/library/system.security.principal.genericprincipal.genericprincipal(v=vs.110).aspx

Question 4: Windows Authentication

https://msdn.microsoft.com/en-us/library/ff649349.aspx

Using Windows Authentication

If the <authentication> element in your application's Web.config is configured for Windows authentication, use the following code in your Web application to check whether anonymous access is being used (and the authenticated user is the anonymous Internet user account [IUSR_MACHINE]).

WindowsIdentity winId = HttpContext.Current.User.Identity as WindowsIdentity;if (null != winId){  Response.Write(winId.IsAnonymous.ToString());}

Question 5: WindowsImpersonation

https://blogs.msdn.microsoft.com/jimmytr/2007/04/14/writing-test-code-with-impersonation/

Question 6: Form Authentication (code)

https://docs.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-security/introduction/forms-authentication-configuration-and-advanced-topics-cs

Question 7: AuthorizeAttribute

https://stackoverflow.com/questions/30658315/c-sharp-mvc5-easy-way-to-check-if-user-is-authenticated-in-each-controller-met

Question 8: CustomAuthorizeAttribute

https://stackoverflow.com/questions/19358802/overriding-authorizeattribute-in-mvc-4/19358907

Adding Web Forms to Register Users

https://docs.microsoft.com/en-us/aspnet/identity/overview/getting-started/adding-aspnet-identity-to-an-empty-or-existing-web-forms-project

WebAPI Basic Authentication MessageHandler

https://weblog.west-wind.com/posts/2013/Apr/30/A-WebAPI-Basic-Authentication-MessageHandler

Web API Security

https://www.c-sharpcorner.com/article/basic-authentication-using-message-handlers-in-web-api/

Web API Security: Custom Response Header

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-message-handlers

https://www.infoworld.com/article/2991458/application-architecture/how-to-work-with-message-handlers-in-web-api.html

External Authentication Services with ASP.NET Web API (C#)

https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/external-authentication-services

Enabling Google Authentication

Best Practices for Exceptions

https://docs.microsoft.com/en-us/dotnet/standard/exceptions/best-practices-for-exceptions

https://msdn.microsoft.com/en-us/library/seyhszts(v=vs.100).aspx

https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/exceptions

https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/index

https://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET

https://stackify.com/csharp-exception-handling-best-practices/

https://stackify.com/csharp-catch-all-exceptions/

https://dzone.com/articles/c-exception-handling-best-practices

https://www.c-sharpcorner.com/UploadFile/84c85b/best-practices-exception-handling-in-C-Sharp-net/

https://www.infoworld.com/article/2896294/application-development/best-practices-in-handling-exceptions-in-c.html

 

Categories

Recent posts