Custom blazor server-side authentication - c#

I am new to blazor and stumbled across a problem when trying to implement authentication in my app. For now, I need to store all my users' data in JSON file and do not have a SQL DB to refer to, which, as I understand is needed to implement authentication.
As for now I have a list of users and check if the user is in my list of signed in accounts, then call markAsAuthenticated
public void markUserAsAuthenticated(string emailAddress)
{
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, emailAddress),
}, "someType");
var user = new ClaimsPrincipal(identity);
NotifyAuthenticationStateChanged (Task.FromResult(new AuthenticationState(user)));
}
I would like to add roles or claims now to be able to include them in the component, but find it difficult to understand, what the following steps should be.
Most of the tutorials use Authorization services provided by VisualStudio, but we work in VSCode and I would like to implement this myself, so I can use the list of users I have.
I would also like to find out if I can use cookies or JWT in my app and if there are any good tutorials for that or suggestions considering work with VSCode and server-side work, thanks in advance!

If you want to use cookies you need to use a razor page (.cshtml). You can have a razor page inside a Blazor application. It's the same code you'd use in a traditional razor application (pre-Blazor).
There's nothing Visual Studio specific to this that I know of.
See https://blazorhelpwebsite.com/ViewBlogPost/36

Related

Change password remotely through API for Identity server

I just received an .Net API that uses Identity server for Authentication. I have never used Identity server before. So I'm lost looking for info.
Here is my code for authentication.
[HttpPost]
public async Task<IHttpActionResult> Post([FromBody] Login loginInfo)
{
OperationResult<string> result = new OperationResult<string>();
result = await GetAuth(loginInfo);
return Ok(result);
}
private async Task<TokenResponse> GetAuth(Login loginInfo)
{
var client = new TokenClient(Constants.IdSrvToken, Constants.ClientId, Constants.ClientSecret);
return await client.RequestResourceOwnerPasswordAsync(loginInfo.Usuario, loginInfo.Password, Constants.Scope);
}
This works ok. But I need to create a new API method that receives the current and a new password and change it. The TokenClient class doesn't have any useful methods that I can use, and can't find information related to how implent the password change.
Any suggestions where I can find info?
Thanks in advance.
There will not be one. The whole point of using Identity Server - and other providers like it - is to delegate responsibility for authentication to it, primarily so that apps and APIs have no visibility of user credentials. IS also has very little awareness of "users"; they’re just an abstract concept to it. Something like ASP.NET Identity is more focused on users.
Using resource-owner flow is quite counter to the whole intent of OAuth2, and should not be used in virtually all circumstances. If you’re using IS just for that, adding it to the equation is largely pointless. It doesn’t solve most of the problems OAuth2 was designed to solve, and you also get no Single Sign On.
In practice usually you would have web pages on (or alongside, on the same server) IS that provide the password change functionality, and you would give users a link or redirect them to those pages. I suspect most people using IS who want to manage users either integrate something like ASP.NET Identity or add their own pages. There are many articles written on the former; here is one as a starting point. It’s not exactly trivial but quite doable.
If what you have is a legacy app that is unlikely to migrate to using OAuth2 as intended, then ultimately your code just needs to change the stored password (or hash as it hopefully is) wherever the users are stored; e.g. a database table somewhere. IS won’t help with that though; you need to write your own code for that.

Using Identity.UI in WebAPI project

I'm pretty new to Asp.NET and would like some more information on how to proceed. I have a standard WebAPI project which contains the standard weather template - I'm trying to apply some authentication via registering/logging in. I know theres a way to have template do it for you when create project, but for web api it doesn't let you do a local database which I want.
So right now I've attached the Identity.UI package to give me access to this method and generate the migration for identity tables
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
which allows me to use the UserManager to register a user and for login I do this:
if (!ModelState.IsValid) return BadRequest();
var result = await m_userManager.FindByNameAsync(user.Email);
var correct = await m_userManager.CheckPasswordAsync(result, user.Password);
if (!correct) return BadRequest();
return Ok(new { token = m_tokenService.BuildToken(user.Email) });
My question is a correct way of handling registering and login via WebAPI because the Microsoft.AspNetCore.Identity.UI package as the name suggests provides razor pages for login/registering which I don't really need which makes me believe this isn't correct. Is there downside/problem doing it this way, or is this a cleaner way of doing this.
The default Microsoft.AspNetCore.Identity.UI package provides a razor page for login/registration that seems redundant for web api .
For implementing Microsoft identity on web api to handle basic individual user accounts , you could try to use JWT tokens , refer to the following links which are good tutorials about using JwtBearer Authentication in an ASP.NET Core API Project :
https://wildermuth.com/2018/04/10/Using-JwtBearer-Authentication-in-an-API-only-ASP-NET-Core-Project
https://dotnetdetail.net/asp-net-core-3-0-web-api-token-based-authentication-example-using-jwt-in-vs2019/

C# Web API 2 & Angular - Microsoft Account Authentication

