What pitfalls or consequences could there be when structuring a solution in 3 projects (.net core, vue.js and webapi)? - vue.js

I want to make a quick, safe and nice application.
For many years I have been programming in PHP and regular ASP. But wanted to go on with .NET and vue.js.
So I have an idea, I wanted to create and plan to do it like this:
I was thinking of using hosting from an external service.
Then I would have three projects:
domain.com/index - Vue.js which will be a SPA, where the user can filter through a catalog, press like and send few api requests (mainly get-requests).
secure.domain.com - Here I will have a .net mvc project where I can use identity. This will make it simple to handle/register users. I will also give the correct session here for authenticated users. And it will affect domain.com/index, where they only are allowed to do some of the things if they are logged in
api.domain.com - This will be the webapi api. Only authenticated users will be allowed to send some of the requests.
I have used several weeks at looking into how to structure this.
But as I do not have much experience with this.
What pitfalls and bad consequences do you see in structuring it like this?
Are there any heads up you want to give me? Or any other recommendations?
I have been trying to melt all of this together in one project, but that has been difficult, because they operate in different ways. So now I have ended up with this, and look forward to
Size of project
It will be a relative small project.
People should be able to register/authenticate themselves (through facebook/google/server login).
Authenticated People should be able to add records(links) to a database. When adding this to the database they may also want to upload files, and choose some additional information.
All people should be able to filter through the catalog of records (5000+) ( Here I am using vue.js/vuex/axios). Here they should be able to comment too on links too.
Webapi will have 8 entities/tables and one view which will GET all the information. 3 tables should be able to have POST.
So it is more or less a catalog, where people should be able to add records and find new ones.
I was planning to use the identity from asp.net core 3.1. It is a "template" where I can easily add 3rd party logins. (https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-3.1&tabs=visual-studio)
Additional questions:
Can you tell me how request from SPA will be authenticated in your API? (Jwt or cookie)? Why would you like to have a separate identity service, also Why you would like to use asp.net identity (is it because of ease of setup)?
I have not been thinking about authenticating API requests. Was thinking to only have authenticated users who can send POST-requests. And the rest will be get requests. Limited only from the server. Should I have some additional authentication? Does JWT make web APIs safe enough for my use?
Was thinking of using .net identity because it is simple. And I don't want to use time on setting it up.

Since this is your first project of this type, I would recommend to keep it simple.
Just create one web site. Otherwise you might get issues with the cookies not working for subdomains and you will also get issues with CORS. That is, you will get all problems at the same to time (configuration issues, infrastructure issues and the pain from writing the application itself).
You can still have a clean separation by using sub folders (or Areas in MVC) and by using class libraries for the backend (API) business logic.
Once you have mastered the basics (i.e. writing the actual application) you can start looking at other means of separation etc.

Related

Authenticating by Request Header in ASP.NET Core

I'm developing an intranet application that will be hosted behind an appliance that performs user authentication, then adds a unique user identifier to the header each authorized request it passes through. Which is to say, all the hard stuff is already done.
How can I configure ASP.NET Core to utilize the supplied header? User accounts with the associated request header are accessible from Entity Framework, but it's an Oracle provider, with a nonstandard schema. I'm using .net 5.0.
I assume this is relatively simple to implement, but I've been digging through documentation for a couple days and so far I've only found things that don't quite do what I need.
I'm not looking for a complete solution, just hoping to be pointed in the right direction. I'm not confident that what I've written so far is correct, but the project I'm experimenting on is based off the dotnet new mvc --auth individual starting template. Any advice or examples would be greatly appreciated.
If i get the question right, all the hard stuff was gone and now we just need to pull related information based on a given userId.
If that's the case, I would recommend to define your own AuthenticationMiddleware, that would not doing anything related to validate the user, but rather to pull user information from some where and cache it(with a reasonable expiration and clear cache by key mechanism).
Then, every request came after, just took the info from cache then build our own User object that would stick to each HttpContext. This is the final result we should aiming to.
All the process that should make use of AuthenticationSchemeOptions and AuthenticationHandler to build our own authentication middleware. Take a look at this would be good for a starting point.

What is a good architecture to add an API to an existing ASP.Net Core 2.2 MVC solution

