Add multiple authentication mechanism for different api groups springboot - spring

We have an existing spring-boot application that supports basic Authentication with spring-security. this application uses spring templating so it accepts form data as input and saves sessions by doing authentication.
the login page is at /login after successful login it redirects to the home page of the website.
in the same spring boot service, we want to start supporting JSON based API which would be used by the Mobile app.
we were thinking of adding login API at /api/login which will be served for mobile devices.
is there a way where we can say
for /login use default authentication class and for /api/login use some other custom class which will read JSON data and will do Authentication.
we also want to use different page for unAuthorized access. as existing one renders custom HTML page. but with API we want to send JSON response with HTTP code.

Not a Java person, but generally speaking this can be done by creating a different controller that would handle the /api/login route.
Here's snippet below that might help :
[Source : https://spring.io/guides/gs/spring-boot/]
package com.example.springboot;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
#RestController
public class HelloController {
#RequestMapping("/api/login")
public String LoginAPI() {
// handle your authentication logic here.
}
}
I would strongly recommend against using the session based authentication. It's simply not designed for modern applications. If the option is open, you can take a upgrade to token based authentication (jwt.io), that would make your life much much easier.
If you must implement the session based authentication for mobile app as well. here's what you need to do
create the session on server
set the session key as a part of cookies in the response header
store the cookies in your app.
Include the cookies in request header in subsequent API calls from mobile app.
Again, not a Java person. Just hoping to help.

Related

Laravel Passport CreateFreshApiToken middleware vs web middleware

If i understand right, the CreateFreshApiToken-middleware uses a cookie-based authentication mechanism (https://laravel.com/docs/8.x/passport#consuming-your-api-with-javascript). Accordingly the use of csrf-protection makes sense.
What exactly is the difference between using the CreateFreshApiToken-middleware or simply accessing my API through the web-middleware, since both seem to be stateful.
In my scenario im working on a laravel-module (https://nwidart.com/laravel-modules/v6/introduction) which is supposed to be a REST-API. This API can only be accessed by authenticated user and also consumes user informations. The main module/platform uses a normal web authentication through a login form. The user informations are stored in the main module/platform.
What would be the best way to implement the REST-API module stateless (based on the authentication) and without interfering with the web-authentication which is used by the main module.
Should i considere making the API not restful?

Where to place credentials(User Name and Password) in Angular8 code securely to access secured SpringBoot Rest API

We developed a web application that uses Angular8 for the front-end and SpringBoot for Service APIs. We secured the SpringBoot application with Basic Authentication. So that when we need to call the API from front-end angular code we need to send the user name and password with the API headers.
So we are keeping the username and password in the environment.js file in the angular project. Those credentials are exposing in client-side code which loads into the browser.
So Anyone please help with where to place these credentials in Angular code?
Storing credentials in code is not recommended
To answer your question, you can store it in localStorage, sessionStorage or you can use HttpInterceptor in which you can automaticaly add headers to your every request. For more information, read Authenticaion using the HttpClient and HttpInterceptors
Recommend Using Token based authenticator - users will provide its credentials and get unique and time limited access token. you can manage token creation, checking validity, expiration.

(Ajax) Authenticate MVC Website user using a WebAPI

Trying to search for this results many many results for securing a WebAPI and how to secure an MVC application, but i could not find a solution.
What i want to achieve:
i have an MVC website with a modal Login form,
When the user enters he's credentials to the the form, an Ajax request is sent to a WebAPI with the credentials.
The WebAPI should return (i guess a ticket, since that is what i found).
The ticket would be then saved into the sessionStorage of the browser (no cookies),
Each page request to the website will check for the token, and enable/disable the parts that need to be secured.
All the examples i have found are showing either MVC only authentication,
or WebAPI authentication, but i could not find anything that does the described above.
The sessionStorage is available only for client-side use. You can manipulate or retrieve values from the storage using Javascript, but you can't directly read data from the server. Since MVC typically renders HTML Views server side, you have no options to send the token stored in the sessionStorage on each request.
The situation you described is an hybrid solution which can't be achieved without the use of cookies.
A simple solution is to set the login data (specifically the token if you will use a token-based approach) in a cookie issued by the Web API endpoint during the login phase.

Spring authentication through REST Service

I have a Webapp that consists of a REST API, and then another app that represents a frontend of this API. Both of this apps are developed using Spring.
Currently my REST api is not secured and data can be accessed directly by calling the REST endpoint without additional security info.
My frontend does have a login form (I'm using Spring Security for that), but does not have access to a database (the only access is through the REST endpoint). So the login process is done through an extension of the AuthenticationProvider that calls the REST api with the user and password and then responds with the authentication result. No authentication/authorization is kept on the REST side since to my knowledge this protocol should be stateless.
The problem is I need to incorporate ACL into my app, so that a user can only see those resources he's authorized to see (i.e. those he created). But given that my authentication process takes place on the frontend layer (which is where I keep a session attribute with the user info), I have two main problems:
How can I secure my REST channel?
How can I know which user is making the request on every communication, without explicitly passing the userdetails in each API request? is this even possible?
Doing it stateless and making two separate web application usually is overkill.
What I usually end up doing is.
Make my RestAPI stateful, because usually scaling is not an issue and simple form authentication will suffice.
Combine a Rest API/HTML Client in one Webapplication. If you want to keep it modular, you could create a Rest API module and integrate it as a JAR file in the lib folder of your web app.
Here is also some thread which goes through different alternatives for a rest API.
How to do authentication with a REST API right? (Browser + Native clients)

Is it possible to expose multiple endpoints using the same WebAPI controller?

I want to create a WebAPI service for use in my single page application but I also want it to be available for a mobile application too.
When users are using the SPA they are signed in using forms authentication and have a session cookie but if they're using the mobile application this wont be the case.
Is it possible to expose the same API controller as 2 different endpoints where one is authenticated using mutual SSL, a token or as a last resort basic auth and the other uses the session cookie?
For example take the following controller:
public class TodoController :
{
public IQueryable<TodoModel> GetTodos()
{
...
}
}
Can I add multiple routes that map to the same method?
https://myapp.example.org/api/todo
https://myapp.example.org/mutual-auth/api/todo
I want to configure IIS to use mutual SSL for the mutual auth endpoint and use forms authentication for the other endpoint.
Short answer: yes
This is a very broad question, so I won't go into excessive detail about every aspect. I think you should also take a look at BreezeJS because it makes things building these applications significantly easier.
DESIGN
Do you want to build in pure HTML and JavaScript or incorporate CSHTML? The decision is yours, but if you want to eventually create native-based applications using something such as PhoneGap Build, you'll want to stick to pure HTML and JavaScript so that you can compile the code later.
Do you want to use another JS library such as BreezeJS to make life a little easier when designing your controllers? Out of the box, your Web API controllers will be prefixed with api/{controller}/{id} in WebApiConfig. You may want to add {action} routing if you don't go with something like BreezeJS so that you can have more flexibility with your controllers.
Lastly, let's talk about the Repository Pattern and Unit of Work Pattern. This is a bit of hot-topic, but I find that usually creating a repository allows you a great deal of flexibility and it's great for dependency injection. Adding an additional repository layer to your controllers allows you to differentiate between different users or means of access such as a SPA or mobile application very easily. You can use the exact same controllers, but simply draw from different repositories.
SECURITY
You'll want to touch up a bit on [Authorize], [ValidateHttpAntiForgeryTokenAttribute], [Roles("")], and several other data annotations for starters. This is a huge topic which has a ton of reading material online -- invest in some research. Your controller can have multiple actions which have varying limitations on them, such as preventing CSRF on the SPA, but be less restricted on Mobile by either utilizing varying actions on the controller or drawing from separate repositories.
Can I add multiple routes that map to the same method?
https://myapp.example.org/api/todo
https://myapp.example.org/mutual-auth/api/todo
Yes, absolutely. You'll just have to do some extra work with your routing configuration files. With BreezeJS, you get access to not only /api/ but /~breeze/ which works very similarly.
You can secury your Web API using the way you want. For exemple, you can provide a custom Message Handler or a custom Authorization Filter to provide external authentication via token.
There's a full session from the ASP.NET Team that covers this, you just need to choose which one you will pick up:
Security issues for Web API.
Assuming you are hosting web API in IIS, if you enable the forms authentication, FormsAuthenticationModule establishes the identity. That is, if you look at HttpContext.Current.User or Thread.CurrentPrincipal after a successful authentication, the object of type IPrincipal will have the identity (which is FormsIdentity) and the IsAuthenticated property will be set to true. You can do the same thing for any other credential using a custom DelegatingHandler. All you need to do is to validate the credential (token, user id and password in basic scheme in HTTP authorization header or whatever) and set the HttpContext.Current.User and Thread.CurrentPrincipal to an object of type GenericPrincipal with GenericIdentity. After this, the same action method of a controller which is decorated with Authorize will work for both types of requests.

Resources