I've asked the question below a couple weeks ago and I didn't get a working answer. Or maybe just not suitable for my case.
C# Microsoft Authentication Get logged user from controller
So I thought maybe I wasn't asking the right question. What i'm trying to do is create an app which has a C# Web API 2 backend and an Angular 2 frontend. Now, I want that my authentication be using people's Microsoft Account which means this will be an external authentication.
What's the best way of doing this? It would be very much appreciated if you can give a link on a blog or article that explain what I'm looking for. On my link above I've used msal.js and so far it was working fine for me until I had to get the logged user's details. It was possible from Angular's side but I want to do it in Web API so it is more secured.
Thanks in advance!
If you are using OpenId, you have claims that are returned when user is authorized. I am assuming you are using Azure B2C for authorization in which case you can select clams that will be returned as part of token.
For example, if you want to fetch user id:
var userId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier")?.Value;
Email:
string userName = ClaimsPrincipal.Current.Claims.Where(x => x.Type == "emails").FirstOrDefault()?.Value;
It depends what claims your authorization has returned, easiest way would be to put breakpoint on
ClaimsPrincipal.Current
and inspect it, it should return list of claims.
From your code in the previous post, it looks like you need to read from the ClaimsPrincipal instead. ClaimsPrincipal is the implementation of IPrincipal when you use OAuthBearerTokens, so of course you can get the username from CurrentPrincipal.Current.Identity
From this documentation
https://msdn.microsoft.com/en-us/library/system.security.claims.claimsprincipal(v=vs.110).aspx
https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-devquickstarts-api-dotnet
public IEnumerable<Models.Task> Get()
{
var user = ClaimsPrincipal.Current;
...
}
i do with this example
https://github.com/Azure-Samples/active-directory-b2c-javascript-angular2.4-spa
and it work well

Issue with posting on business page of facebook using c# sdk

I have read many many articles tonight and still do not understood what I shoud do to post on business page of facebook. Here is my code:
string token = getHtml("https://graph.facebook.com/oauth/access_token?client_id=clientID&client_secret=secretKey&grant_type=client_credentials");
token = token.Replace("access_token=", "");
FacebookClient fbClient = new FacebookClient(token);
var args = new Dictionary<string, object>();
args["message"] = "Testing 12qwe3";
fbClient.Post("/pageID/feed", args);
It always says app not authorized. How to authorize it? I read so many articles, but still not able to do it.
I am posting this after totally failing from researching many articles. Kindly let me know whats wrong?
----UPDATE
I did the first part, by making myself the manager page and then creating an app and then providing that app the ability to manage pages and publish etc...but again another issue when i do so even using the above code i still get the same error.But when i use the tools (GRAPH API EXPLORER) portion of facebook site and select this app and generate a token .I than use that directly in app and it posts fine. Kinldy let me know whats wrong!

How to control the "flow" of an ASP.NET MVC (3.0) web app that relies on Facebook membership, with Facebook C# SDK?

I want to totally remove the standard ASP.NET membership system and use Facebook only for my web app's membership. Note, this is not a Facebook canvas app question.
Typically, in an ASP.NET app you have some key properties & methods to control the "flow" of an app. Notably: Request.IsAuthenticated, [Authorize] (in MVC apps), Membership.GetUser() and Roles.IsUserInRole(), among others. It looks like [FacebookAuthorize] is equivalent to [Authorize]. Is fbApp.Session != null essentially the same as Request.IsAuthenticated?
Also, there's some standard work I do across all controllers in my site. So I built a BaseController that overrides OnActionExecuting(FilterContext). Typically, I populate ViewData with the user's profile within this action. Would performance suffer if I made a call to fbApp.Get("me") in this action?
I use the Facebook Javascript SDK to do registration, which is nice and easy. But that's all client-side, and I'm having a hard time wrapping my mind around when to use client-side facebook calls versus server-side. There will be a point when I need to grab the user's facebook uid and store it in a "profile" table along with a few other bits of data. That would probably be best handled on the return url from the registration plugin... correct?
On a side note, what data is returned from fbApp.Get("me")?
The Facebook C# SDK provides an action filter called [FacebookAuthorize] that will handle the authentication like you describe. And yes, fbApp.Request == null is the correct way to determine if the user is authenticated. I think I'll add a property on the next release called IsAuthenticated to make it easier.
You are correct in using the Javascript SDK for login. Basically, how it works is the Javascript side creates the cookie that FacebookApp reads and verifies. For a non-canvas app you basically have to use the Javascript SDK. You could do it all manually with OAuth, but that would be a huge pain.
And regarding the result of fbApp.Get("me") the result is a JsonObject. You can access it two ways:
// Using dynamic (.Net 4.0 only)
var app = new FacebookApp();
dynamic me = app.Get("me");
string firstName = me.first_name;
string lastName = me.last_name;
string email = me.email;
// Using IDictionary<string, object> (.Net 3.5, .Net 4.0, WP7)
var app = new FacebookApp();
var me = (IDicationary<string,object>)app.Get("me");
string firstName = (string)me["first_name"];
string lastName = (string)me["last_name"];
string email = (string)me["email"];
We have more code samples on our Codeplex wiki.

Categories