When I started development of my current project I had no knowledge or prior experience of web development, ASP.Net (Core), C#, JS and so on.
With a lot of reading, excercising and testing I now have an ASP.Net Core 2.2 web application with multi-tenancy based on the database-per-tenant strategy hosted on Azure with Azure SQL as backend.
I have a solution with 2 projects:
the MVC web application that also has the .Net Core Identity from which I use the individual user accounts stored in ASPNet... tables (I did implement my custom UI, mainly so I could use the Localization middleware already used throughout the application)
a data layer that contains the db context's, the data models and the repository
Now I need at add an API.
The sole purpose of the API is cleary defined: give customers(tenants) the possibility to import and export data, most likely connected to other customer's application(s). This API will not be used by the UI. The API will not be hit with thousands of queries per second. It will be part of a business solution with 50 to 200 customers who will perform occassional import/export actions.
I have already implemented Identity and the authentication for the API should be done against the users setup in Identity but with a different authentication mechanism.
I have done a fair bit of searching and reading and found many tutorials/blogs on how to create a WebAPI with .Net Core but they all start from a new project and never go much more into depth. The once that really go in-depth are too complex for me ...
I have 3 questions unanswered at the moment although I know that there's probably more than 1 good answer to each of the questions but I think these are the likes of questions that many in my position, beyond the newbie/beginner but not yet a seasoned veteran, have and are searching for so I hope this post helps not just me but many others as well.
Question 1 - Architecture, where to create the API (project)?
There are 3 possibilities:
1 Add APIControllers to the MVC application (organize API-related classes in separate folders)
Benefits
quick and easy, everything else is already in place
deploys with the solution
Concerns
as it is part of the solution it becomes very monolithic, less flexible
Questions
can I implement a second authentication/authorization mechanism next to the implemented individual user accounts? (more detailed in the second question which is all about security)
2 Add a WebAPI project to the solution
Benefits
better separation but can still use/reference the resources of the other projects
probably gives benefits for scaling and tuning?
Questions
can I implement a second authentication/authorization mechanism next to the implemented individual user accounts leveraging the Identity of the MVC project? (more detailed in the second question which is all about security)
is this project separately published to Azure (or any cloud provider for that matter) using the www.example.com/api path (virtual directory) or is the solution published a whole?
3 Create a separate solution with the WebAPI project and include the data layer project
Benefits
full separation although sharing the use of the data layer project
completely independent with regards to deployment, scalability etc.
Concerns
maybe adds a layer of unnecessary complexity (the API will not handle thousands of requests per second)
Everything that is already configured/setup in the MVC project and that is required will need to be redone
Questions
can I include the data layer project in the solution (it is then part of 2 solutions) or should I reference it as a dll?
Question 2 - how to implement Authentication/Authorization that resides side-by-side with the Identity individual user account?
This is related only to the first 2 options of the architecture as in the third option the project would be on it's own.
The basic question is how to setup more than one authentication mechanism, one for UI users and another for API access.
First there is the choice of Authentication, most of tutorials blogs talk about JWT and Auth (OAuth?). I am not asking what the "best" solution is but which solution would be "preferred" by B2B customers who are the only ones that will use the API.
I am not sure how to redirect to the right authentication: when a request is sent to an API controller method with the Authorize attribute and the user hasn't been authenticated yet it needs to reply with an error.
Currently if a method with the Authorize attribute is executed by an unauthenticated user the user is redirected to the login page as configured in startup.cs:
public void ConfigureServices(IServiceCollection services)
{
...
services.PostConfigure<CookieAuthenticationOptions>(IdentityConstants.ApplicationScheme,
opt => {
opt.LoginPath = "/User/Login";
...
Do I need to configure this with something like the example I found below:
app.UseWhen(x => (x.Request.Path.StartsWithSegment("/api", StringComparison.OrdinalIgnoreCase)),
builder =>
{
builder.UseMiddleware<AuthenticationMiddleware>();
});
or is this configured in a different way?
In the case of creating the API as a separate project should I use the "Multiple startup projects" option? I guess this means that I need to create the whole startup.cs again?
Question 3 - if I want to offer my customers a REST API and an OData API, can I handle this through a single API or do I need to develop a second to support OData?
I know it is lengthy but I'm sure that others are looking for similar information and I'd appreciate any input.
Thanks

ASP.NET MVC 5 simple login

I need simple log in functionality in my project (logged in users can access and modify their profile). I've read a book "PRO ASP.NET MVC 5" by Adam Freeman where he quickly written a simple, short and elegant login mechanism just by using authorization and authentication filters and extending from some built-in classes. However, I just checked the internet and found many completely opposite approaches using classes such as Identity and Claim and achieved by writing LOTS of code, i.e. this or this.
Is it really necessary to implement a huge framework and write many lines of code just for a simple log in approach with some security? Is it really that bad to rely on authentication and authorization filters?
Yes, I am planning on publishing my project, but it's really very small.
What would be the best and the most beneficial practice for creating a basic log in functionality?
when you create asp.net mvc 5 webapp you will find asp.net-identity already exist you just have to make simple changes in the user to link it to your other entites

Is it necessary to build a separate API endpoint for mobile apps to access a Rails web app?

I have a web app implemented in Ruby on Rails 4, need an Android native app for it, I am really new to mobile development.
I am a bit confused as to what the mobile-web architecture should look like in this case. I've done some research online, there seems to be a few ways of doing this, but I still have some questions that I haven't been able to find answers for. Thanks in advance for all pointers.
1) do I really need a separate API for the mobile app? what are the issues in using my Rails app's existing controllers with respond_to format.json?
2) I've seen some online examples that suggest using an separate API namespace in the Rails app to serve mobile requests, e.g class Api::ApiController < ActionController::Base for the new controller, then add namespace :api do in routes.rb. With this approach, doesn't it imply that I'll need to duplicate quite a bit of my controller functionality in this new namespace just for mobile?
3) Regarding authentication, many examples suggest using token authentication, is the built-in Rails sessions management framework not good enough for mobile apps? or is it because session cookies work completely differently in a mobile app?
Appreciate your time.
It is not necessary, but it is, like you said, considered a best practice.
1+2) Having same controllers with respond_to/respond_with logic is a nice idea at first sight. But, from my experience, I can say, there always comes a day where API code start to differ with HTML client code. The mobile client might have a different UI and it is just natural that it will expect to consume your data another way as your web client does. The web client is specialized to one use case where an API should be more generic allowing multiple consuming ways.
The second issue that will arise is the fact that you cannot rely on your mobile users to always have the latest app version where with a webapp you can. So for the HTML app you can easily introduce non-compatible changes because you are delivering a proper client right within where for the mobile API breaking the API is at least concerning. Perhaps, you will want to maintain a backwards compatibility which will make your all purpose controllers ugly as hell. And without a proper api/v1 namespace you even can't have two different API versions at the same time.
You can avoid duplication of your logic by keeping your controllers very skinny and move the logic out into models (Service Objects are models too, not only Active Records).
3) Your mobile HTTP lib will to a high probability have a proper automatic cookie management. Having token based authentication is just again a best practice. If it is just a token vs session_id within cookie, there will be not much win. I can only think that it will be automatically secure against CSRF attack and you can disable this protection entirely for the API because your website users won't be allowed to consume the API, just by logging in to the site (an additional benefit perhaps). With session based authentication you will have to generate a CSRF token on first API request and set it within X-CSRF-Token cookie.
The big advantage of token based authentication is that it is extendable to more security, like introducing expire tokens, HMAC tokens etc, whereby session authentication is not.
See Using Sessions vs Tokens for API authentication
I would also encourage you to look at json:api. It comes from the creators of ember.js, who have thought about minifying decisions to take, when building APIs. Another interesting thing is an active_model_serializers gem. An intro to it is given within Rails: The Next Five Years by Yehuda Katz

