Asp.net Mvc 6 get user claims immediately after log in - asp.net

In a Asp.net Mvc 6 website I customized the out-of-the-box AccountController so that I add a custom Claim before calling userManager.CreateAsync(), both when registering
with a local account (email/password), in the Register() method of the controller
with an external provider (google/facebook), in the ExternalLoginConfirmation() of the controller
Now what I'd like to do is, immediately after the user logs in, both
in the Login() method after calling signInManager.PasswordSignInAsync() and
in the ExternalLoginCallback() method after calling signInManager.ExternalLoginSignInAsync()
...to retrieve that claim, ideally without hitting the DB to get the User.
I noticed that if I look at User directly after sign-in, the Claims collection is empty. However, if I look at it in a subsequent controller action the Claims collection is populated and has my custom claim in it.
The question is, why isn't the Claims populated immediately after sign-in (I guess the sign-in code doesn't refresh the CurrentPrincipal?) and is there another place to check directly after sign-in to get the claims without hitting the DB?

You could try to implement your own ApplicationUserStore and fill whatever properties of the user (or entity which is used as identity entity) you need.

Related

IdentityServer IsActiveAsync method not being called on the profile service

I'm using IdentityServer v4 to handle authorisation for my ASP.NET application, using Resource Owner flow.
I've implemented the IdentityServer4.Core.Services.IProfileService interface which has two methods, GetProfileDataAsync and IsActiveAsync.
When making a request to the token endpoint, the GetProfileDataAsync gets called as expected. We use this method to issue our claims.
However the IsActiveAsync method does not get called. I'd like to implement this method to determine whether the user is active in our database. At what point is this method supposed to get called?
The comment in the IdentityServer source (see below) suggests it should get called during token issuance, but the method isn't called when requesting a token. I suspect I'm missing something. Any help would be appreciated.
// Summary:
// This method gets called whenever identity server needs to determine
// if the user is valid or active (e.g. if the user's account has been
// deactivated since they logged in). (e.g. during token issuance or
// validation).
Task IsActiveAsync(IsActiveContext context);
Right now IsActiveAsync does not get called for resource owner password requests. I guess the assumption was that you wouldn't successfully authenticate a user if the user is inactive.
These details are not yet decided on - if you have a strong opinion on how this should work - please open an issue on github. We will lock down the API in late August.

Verify claims/roles in token with Web API 2 bearer token

I would like to confirm that the the claims in the bearer token are up to date on each API call so that I be sure that the given user still have access to the given method.
For example, for a method decorated with [Authorize(Roles = "admin")] I want to make sure that the user is an admin when the call is executed, not if the user was an admin when the token was issues.
After some looking around I am planning to
write a public class VerifyTokenAttribute : System.Web.Http.AuthorizeAttribute apply it globally and inside OnAuthorization check if the action is decorated with Authorize and if so, get the user info from the database and confirm that the roles match.
Is there a better way?
I planned on doing basically the same thing. In my case, there exists the definition of "system features" where a Role in the system can perform a number of system features. The features a role can perform can vary, and the administrator can change them any time.
So basically, on each request I should grab all the roles a user has, and for each one all the system features it can execute. I thought about something like creating an attribute that would look like this: [CustomAuthorize("Feature_Name")] and applying it to the controller (or action) level. Then, I would need to check if "Feature_Name" is a feature the current user can perform based on their roles.
Off course, that would require access to the database each time.
A possible enhancement would be to cache this information in a cache server, and the cache would be invalidated each time the admin changes the users privilleges. Something like that.
So, as Mayu said: Is there a better way?

ASP.Net MVC3 FormsAuthentication overall logged-in event

I have an ASP.Net MVC3 app. When the LogIn action is called, I use the MembershipProvider to validate the user and FormsAuthentication to set the cookie.
Additionally, I get some info about the user from a database and store it in Session.
When the user subsequently visits the site, they're already authenticated via the cookie, and I'm looking for somewhere to hook into so I can fetch the info about the user from the database again.
Is HttpApplication.AuthorizeRequest() the best place to do this? Obviously this is called for every request so I was hoping there was something I could use that just indicated the user had been authenticated - either explicitly after logging in or when they're authenticated automatically.
There are several events that get triggered on every request, HttpApplication.AuthorizeRequest() should work.
In order to only fetch from the database for logged in users, you can check the Name property of User.Identity which only gets set once the user authenticates:
if(!string.IsEmpty(User.Identity.Name))
{
//make call to database
}

whether ASP.Net Profile Provider's GetPropertyValue() is per request method or per session method?

I like to know, when will the GetPropertyValue() Method called?
I have written a proxy pattern for sql profile provider and i tried using the profile properties in my application.
I tried both authenticated and anonymous user mode, when ever the profile property values are accessed, profileProvider GetPropertyValue() method is called and it is hitting the DB to fetch the values.
I like to know, when will the profile values presist in the context?
For each & every request, I m seeing the profileProvider is called to fetch the values. If so, then what is use of having Profile in HttpContext.Current?

What to call after validateUser() for forms authentication?

I made a custom membership provider and overrode the ValidateUser method, but now I am confused. I am not using any Login controls, I just have a site wide login (username and password box) on a masterpage.
Questions:
Do I need to call the ValidateUser() method myself? If so, what are
the next steps to take? Do I create the auth cookie which methods do I need to call to complete the login?
I need to return some custom user data if the user is authenticated. Is it better to
call GetUser and check for null or just call ValidateUser and then
grab a user object?
Where and how should I store the custom data for the user? Is it stored in the identity object? Should I store it in the MembershipUser Object?
Yes, you verify that the credentials are correct by doing a call such as
Membership.ValidateUser(TextBoxUsername.Text, TextBoxPassword.Text)
If the above call returns true then you need to set the authentication cookie like so:
FormsAuthentication.SetAuthCookie(TextBoxUsername.Text, CheckboxRememberMe.Checked);
There I used a "remember me" checkbox if you want to login automatically next time.
To get the user details you can call
Membership.FindUsersByName(TextBoxUsername.Text)
The most handy place you can store the user details is the session.
You didn't ask, but just as important would be a log out page. The functionality needed to undo the login steps are:
FormsAuthentication.SignOut();
Session.Abandon();
Response.Redirect("~/login.aspx", false);//or homepage, or any other page

Resources