3

I am creating a Rest API (Spring Boot project) for Android App. What should be the ideal way of authenticating User from the database?

1. Querying database in Controller Class
2. Querying database in Filter Class
3. Using Spring Security

    public class TokenValidationFilter implements Filter {

        Connection connection = null; 

        @Override
        public void doFilter(ServletRequest request, 
            ServletResponse response, FilterChain chain)
          throws IOException, ServletException {
            final String accessToken = req.getHeader("accessToken");
            final String userId = req.getHeader("userId");

            // Do Sql Query to Authenticate User
        }

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {}
 }
Kalamarico
  • 5,466
  • 22
  • 53
  • 70
Ashish Rathee
  • 449
  • 3
  • 16

4 Answers4

3

You shouldn't be needing to add your own Filter.

When you use Spring security, it works by adding a filter only, for e.g., BasicAuthenticationFilter. And on top of this it allows you to manage things which otherwise you'd need to do on your own.

For e.g., it allows you to use the Authenticated principal by simple means of SecurityContextHolder.getContext().getAuthentication() as it works on the basis of ThreadLocal you can use this anywhere in your code.

What about managing Authorization for different URLs? Or managing CORS config?

All these things are achievable through a simple builder pattern for you while configuring Spring security using the framework.

Plus, if you want to go for OAuth later on, the security framework is integrated with it, you can get it working very easily by using AuthorizationServer and ResourceServer

Even for the simplest of configurations for a basic authentication you should go with using the security framework, rather than authentication using a be-spoke solution.

Also you can think that there are other things integrated with the security framework like Auditing your database transactions modified by which user, etc.


What you'll be writing (and going to refactor in future) in your own Filter is already written in the framework for you to use.

bitscanbyte
  • 650
  • 8
  • 14
  • I agree with this. Though I must say Spring Security can get so complicated that the OP's Filter idea is somewhat palpable. – Jose Martinez Apr 12 '18 at 12:20
  • For OP's use case the configuration of Spring security is minimal, even so I wouldn't say it can get complicated and it very clearly provides separation of concerns. – bitscanbyte Apr 12 '18 at 12:29
1
  • You should definitely avoid authenticating users in a Controller class.

  • Spring Security is the most recommended way for authenticating users in a Spring Boot application.

    • It is relatively easy to use and based on standard servlet filters. This way you can avoid writing your own custom filter.
    • Allows fine-grained control over endpoint and HTTP method combination.
    • Allows for different types of authentication - Basic Authentication, OAuth2, MTLS, etc.
    • Allows you to ignore security for certain endpoints.
    • To configure spring security, create a custom security configuration class which extends WebSecurityConfigurerAdapter.
    • It's relatively easy to configure the database with Spring security by writing a custom AuthenticationProvider. You make the calls to the database within this provider.
Indra Basak
  • 7,124
  • 1
  • 26
  • 45
0
  1. Querying database in Controller Class

No, doing like this will make your business controller tighly coupled with the authentication mecanism which is not the purpose of such kind of components

  1. Querying database in Filter Class

I assume you talk about Servlet Filter class. This way you'll probably reinvent the wheel and end up with a lot of home-made boilerplate code. And as you talk about Spring Security point 3, I assume that you have a Spring backend.

  1. Using Spring Security

Definetely the way to go if you have a Spring Backend. Spring security provides some standard authentication mecanism (BASIC auth for instance). You can add some Spring Security extension like OAuth2 or SAML if have such requirements. It is a widely used framework, so finding help should not be a problem. Besides, Spring Security allows you to create your own Security Configuration in case none of the standard is ok for you.

From a mobile app point of you, setting a Basic Authentication to get Json Web token and then access the API with the token should be pretty straight forward and maintenaible with Spring Security. Or you can rely on some standard like OAuth2 - OpenIdConnect. Either way should be ok with Spring Security.

slemoine
  • 367
  • 3
  • 8
0

I believe this is not a good software design practice to connect to the database on either the Controller or the Filter. This is not market practice. The most usual is to create a Data Access Object (DAO) that will be responsible for doing the queries properly. You can check out more details of this design pattern here: https://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm

The connection data, such as UserID, Password, Token, etc. are usually stored in an application configuration file (web.xml, AndroidManifest.xml or persistence.xml) and must be retrieved at run time. And the connection can be made via a parent class, for example GenericDAO, and be retrieved as an inherited attribute. Take a look here: How do I implement a DAO manager using JDBC and connection pools?

Organizing your code this way will help you split the responsibilities of your system, depending on the nature of each layer.

Fulvius
  • 511
  • 6
  • 15