To Make an API Centric Application or Not? - Laravel

So. I have embarked on the journey of learning Laravel in the last couple of weeks, and am thoroughly enjoying it.
It has come time for a site redesign and I thought it was about time to tighten up some of our functionality, so I am making the switch from CodeIgniter to Laravel.
I was wondering whether it is worth starting off with a RESTful API layer in Laravel (easy enough to create) and use it as a base even for the web application. In the future we are likely to build a mobile app that will need to use the API. So:
Is it worth having the web application connect to the API
and what is the easiest way/s to make calls to the API without having to write a bazillion
lines for cURL everytime I want to make a request?
It is definitely worth it.
I am currently redesigning a messy PHP code for an established hosting company turning it into beautiful Laravel code. I already have a mobile app working with it - Laravel makes it easy to return JSON data with one line -
Response::json('OK', 200);
or
Response::eloquent(Auth::user());
or
$tasks = Task::all();
Response::eloquent($tasks);
You don't need to use CURL as far as I know.
You can make all requests with simple AJAX, jQuery would simplify that.
Also using some MVC JS framework would help you make the application code structure more elegant for the client side, and the advantage is that you can easily package that into PhoneGap when you are ready to have your API take some real testing.
Today I posted on my blog about a simple example that you can try to see if this approach is worth your time : http://maxoffsky.com/code-blog/login-to-laravel-web-application-from-phonegap-or-backbone/
Check it out and accept the answer if you think it's on the right track.
As always, your results may vary, but this is exactly what I'm going through at the moment. I'm migrating a large .Net site with this API architecture and I've decided to keep it for Laravel.
I personally decided for this because:
More scalable. I can setup api.domain.com and then add additional
boxes/vm/whatever as our traffic grows. In fact, you could load
balance just the api by "round robin" or multiple dns entries for
that domain.
Future proofing for new sites and apps. Sounds like you're in the
same situation. I can see an app or two being added in the next year
or so.
Lost cost. You'll already be laying out your controllers, so really
it can be just a matter of setting them to RESTful and making small
tweaks to accommodate.
To be fair, some counter points:
Possibly additional load time, from processing through the API, though this should be minimal.
Additional security items to consider if you'd like to lock things down to just your app.
Either way, welcome to Laravel!
and what is the easiest way/s to make calls to the API without having to write a bazillion lines for cURL everytime I want to make a request?
#Sneaksta try postman chrome extension for calling rest services. you can create forms in this extension and pass data from these forms to you Rest services
https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?utm_source=chrome-ntp-icon