Asp .Net Core 5 Identity - How to fetch a user? - jwt

In the new SPA (react and angular) web templates for .Net core 5. I'd like to fetch the current logged in User. However, when I try to get a user in the controller the User doesn't have anything populated.
Does anyone know how to achieve this with the new Identity Classes?
I've made a repo of the vanilla reactJS template, the only thing I changed is the line highlighted in my screenshot below to show there's no user set.
I've done a bit of googling and these pages are all I could find on the topic, unfortunately, they don't give enough detail for me to be able to implement anything practical.
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-api-authorization?view=aspnetcore-5.0
https://learn.microsoft.com/en-us/aspnet/core/security/authorization/claims?view=aspnetcore-5.0

Backend:
ClaimsPrincipal currentUser = this.User;
var currentUserName = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
ApplicationUser user = await _userManager.FindByNameAsync(currentUserName);
On the frontend if you need yo access it
//with UserManager
UserManager<ApplicationUser> UserManager
#{
var user = await UserManager.GetUserAsync(User);
}
// with SignInManager
SignInManager<ApplicationUser> SignInManager
#if (SignInManager.IsSignedIn(User))

To answer my own question.
In order to populate the User detail in the HttpContext you have 1 of 2 routes. Either change
services.AddDefaultIdentity<IdentityUser>();
to
services.AddIdentity<IdentityUser, IdentityRole>();
or you can continue to use the Core Identity
services.AddIdentityCore<IdentityUser>();
but then you also need to implement your own Microsoft.AspNetCore.Identity.ISecurityStampValidator and add it as transient services.AddTransient<ISecurityStampValidator, MyValidator>();
Your MyValidator implementation will be responsible for validating the cookie. You can see the default implementation here on github
Edit: Under the hood services.AddDefaultIdentity<IdentityUser>(); uses services.AddIdentityCore<IdentityUser>();. I feel like its importatnt to know this.

Related

How to configure resetpassword

I am using IdentityServer3 for authentication. Users are stored using AspnetIdentity framework. I wanted to provide reset password functionality to users. I want to provide this functionality in IdentityServer hosting application. I have gone through several posts here here here and this what I have done so far:
1>I have created custom user service derived from AspNetIdentityUserService.
2>Created resetpassword.html and put it in template folder. (documentation)
3>It's not necessary to create a CustomViewService, so I added LoginPageLink in AuthenticationOptions and now the link is available on login page.
4>Created ResetPasswordController
public class ResetPasswordController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ResetPassword(string username)
{
// call customservice here and reset password
return View();
}
}
Issue
when i click on the resetpassword link, i get error
The view 'Index' or its master was not found or no view engine
supports the searched locations. The following locations were
searched: ~/Views/resetpassword/Index.aspx
~/Views/resetpassword/Index.ascx ~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx ~/Views/resetpassword/Index.cshtml
~/Views/resetpassword/Index.vbhtml ~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml
I know why the error is, its because we don't have corresponding view in Views folder where MVC framework in looking for. My view resetpassword.html is in template folder. And that's the confusion. Identity server is using Angular to build its views.
If I decide to use angular then
1>How do I create and pass model to resetpassword.html.
2>How do I wire-up my CustomUserService to controller.
If I use ASP.NET MVC then
1>I need to add resetpassword.cshtml in Views folder and also a new Layout.cshtml in shared folder.
2>Doing so MVC scafolding will add bootstrap resources (css,js, jquery). The version may not match with IdentityServer's embedded resources.
I am comfortable coding ASP.NET MVC but worried adding bootstrap resources twice in the solution.
What is the best and easy approach here. Any sample example will be greatly appreciated.

App with no DB: You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class

First things first. I'm a complete OAuth newbie. This will be my first stab at it, and things are getting hairy...
I'm writing a single page application using Durandal & Web API.
The user needs to be able to login using any social network.
I don't have access to a database whatsoever, I have to call an unprotected 3rd party web service which I consume server-side, and need to protect using OAuth.
So I've managed to add the files to my solution which generates the login using facebook contol/button (created a new MVC4 web application, and did a manual copy and paste of all the auth related files, updated bootstrappers etc..), and the code seems to work for the most part.
When facebook redirects back to
[AllowAnonymous]
public ActionResult ExternalLoginCallback(string returnUrl)
{
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(this.Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
if (!result.IsSuccessful)
{
return this.RedirectToAction("ExternalLoginFailure");
}
if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
{
return this.RedirectToLocal(returnUrl);
}
//code removed for brevity ....
}
I get the error specified once the following line tries to execute.
OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false)
I've removed the [InitializeSimpleMembership] attribute from the controller, as I don't have a database.
Please forgive me if this is the dumbest question ever, but...
Why does the login fail? I mean at that point, isn't the app trying to log into facebook, why does it need a databse? Or am I correct in saying I can remove/replace that code section, with a login/authorise call on the web-service I'm using?
Not the dumbest question ever. Not by a long shot. But you are getting the error because your membership provider is still set to use the SimpleMembershipProvider and OAuthWebSecurity will use the default membership provider. If you don't want to use a database you will have to create or find a different membership provider to use.
EDIT:
I know you said you don't have access to a DB but if you can use SQL Compact you can just stick with the default SimpleMembershipProvider(check out Hanselman's blog) or DevArt has a SQLLite provider. Also the MemFlex Project has a RavenDb provider. If none of those work I think you might just have to write your own.

