|
My apologies for not replying sooner to the people who commented on my post. However, I have been involved in quite a bit of in-depth testing of the newer web development tools on offer by Microsoft, which includes ASP.NET MVC, Blazor, and Razor pages.
I have a standard that I always go by when it comes to software tools... If it can't be figured out in 20 minutes it is not worth the effort. I use this standard as a basis for how well the corresponding documentation to the tools presents itself to the developer while allowing the developer to quickly set up scenarios that he or she would require for their projected endeavor.
What I found in my testing is that the web development environments now being offered by Microsoft are almost schizophrenic in nature while being accompanied by such erratic documentation from a wide range of sources as to be almost incomprehensible. So much of the documentation provides for so many differing implementations of the same thing that a developer would be more than confused as to which one is best for his or her circumstances in addition to which implementation actually works consistently.
As it regards ASP.NET WebForms being merely a prototyping software tool. This is completely false. WebForms was designed to be similar to current desktop development endeavors with an event driven environment. However, it did not fully encapsulate the concept of the thin-client, which was a radical departure from desktop applications where such clients were usually quite heavy.
The thin-client model became popular in the late 1990s and early 2000s as a result of the n-tiered client-server architecture then being promoted. In my view, the thin-client concept was and still is far superior to the now thick-client emphasis in development. The thin-client was there to promote only code on the front-end that dealt with the display and retrieval aspects of the interface, leaving the rest to various tiers in the overall application\system. Such a distributed nature of this type of development was and still is the primary factor in making distributed systems that could scale with very high levels of concurrency.
The person who replied that ASP.NET MVC could be made server-side like WebForms may have been able to accomplish such a development but it is not based upon the inherent MVC paradigm if such a development breaks with it, which is strictly based on a middle-tier model along with its corresponding middle-tier controller. The view then is used strictly for the interface. There is no allowance for pre-made components such as is found with WebForms to easily work with the front-end and middle-tiers of such an application, unless you consider the mass of JavaScript comprised components that currently make up the MVC front-end arena.
JavaScript as a basis for such components was never a wise choice by developers simply because the language was never designed for such usage and according to a recent document discussing the nature of the current JavaScript environments still has not been refined well enough to do so. In reality, this leaves MVC with a very limited basis for its implementation, that of content sites. In fact, until it was taken down from the Microsoft site, this emphasis was in fact promoted by Microsoft until they realized that people were using MVC for more than it was designed for.
Having worked on one of the largest MVC projects in the United States in 2010, I saw first hand how inept this paradigm was for complex database project development. The work required to implement such a basic framework was completely out of line with the requirements and deadlines the project had been based upon as I and my colleagues had to work far harder and longer to accomplish the same things that would have been required by the more sophisticated WebForms construct. The fact that WebForms may have not been as efficient as the MVC environment really made little sense to worry about given the huge complexities dinvolved.
Though my colleagues were highly capable software engineers and I admired them for such capabilities, it made little sense to me why they would put themselves in such a position that required them to work far longer hours with far more complexity than that which would have been required had the project been developed with WebForms.
The reason for all this was that my colleagues were of the opinion that this new MVC paradigm was the correct way to build new Internet applications.
They were abjectly wrong since there is no correct way to build such applications. The Internet is based upon a very old technology that was primarily designed to simply support basic messaging, not the complexities that are being sent over it now. In the end, the Internet's primary request and response methods are still the only two communication factors that are available to us at a general level, with lower level forms of communication being more recently implemented.
The idea that was promoted in one of the replies here that developers should have a greater understanding of how the Internet works in order to develop better applications is complete nonsense. That is not our job as software engineers and developers. Our job is to develop quality applications; not worry about what is going on underneath the hood as they say. That job is for network and hardware specialists.
And even if one knows how the Internet works, so what? You are still going to be bound with how any one software tool works to develop your applications.
Recently Microsoft has produced the Blazor environment and the new Razor Pages development paradigm; neither of which appear to work very comfortably considering that attempting to mix the two under certain circumstances yields unworkable conflicts. And yet one has a hard time attempting to figure out just where one environment ends and another picks up based on a lot of the documentation I have gone through.
Razor started off as a more efficient view-engine for MVC and now it is being touted as an alternative development environment on top of the ASP.NET MVC foundation. In fact, Microsoft is touting Razor Pages as the new WebForms. However, trying such an implementation out in its various formats had its own issues demonstrating that it was hardly ready for prime time development. The biggest one I found was the arcane techniques required to extract data when posted from the front-end. I imagine this will be corrected over time but it brings up the question as to why Microsoft would even tout such a development as a new form of a now denigrated technology. I suggest that it is most likely that Microsoft, very late in the game, realized their mistake by dropping the WebForms paradigm in the first place as ASP.NET MVC simply cannot compete with its sophistication and simpler style in the development of quality applications. And for all its inefficiencies, WebForms development, when done correctly, yielded far fewer defects that any other overly complex technology such as MVC would do so under stressful conditions.
In fact, Microsoft did attempt to port WebForms to its new ASP.NET Core environment but found that doing so was causing all sort of issues. As a result, they have been working their way back to it with their latest implemntation of Razor Pages. Nonetheless, the current mechanism in Razor Pages that appears to work consistently is a complete throw-back to Classic ASP, whereby C# code is inherently mixed with HTML markup in a single file. What is this? And now we are supposed to believe that after years of denigrating such a mixture of code it is supposed to be the "new thing"?
There are developments in Razor Pages with a new form of Code-Behind modular structure as was with the WebForms Aspx construct but I have not found it to work very consistently... At least not yet...
I am finding that people who promote the ASP.NET MVC style of development appear not to have been exposed to its drastic limitations when under stress with the development large-scale, complex, database, intensive applications. No one in their right mind would promote such a bare-bones framework as ASP.NET MVC under such circumstances that relies on so many auxiliary technologies to make it work with the complex interfaces involved.
I saw this first hand and ASP.NET MVC has not evolved to a point that would make such implementations easier. In fact, it is getting even more complex than its earlier incarnations. And complexity is the bane of quality software development...
Steve Naidamast
Sr. Software Engineer
Black Falcon Software, Inc.
blackfalconsoftware@outlook.com
|
|
|
|
|
Steve Naidamast wrote: There is no allowance for pre-made components such as is found with WebForms to easily work with the front-end and middle-tiers of such an application, unless you consider the mass of JavaScript comprised components that currently make up the MVC front-end arena.
@Html.TextBoxFor(...)
What do you call that? You can also write your own html extensions so you can have
@Html.LoginForm()
or a custom grid that outputs html with edit capabilities. There's nothing stopping you writing componentised code. As I said in my other reply, yes the state is handled differently but MVC is a different paradigm so of course some things need to be done in a slightly different way.
I spend my days working on MVC based CMS systems, I literally spend all day writing re-usable components that can be placed anywhere on a page so when you tell me this can't be done or is too hard\too much work then I have to be honest and think the issues is that you just don't know MVC well enough or you are struggling to change your thought processes. One of the biggest problems when MVC came out is that everyone wanted to continue doing WebForms, but just using MVC. You can't do that, you have to change your mindset, your way of dealing with issues, solving problems and implementing solutions.
Steve Naidamast wrote: The idea that was promoted in one of the replies here that developers should have a greater understanding of how the Internet works in order to develop better applications is complete nonsense. That is not our job as software engineers and developers. Our job is to develop quality applications; not worry about what is going on underneath the hood as they say.
Wow.
"Why should I have to learn how the human body works to become a surgeon? That's not my job, my job is to simply take the old heart out and put this new one in."
Steve Naidamast wrote: I am finding that people who promote the ASP.NET MVC style of development appear not to have been exposed to its drastic limitations when under stress with the development large-scale, complex, database, intensive applications.
I've used MVC on database based systems, web API based systems, index based systems....you name it I've done it. There is nothing inherent in MVC that stops you working with these things, and again I find myself coming back to the feeling that you've gotten comfortable using asp:DataGrid to maintain a table or asp.net maintaining your state for you and you just don't want to give that way of coding up. Not all sites need that kind of functionality anyway, the majority don't, and the majority of database heavy sites still tend to be light on forms etc.
|
|
|
|
|
First, you are not being asked to become a surgeon so your analogy is not very relevant.
Second, why should I have to bother writing HTML extensions when that is taking time away from my core development endeavor, which is completing an application?
And no, available HTML Helpers are not the equivalent of more feature rich server based components.
But you are correct about me not wanting to change my thought processes to understand and implement ASP.NET MVC applications. Been there, done that. Didn't like it and nor did I find it very efficient.
Your contention is that we have to completely upend our thinking in order to develop with ASP.NET MVC. Why? What is the purpose of having to go to a lower level of development, to do much more as a result, subsequently taking more time to do so. Doing this is certainly not providing any organization with any cost benefits in terms of development endeavors. Would you give up developing in C# or VB.NET to suddenly find you have to do everything in C++? Well, that is what is being more or less asked of web developers today.
CMS systems are not database intensive systems such as what is found in the financial industry where I worked for over 20 years in my career. You think that with brutal deadlines you are going to want to tinker with something like ASP.NET MVC when you need to get development done yesterday? I don't think so.
And your experience in no way outpaces mine as I have done as much if not more than you have across three distinct eras in the Information Technology profession.
The problem is that many developers who are detailed oriented seemed to have inherently gravitated to the ASP.NET MVC paradigm simply due its greater complexities. I can understand that as I watched one engineer develop an entire JavaScript Treeview control from scratch instead of using one of the available components. his reasoning was that he could do a better job than the components available at the time.
That was all well and good but doing what he did cost the project three weeks in time. And from what I have seen this appears to be perfectly acceptable to the ASP.NET MVC promoters. You admitted to some of this yourself. But that is not your job if you are a software engineer working to create line of business applications. Your job is to get the application completed as quickly and efficiently as possible most often within limited deadlines.
And maybe it is your thought processing that requires adjusting if you do not understand this...
Steve Naidamast
Sr. Software Engineer
Black Falcon Software, Inc.
blackfalconsoftware@outlook.com
|
|
|
|
|
Steve Naidamast wrote: First, you are not being asked to become a surgeon so your analogy is not very relevant
"Why should I understand gravity, frictional forces, stress points of materials and so on to become a structural engineer? That's not my job, my job is just to build a bridge that can carry traffic."
Steve Naidamast wrote: Second, why should I have to bother writing HTML extensions when that is taking time away from my core development endeavor, which is completing an application?
Because often what you want to use isn't available off the shelf and you have to write it yourself. What's important is that if you have to, that you can.
Steve Naidamast wrote: Your contention is that we have to completely upend our thinking in order to develop with ASP.NET MVC. Why?
Because it's a different paradigm. WebForms is server-based, state-managed, event-driven so people think in terms of "when I do this thing code runs on the server and at that point I interrogate and update state and everything else happens by magic". With MVC you need to think more about the separation of your components, you then need to output html\views that model binding can convert to a view model in your controller, your controller then has to best decide what domain model needs interacted with, and your domain model needs to know how to update the state of your system (be that amending database tables or whatever else). So rather than having one component responsible for multiple things, you need to be more granular in your thinking, and this ultimately results in better, more reusable, and testable code. The trade-off is that it does indeed often need a little more effort. However if the speed of development is the only metric you are working off then fine, MVC probably isn't for you, but that's your experience and quite a narrow one. Most big projects have many more metrics than speed of development.
Steve Naidamast wrote: CMS systems are not database intensive systems such as what is found in the financial industry where I worked for over 20 years in my career
My point about CMS systems is that they involve a lot of re-usable components, the thing you say MVC struggles to do. I have also worked with more traditionally database-intensive systems, *and* API heavy CMS systems and web API systems. At no point has the infrastructure of MVC held me back in any way at all.
Steve Naidamast wrote: And your experience in no way outpaces mine as I have done as much if not more than you have across three distinct eras in the Information Technology profession.
It's not often I genuinely LOL Bless. With respect you know nothing about me or my experience. If what you are saying is valid I don't know why you can't let your points speak for themselves.
Steve Naidamast wrote: I can understand that as I watched one engineer develop an entire JavaScript Treeview control from scratch instead of using one of the available components
That's dumb, but nothing to do with MVC.
Anyway, from your reply I think I can see where you are coming from better. You seem very much focussed on projects that are very tight on time where speed of development is the only important factor, so what you are basically doing is trying to use technology to solve managerial problems rather than technical ones. Rather than re-thinking management to seek out and accept realistic deadlines that result in better, more manageable software that takes longer to produce, you are dealing with companies that don't really care or understand how software is made, they just want it done tomorrow. If that's your experience then I can understand why you prefer WebForms and might not like MVC so much. But please understand that your experience is not the industry norm and just because MVC isn't right for the companies and environments that you work in doesn't mean the technology itself is flawed....it just means it might not be right for you, and there's nothing wrong with that.
|
|
|
|
|
I agree with your final comments as to what I experienced in my career in terms of the technical management I worked under in which practically all of these people were incompetent.
However, I worked in many companies and corporations both as consultant and an employee across a large spectrum of industries. So unless something miraculous has happened in the management suites of the United States, I really do not see what I experienced or that of many of my colleagues as no longer the norm considering I only retired in 2014.
Maybe you are privileged to work in a company or companies where quality software design takes precedence over deadlines and the like but I never have. And trying to change such technical management is a complete impossibility considering that most are arrogant, incompetents who do not see the need to go up against their own management. The fact that you suggested such a proposition demonstrates your lack of experience in the brutal, working world of Information Technology. Anyone who has had a wide breadth of industry experience under the belts would never say such a thing no matter how long they may have been a professional.
Aside from this it does not appear you have actually read what I have been saying but instead have looked to simply disagree with it.
I came up in the field when 4th generation development was a thing and ease-of-use was a primary motivation for Microsoft. When Java was introduced it was laughed at not only due to its massive complexity but the near impossibility of doing anything with it easily. Though this environment has gained a substantial foothold in our profession and it has come a long way, it still has many detractors for the original reasons. Should they change their thought processes also? The ASP.NET MVC environment and its subsequent add-on environments such as Blazor and Razor Pages to me, all appear to be nothing but added complexity for complexity's sake in what seems like an effort to mimic Java's original complexities. Our side of the profession is after all mimicking what Java web development always had, the MVC paradigm.
I don't doubt that ASP.NET MVC can be more efficient than WebForms but at what cost? Simply because you are doing well with it does not mean that everyone is. Currently there is a 72% job dissatisfaction rating in our profession according to one recent survey taken just a few months ago. And many current development professionals are not very happy with the current web development environments they are contending with. Should they also change their thought processes to accommodate yours or are they all wrong also.
I have also developed a wide variety of WebForms applications, all of which never gave my users any issues in terms of functionality or performance. As a result, I do not understand where you can assume that my development endeavors have been far more narrowly focused than your own. Like you are claiming, I have done it all and then some.
I just believe I have a much more realistic approach to my development efforts than you do. I really don't care how the Internet works. There is nothing I can do to make it better. I am just interested in how my software tools work with it.
But you seem to be centered on the tools you use and not the realities that surround their use in the real world. This is fairly common with the newer generations of technical professionals but based upon everything I have experienced and the reports that are appearing about modern web development it does not look like that these newer tools have done anything but creates new issues...
Mike Si, obviously a developer himself, who posted a very succinct answer on Quora in answer to the question as to why current web development is so complex had the following to say...
...
A smart question and you are very right. Web development today is unnecessarily complex. Why?
Let me start by saying - Most coders (including me) today waste lot of their time on sites like Stackoverflow, looking for solutions and fixes; because open source software is generally horrible, has a long learning curve, and documentation is poor at best. So, coders are not coding much, but reading what other coders have to say! Now to the reasons why web development is complex:
Lot of coders wasting time, developing open source/free software. Few, if any, gain enough market share, leading to lot of ‘dead’, useless, buggy or poorly documented products; making web developers life difficult.
Many coders think they know better than others, and go on to create their own library or framework, thinking they will become legends. No, that never happens, but other naive coders trusting such coders, end up wasting time learning badly written code.
There are simply too many little products out there. Poorly developed products just linger on for years, trapping new coders. Too much choice of mediocre products is not good.
For all the above reasons, today, if you need to develop a web site, it is impossible to find a fully-featured/comprehensive paid product, which is well supported, is less buggy, is well documented, has a long enough lifespan; because no commercial business can sell such a product and make money - thanks to availability of many horrible/buggy free products, and the illusion that software should be free. Remember, companies need to employ people and pay salaries! Good products which can make you productive coders will never be free.
To create a web site one has to use many products and technologies, leading to confusion, fragmented teams, more bugs, performance and security issues. This also adds to the complexity.
So, thanks to the current mentality - “We will not pay for software, software should be free”, that we are in such a big mess.
...
There are quite a number of people on the Internet who have posted similar complaints towards the current state of web development but I believe Mike says a lot in a nutshell...
Steve Naidamast
Sr. Software Engineer
Black Falcon Software, Inc.
blackfalconsoftware@outlook.com
|
|
|
|
|
Steve Naidamast wrote: Maybe you are privileged to work in a company or companies where quality software design takes precedence over deadlines and the like but I never have
I've worked in all sorts...I've worked in places where time is everything, and I've worked in places where they just want the job done right, and everything in between. I guess that's just one of the pitfalls of my inexperience
|
|
|
|
|
Steve Naidamast wrote: If it can't be figured out in 20 minutes it is not worth the effort. Found your problem.
And ironically you can't spend more than 20 minutes to learn something new but expect people to take that long to read your messages.
Social Media - A platform that makes it easier for the crazies to find each other.
Everyone is born right handed. Only the strongest overcome it.
Fight for left-handed rights and hand equality.
|
|
|
|
|
Hi there,
I want to encrypt my site web.config file for security purposes and why searching codeproject for this topic, I found this useful link https://www.codeproject.com/Tips/795135/Encrypt-ConnectionString-in-Web-Config
I followed the steps and was able to encrypt the connection strings on my local system.
Now, I copied the web.config file to my host server root directory.
Then on loading the site, I got this error-: Parser Error Message: Failed to decrypt using provider 'RsaProtectedConfigurationProvider'. Error message from the provider: Bad Data.
Then I tried searching the net and codeproject for solution but none was found by me pointing to error why uploaded to server. Maybe am not using the right keywords!
However, I came across a link that suggested I should change
<identity impersonate="true">
Or
<identity impersonate="false">
Which I did but no luck.
But I believe someone here on codeproject has the solution.
So my question is, how can I make this to work after uploading to server?
Note: Am using shared hosting for now so I don't have admin rights to do anything on the server.
Thanks in advance!
|
|
|
|
|
Did you read the article you've linked to?
Quote: ... if you encrypt your Config file, then your machine would store your keys and if you copy the Config file to a different system and try to decrypt it, then you might get an error.
The encryption keys are stored on the machine where the file was encrypted. You need to upload a decrypted version of the config file and run the encryption commands on the server where you application will be running. You can't encrypt on one computer and copy the encrypted file to another computer.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Ok thanks. Just as I stated on the original, I don't have access to command prompt on the server cos is a shared host.
How about if I create it using code behind on the server, will this error persist?
Once again, thanks for your help!
|
|
|
|
|
If your ASP.NET application has access to write to the config file, you could try encrypting the config using code:
Programmatically Encrypt the Connection String In ASP.NET Applications[^]
Otherwise, you'll need to talk to your hosting provider to see what your options are.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
|
I have finally solved this through the help of many valuable suggestions.
The problem I was having was as a result of not granting write and read permission to ASP.net.
|
|
|
|
|
I'm new to network computing. I am trying to build an ASP .NET database connection string. I have an Application windows 2012 server VM and an SQL windows 2012 server VM. My AD user is Administrator with a password. I have windows authentication turned on. Here is my connection string and VM information:
Domain: SQL.com
DB VM server computer name: win-5c3qtg1rebc.sql.com
From the Application server VM I can ping this computer name for the SQL VM: win-5c3qtg1rebc
ASP .NET connection string: @"Data Source=win-5c3qtg1rebc;Initial Catalog=KML;Integrated Security=SSPI"
When I run my application from Visual Studio I get the error:
"System.Data.SqlClientSqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL server. The server was not found or was not accessible."
Can someone look at my connection string and see what the problem is?
Thanks in advance.
|
|
|
|
|
Is the SQL instance on your VM machine the default instance? If not you will need to include the instance name in the server parameter of the connection string. e.g. server=machine\myinstance
|
|
|
|
|
I don't understand. What is the instance name. How do I get it?
|
|
|
|
|
You specified it when you installed SQL Server. Start up the "SQL Server Management" tool on the machine SQL is on and in the box for opening a connection there is a "Server name" box, drop it down and there will be a "Browse for more" option. That will scan running instances and show you what they are called.
|
|
|
|
|
You can also simply review the services listing to see the name of your SQL Server instance...
Steve Naidamast
Sr. Software Engineer
Black Falcon Software, Inc.
blackfalconsoftware@outlook.com
|
|
|
|
|
Hi,
Can any one please explain this change in "Change Authentication" dialog box. Previously it was easy creating a project with Individual user accounts, but now this is annoying, because I am forced to fill in the options.
Since there is no Image upload option I am typing it out:-
----------------------------------------------------------------
| Change Authentication - Individual User Accounts |
----------------------------------------------------------------
Domain Name
__________________________
Application ID
__________________________
Sign-up or Sign-in Policy
__________________________
What should I do to get past it and still have it create individual user accounts for me. Please point me to any available resources so that I can understand this dialog box and what should be done. I have tried searching but I couldn't find it anywhere.
|
|
|
|
|
I'm having some strange behavior in 2 or my API controller functions, in which I get a status code 401.
So say I delete my authToken in Local Storage, and Login for the first time. A redirect occurs to my "overview" page, in which the "overview" page loads the overview data, called with a client request, and then loads the "performance bar" data that is on every page. These 2 client calls always result in a status 401, unauthorized with a fresh sign in, But if I refresh the page, the 2 client calls work just fine. If I login say an hour later, the automatic login based on token expire data works fine.
What I tried:
I removed the Authorize flags from the 2 API controller functions and it works just fine in all scenarios.
All the other API controllers with the Authorize flag work just fine as well.
So I'm scratching my head on this. I'm thinking it has something to do with roles, in which I added them about 2 months ago. I was careful in how I programed the roles into the AuthToken, having 3 roles to enhance security.
I was also thinking that perhaps the localStorage of the token is lazy, and that the token is not present when the client call is made. But I did research on the internet and all says no, not the case.
I wonder if I can modify the client header to do a retry.
Startup to declare roles
services.AddAuthorization(auth =>
{
auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build());
auth.AddPolicy("RequireAdminOnly", policy =>
policy.RequireRole("Administrator"));
auth.AddPolicy("RequireAccountOnly", policy =>
policy.RequireRole("Customer"));
auth.AddPolicy("RequireEitherOnly", policy =>
policy.RequireRole("Administrator, Customer"));
});
Token Generation from my .Net Core Auth Service
var claims = new List<Claim>
{
new Claim("userID", wsUser.Id),
new Claim("userName", wsUser.AccountName),
new Claim("role", wsUser.Role ?? "Administrator"),
new Claim(ClaimTypes.Name, wsUser.FirstName),
new Claim(ClaimTypes.Email, wsUser.EmailAddress)
};
API Controller Function
[HttpGet("GetOverview"), Authorize(Policy = "RequireAdminOnly")]
public async Task<GetOverview> GetOverview()
{
return await _overviewRepository.GetOverview();
}
Client Header that is being sent
const httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + getAuthToken
})
};
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Looks like I have to write my own custom middleware to read the header, for the token and process it.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Well after another failed day to figure it out ...
What I did learn is that there are new methods in .Net Core 3.1 to validate views or razor pages, and new methods to validate a client API call from say Angular or React. Looks like the latter requires a new package called Microsoft.AspNetCore.ApiAuthorization.IdentityServer
So basically using a straight Autorize Attribute doesn't understand how to read the JWT token and authenticate it, thus me thinking that the token wasn't read fast enough for the API controller action to pickup. And then toss the Roles and Policies out the window because the token is not even read.
Now that I have to write an identity server, basically redesign and rewrite my entire Auth system. Like rethink the entire thing and implement it again. What a pain in the as.. But I guess I'll get a better app in the long run. I wasn't that happy with my current Auth system anyways, and those little glitches shows that it was poorly designed anyways.
Now I'm wondering if I should just shoot straight to .Net Core 5, so I can avoid another rewrite of my app's back end and configuration. The downside seems to be the lack of examples, or a clutter of examples that are outdated and pollute the internet. Feels like going through a pile of trash and cherry picking what I need.
Side Note:
I need roles or policies so I can store a single token, that can work on both the customer side and back end, without having several different Auth systems.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
After looking at hundreds of examples and tutorials on the subject, most tutorials where repeats of the age 21
I rewrote the way my app auths using JWT. Wasn't really a complete rewrite but rewritten anyways.
Finally got it to Authorize on a plain Authorize attribute. I got the error that the token needs 3 or 5 parts and that opened my eyes up to what the ValidIssuer and ValidAudience is, An account at Auth0 in which you use a third party Authority to generate extra secure parts of the JWT token. I suspect that the people that wrote the tutorials earlier never really explained what this does, and that my upgrade to.Net Core 3.1 simply exposed my security flaws.
The other confusion was that 3/4 of the tutorials were for authenticating razor pages and not api calls.
So I went from status 401 to 403, to 3 or 5 parts needed.
I'll turn off ValidateIssuer , ValidateAudience , ValidateIssuerSigningKey and ValidateLifetime and work on Roles and Policies.
So I'm back to not authenticating after login again, but I think I know why now. Might have something to do with cookie authentication. I must have some View and Razor stuff mixed in wrong. Or it's not aware of falling back to Bearer after login.
Something like that.
I'll sign up for a personal Auth0 account and program the authority later this week.
The Authorize attribute works, just didn't have a way to see the errors.
I have new authentication schemes now, injected into services
services.AddAuthorization(auth =>
{
auth.AddPolicy(AuthPolicies.Admin, AuthPolicies.AdminPolicy());
auth.AddPolicy(AuthPolicies.Account, AuthPolicies.AccountPolicy());
});
And a new AddAuthentication
services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddIdentityServerJwt()
.AddCookie(option => option.SlidingExpiration = true)<br />
.AddGoogle(CertificateAuthenticationDefaults.AuthenticationScheme, option =>
{
var googleAuthNSection = Config.GetSection("Authentication:Google");<br />
option.ClientId = googleAuthNSection["ClientId"];
option.ClientSecret = googleAuthNSection["ClientSecret"];
})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
var settings = Config.GetSection("Settings");
var secretKey = settings.GetValue<string>("Auth0:Secret");
var authority = settings.GetValue<string>("Auth0:Authority");
var audience = settings.GetValue<string>("Auth0:Audience");
var issuer = settings.GetValue<string>("Auth0:Issuer");
var expiresDays = settings.GetValue<int>("Auth0:ExpireDays");
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
options.Audience = audience;
options.Authority = authority;<br />
options.SaveToken = false;
options.RequireHttpsMetadata = false;
options.Configuration = new OpenIdConnectConfiguration();<br />
options.TokenValidationParameters = new TokenValidationParameters
{
ClockSkew = TimeSpan.FromMinutes(0),
ValidateIssuerSigningKey = false,
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = false,
ValidIssuer = issuer,
ValidAudience = audience,<br />
IssuerSigningKey = signingKey
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
services.AddCors();
});
New Auth Polices with authentication schemes added, and more roles.
I'll test this later tonight to see if it works now.
public class AuthPolicies
{
public const string Admin = "Admin";
public const string Account = "Account";
public static AuthorizationPolicy AdminPolicy()
{
return new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes("Cookies", "Bearer")
.RequireAuthenticatedUser()
.RequireRole(Admin)
.RequireClaim("jti", "sub", "unique_name", "role", "idpId")<br />
.Build();
}
public static AuthorizationPolicy AccountPolicy()
{
return new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes("Cookies", "Bearer")
.RequireAuthenticatedUser()
.RequireRole(Account)
.RequireClaim("jti", "sub", "unique_name", "role", "idpId")<br />
.Build();
}
}
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Got it to work by accident.
I figured out the JWT Token 3 segment 5 segment issue after reading tons of material. That was an issue with a null token value being passed by Angular V7. The answer was to change the key from "authToken" to just "Token" in localStorage. Go Figure.
I didn't fixed the SignIn, it still fails after redirect to the overview page. But at least I know that it's the client side passing a null token.
Got my Authentication schemes straightened out. So now I'm just down to the policies.
This works ...
I went through each claim one at a time, and only the jti works, in which jti has to be a unique GUID value. Well that is not proven yet.
public static AuthorizationPolicy AdminPolicy()
{
return new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes("Bearer")
.RequireAuthenticatedUser()
.RequireRole(Admin)
.RequireClaim("jti")
.Build();
}
This doesn't work ... Trying to add all the claims compiles, but doesn't authenticate.
Of course I need to test a token from the another role to validate that it really works.
public static AuthorizationPolicy AccountPolicy()
{
return new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes("Bearer")
.RequireAuthenticatedUser()
.RequireRole(Account)
.RequireClaim("jti", "sub", "unique_name", "role", "bsonId", "idpId")
.Build();
}
What is interesting is that I read that "Roles" will no longer be supported, and that "Claims" will replace it. Of course you can place a "Role" inside a "Claim".
Now to test the policies with other account tokens.
What sucks is that so many people copied the same examples of how it works and claimed them as their own writings polluting the internet with trash on the subject. And the pollution of so many examples and descriptions of every .Net Core Version makes it confusing as well. And then add Views, Context, Razor, Blazer, API into the mix, plus Azure support as well. Then Auth0 vs OpenIdConnect, and trying to build Authorization that works for all in Startup, plus your policies.
But overall in the end so far, what I thought was going to be a huge Authorization build just ended up being a cleanup and rework of my current design.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
modified 23-Jul-20 16:50pm.
|
|
|
|
|
So there was really nothing wrong with my code, or my design. It wasn't like a block of code was going to fix everything.
I have everything working now, except for new ideas such as a 15 minute token expiration that just keeps refreshing. So I need to read up on how to refresh tokens, but I've made preparation for it in my token claims and storage system.
What it boils down to is that I took a simple example of how to integrate Angular V5 with .Net Core 2.0 designed like learning how to walk and modified it to be like Amazon and it crashed. I tried to take a simple example of authenticating a user and took it to handle multiple authenticated user roles with multiple systems such as Google SignIn, Admin SignIn, Customer SignIn.
I can now see the progress made on .Net Core 3.2, in which what I wanted to do with .Net Core 2.2 has been realized. I remember Asp.Net Microsoft.Identity and how it was this huge Auth system with all the bells and whistles, but you had to use it there way or no way. So I created a hack of it in a smaller package size. With .Net Core 3.2, it's alacarte now, and I can choose the components I want to use to create my Auth system, very nice. I can package anything I want inside the Jwt Token and use it to also hold info like the user name, email address without having to go to the database to get it.
Basically .Net Core and Angular has really matured and seems to be spot on now in terms of building a huge web app that is fast, reliable and durable. So I'm not going to post any code or lead anyone down the rabbit hole here. My issue simply just needed a complete rethink of what I had already implemented and just do a complete fresh redesign of my Auth system.
Frustrated at first and didn't want to change, very happy today and embraced the new changes.
I feel very confident that I have a great Auth system now that is very secure.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|