ASP.NET Web API Authorization with AuthorizeAttribute

Using the new ASP.NET Web API beta. I can not seem to get the suggested method of authenticating users, to work. Where the suggested approach seems to be, to add the [Authorize] filter to the API controllers. For example:
[Authorize]
public IEnumerable<Item> Get()
{
return itemsService.GetItems();
}
This does not work as intended though. When requesting the resource, you get redirected to a login form. Which is not very suitable for a RESTful webapi.
How should I proceed with this? Will it work differently in future versions?, or should I fall back to implementing my own action filter?
Double check that you are using the System.Web.Http.AuthorizeAttribute and not the System.Web.Mvc.AuthorizeAttribute. This bit me before. I know the WebAPI team is trying to pull everything together so that it is familiar to MVC users, but I think somethings are needlessly confusing.
Set your authentication mode to None:
<authentication mode="None" />
None Specifies no authentication. Your application expects only anonymous users or the application provides its own authentication.
http://msdn.microsoft.com/en-us/library/532aee0e.aspx
Of course then you have to provide some sort of authentication via headers or tokens or something. You could also specify Windows and use the built in auth via headers.
If this site is mixed between API and actual pages that do need the Forms setting, then you will need to write your own handling.
All the attribute does is return an HttpUnauthorizedResult instance, the redirection is done outside of the attribute, so its not the problem, its your authentication provider.
Finally, I've found a solution at:
ASP.NET MVC 4 WebAPI authorization
This article shows how you can fix this issue.
You are being redirected to login page because forms authentication module does this automatically. To get rid of that behavior disable forms authentication as suggested by Paul.
If you want to use more REST friendly approach you should consider implementing HTTP authorization support.
Take a look at this blog post http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-membership-provider/
ASP.NET 5 Introduced the new Microsoft.AspNet.Authorization System which can secure both MVC and Web API controllers.
For more see my related answer here.
Update:
At that time 2 years ago it was Microsoft.AspNetCore.Authorization.
As #Chris Haines pointed out. now it resides on
Microsoft.AspNetCore.Authorization.
From .NET core 1.0 to 2.0 many namespaces have been moved i think.
And spread functionality between .net classic and core was obscure.
That's why Microsoft introduced the .net standard.
.net standard
Also, look at my answer for:
How to secure an ASP.NET Web API
There is a NuGet package I have created which you can use for convenience.
If you're using a Role, make sure you have it spelled correctly :
If your role is called 'Administrator' then this - for instance will not work :
[System.Web.Http.Authorize(Roles = "Administator")]
Neither will this :
[System.Web.Http.Authorize(Roles = "Administrators")]
Oops...
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Produces("application/json")]
[Route("api/[controller]")]
public class CitiesController : Controller
{
[HttpGet("[action]")]
public IActionResult Get(long cityId) => Ok(Mapper.Map<City, CityDTO>(director.UnitOfWork.Cities.Get(cityId)));
}
Use
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
Filter with authentication type

ASP.Net MVC 2 Forms Authentication cookieless = "UseUri" while submit authorization fails

I just started working with ASP.Net MVC 2.
I created a new ASP.Net MVC application and created one vehicle controler with a database table connected with LINQ. Then created forms authentication mechanism for the application and tried to use the uri instead of cookies it was working smoothly but when i submit the form by creating a "Create" view from the controler using the utility it just dont work. The autherization got failed and asking to enter the user name and password again.I had created the authorization mechanism by adding Authorise attribute to the Controller so as to get authorized for all the actions.
namespace MVCNEW.Controllers
{
[Authorize]
public class VehicleController : Controller
{
But if i use the cookies instead of uri it works fine.
Thanks in advance...
Please see http://forums.asp.net/p/1517391/3634908.aspx for an official response.
Summary: Cookieless Session support is essentially obsolete, and the MVC framework isn't likely to include additional support for it.
I found the problem and a solution.
This was due to some error in the framework. They are not creating the Uri string for the Form action while calling
Html.BeginForm()
But if we make it call overloading of this method like the providing the Controller name and Action name it is working fine.
view plaincopy to clipboardprint?
Html.BeginForm("Create","Vehicle")

Impersonating user with Entity Framework

So we have our web app up and going with entity framework. What we'd like to do is impersonate the current user when we're accessing the DB. We're not interested in setting impersonation up in our web config.
Ideally using something like this: Link when we're about to access data.
UPDATED: I'm looking for a way to abstract this code out so I don't have to have it in every repository function call.
Your EF connection string is going to need to be set up for using a trusted connection.
You won't need to set up Impersonation in your web.config, but you do need to be using Windows Authentication.
Then just do this:
using (((WindowsIdentity)HttpContext.Current.User.Identity).Impersonate())
using (var dbContext = new MyEntityFrameworkContainer())
{
...
}
Any code inside the curly braces of the using statements will run as the authenticated user.