jsp – Authenticating the username, password by using filters in Java (contacting with database) – Stack Overflow

Authorization using filters in java ee

Java EE implementations typically allow you to set-up login modules. Those contain the actual code for doing authentication with a lot of different systems. These include a local XML file, a database, LDAP, Kerberos and quite a bunch of others.

You don’t have to write those yourself, they are already provided for you.

Your code only triggers authentication (or declares resources to be protected and Java EE triggers authentication for you) and knows nothing about the actual authentication mechanism. The actual authentication is typically configured outside your code. Some Java EE implementations allow you to specify this within your EAR (e.g. via a -service.xml file on Jboss AS).

A potential disadvantage is that these modules are specific to your Java EE implementation (e.g. JBoss AS, Glassfish, etc). If you configure it outside your code, someone has to redo this again for each different Java EE application server you want to run your code on.

Next to that, the ways in which Java automatically triggers authentication for you (declarative security) are rather crude. More often the triggering of it is done programmatically, so you have greater control over how your login box works and when it exactly takes place.

See the following for a nice write up how to do this: http://it-result.me/servlet-3-programmatic-authentication-api/

Alternatively, there is indeed also the way limc explains. Via that approach, you completely ignore the APIs Java EE offers for this and just build your own code that typically queries a DB and stored some object into the HTTP session. The disadvantage here is that your security context does not automatically propagate and you have to manually pass along this object or provide the code that needs to check for the authentication with access to the HTTP session.

Especially for business beans accessing the HTTP session is a bad practice.

Finally, Seam 3 promises to build a portable CDI extension for security concerns, which might be a big help if/when it comes available.

Configuring the filter

To configure the filter, the following settings are required for each of the two concrete implementations, depending on the format of the token your OAuth server is using.

Creating filter

We are creating a Filter by implementing the

Filter

interface and by implementing its three methods –

  • init(FilterConfig)
  • doFilter(ServletRequest, ServletResponse, FilterChain )
  • destroy()

Within the doFilter(ServletRequest, ServletResponse, FilterChain) method, we must make a call to doFilter(request, response) method of FilterChain interface.

MyFilter1.java

Creating the deployment descriptor file

As per the Java Servlet specifications, every web application based on Servlet must have a Deployment Descriptor file(an

XML

file) named

web.xml

.
So, let’s create one and this time, associate our two filter classes with our Servlet class –

web.xml

Directory structure of servlet files

The diagram above depicts how to arrange the Servlet files in a specific directory structure, as per Java Servlet Specification-

Filter overview

The filter is build to perform two tasks.

  1. Authenticate the caller by validating the incoming access token
  2. Authorize the operation by validating the scopes in the access token against the configured scopes

Filter review

Servlet Filters were introduced in version 2.3 of the Java Servlet specification. If you are completely new to Filters, I suggest reading about them here. I will attempt a high-level overview now. Read about the Intercepting Filter design pattern to better understand the problem Filters try to address.

Похожее:  Токен Авторизации / Хабр

Installing the library

The oauth-filter library is available on Maven Central since version 3.0.0. so you can easily include in your projects.

For example, if you use Maven, add to your pom.xml:

or with Gradle, inlcude in build.gradle:

Methods of filter interface

In order to create a filter class we must implement the three methods of

javax.servlet.Filter

interface.

MethodsDescription
voiddoInit(FilterConfig config)This method initializes the Filter.
voiddoFilter(ServletRequest request, ServletResponse, response, FilterChain chain)This method is called by the web container when a client requests for a web resource
which could be a Servlet or a JSP page .
voiddestroy()This method destroys the Filter instance.

More information

For more information, please contact Curity.

Copyright (C) 2022-2022 Curity AB. All rights reserved

Please share this article –

Advertisement

Scope-bases authorization

The abstract class OAuthFilter implements a simple authorize method, that validates the incoming scopes against the configured ones. It is simple to override this method in the implementing classes instead to perform more advanced authorization.

Setting the classpath


Much of the support for developing the web applications based on the Java Servlet technology does not come with the core Java.
Hence, in order to compile the Servlet programs, we have to set the

classpath

to a jar file named

servlet-api.jar

This jar file provides all the classes that are required for the Servlet programming and it comes within the lib Folder of
Tomcat installation folder.

For example, in our case we have installed Tomcat Web Server within the C: Drive, hence the path to our lib folder containing the servlet-api.jar is – C:apache-tomcat-9.0.2lib

There are two ways to set the classpath –

Using json web tokens (jwt)

OAuthJwtFilter implements a filter that expects a Json Web Token, and that can validate the token either by using a pre-shared certificate or by calling the OAuth servers Json Web Key (JWK) endpoint. The default is to use the JWK service, as this provides a more maintainable deployment structure for microservices.

Using opaque tokens

OAuthOpaqueFilter implements a filter that expects an opaque token (i.e., a token that needs to be introspected in order to determine the contents). This requires the OAuth server to support introspection. Introspection means that the API acts as an introspecting client, and, therefore, needs client credentials in order to authenticate itself against the introspection endpoint.

Init-params for the oauthjwtfilter

Configuration Setting NameDescription
oauthHostHostname of the OAuth server.
oauthPortPort of the OAuth server.
jsonWebKeysPathPath to the JWKS endpoint on the OAuth server.
scopeA space separated list of scopes required to access the API.
minKidReloadTimeInSecondsMinimum time to reload the webKeys cache used by the Filter.

Conclusion

In this article, I have demonstrated one way to implement authorization for a J2EE application utilizing a Servlet Filter. This is a simple and unobtrusive way to satisfy authorization requirements. It can be plugged into a new or existing application running on any Servlet container.

Init-params for the oauthopaquefilter

Configuration Setting NameDescription
oauthHostHostname of the OAuth server.
oauthPortPort of the OAuth server.
introspectionPathPath to the introspection endpoint on the OAuth server.
scopeA space separated list of scopes required to access the API.
clientIdYour application’s client id to use for introspection.
clientSecretYour application’s client secret.
Похожее:  Как просто получить токен для работы с API Вконтакте

Authentication filter in java – java infinite

Authentication Filter in Java:
In this article, Let us see an example of using authentication filter.

What is a Filter?
As the name suggests, Filter performs filtering tasks. Filter is an object that perform filtering tasks on requesting for a resource or response from resource or both.

Types of Filters:
There are various types of filters,

  • Authentication Filters
  • Image Conversion Filters
  • Date Compression Filters
  • Encryption Filters
  • Logging and Auditing Filters
  • Mime type chain Filters
  • Filters triggering resource access events
  • Tokenizing Filters
  • XSL/T filters

Methods in Filter:
public void init(FilterConfig filterconfig) –
Initializes the filter, this is called by web container only once to place the filter into service
public void destroy() – Used for destroying the filter that is been placed into the service
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) – Called each time request or response  pair is passed through the chain.

Filters are mapped to the Servlet with Servlet name or with URL in deployment descriptor – web.xml

Now let us see an example,
We are going to set a filter that checks whether the user entered the correct code. If user enter the correct code he will be shown success message or to the error page

Structure:
structure

Sample.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Filter Code</title>
    </head>
    <body>
        <form action="Servlet" method="post">
            Enter the Secret Code: <input type="text" name="code">
            <input type="submit" value="submit" name="submit">
        </form>
    </body>
</html>

sorry.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>sorry! Invalid Code</h1>
    </body>
</html>

FilterChecks.java (Filter) // doFilter method

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Vikram
 */
public class FilterChecks implements Filter {
    
    private static final boolean debug = true;
   private ArrayList<String> urlList;

    // The filter configuration object we are associated with.  If
    // this value is null, this filter instance is not currently
    // configured. 
    private FilterConfig filterConfig = null;
    
    public FilterChecks() {
    }    
    
    private void doBeforeProcessing(ServletRequest request, ServletResponse response)
            throws IOException, ServletException {
        if (debug) {
            log("FilterChecks:DoBeforeProcessing");
        }

	// Write code here to process the request and/or response before
        // the rest of the filter chain is invoked.
	// For example, a logging filter might log items on the request object,
        // such as the parameters.
	/*
         for (Enumeration en = request.getParameterNames(); en.hasMoreElements(); ) {
         String name = (String)en.nextElement();
         String values[] = request.getParameterValues(name);
         int n = values.length;
         StringBuffer buf = new StringBuffer();
         buf.append(name);
         buf.append("=");
         for(int i=0; i < n; i  ) {
         buf.append(values[i]);
         if (i < n-1)
         buf.append(",");
         }
         log(buf.toString());
         }
         */
    }    
    
    private void doAfterProcessing(ServletRequest request, ServletResponse response)
            throws IOException, ServletException {
        if (debug) {
            log("FilterChecks:DoAfterProcessing");
        }

	// Write code here to process the request and/or response after
        // the rest of the filter chain is invoked.
	// For example, a logging filter might log the attributes on the
        // request object after the request has been processed. 
	/*
         for (Enumeration en = request.getAttributeNames(); en.hasMoreElements(); ) {
         String name = (String)en.nextElement();
         Object value = request.getAttribute(name);
         log("attribute: "   name   "="   value.toString());

         }
         */
	// For example, a filter might append something to the response.
	/*
         PrintWriter respOut = new PrintWriter(response.getWriter());
         respOut.println("<P><B>This has been appended by an intrusive filter.</B>");
         */
    }

    /**
     *
     * @param request The servlet request we are processing
     * @param response The servlet response we are creating
     * @param chain The filter chain we are processing
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {
        
       String code = request.getParameter("code");
        
        if(code!= null && code.equals("javainfinite"))
        {
            chain.doFilter(request, response);
        }
        else
        {
            RequestDispatcher rd = request.getRequestDispatcher("/sorry.jsp");
            rd.forward(request, response);
        }
    }

    /**
     * Return the filter configuration object for this filter.
     */
    public FilterConfig getFilterConfig() {
        return (this.filterConfig);
    }

    /**
     * Set the filter configuration object for this filter.
     *
     * @param filterConfig The filter configuration object
     */
    public void setFilterConfig(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }

    /**
     * Destroy method for this filter
     */
    public void destroy() {        
    }

    /**
     * Init method for this filter
     */
    public void init(FilterConfig filterConfig) {        
        this.filterConfig = filterConfig;
        if (filterConfig != null) {
            if (debug) {                
                log("FilterChecks:Initializing filter");
            }
        }
        
    }

    /**
     * Return a String representation of this object.
     */
    @Override
    public String toString() {
        if (filterConfig == null) {
            return ("FilterChecks()");
        }
        StringBuffer sb = new StringBuffer("FilterChecks(");
        sb.append(filterConfig);
        sb.append(")");
        return (sb.toString());
    }
    
    private void sendProcessingError(Throwable t, ServletResponse response) {
        String stackTrace = getStackTrace(t);        
        
        if (stackTrace != null && !stackTrace.equals("")) {
            try {
                response.setContentType("text/html");
                PrintStream ps = new PrintStream(response.getOutputStream());
                PrintWriter pw = new PrintWriter(ps);                
                pw.print("<html>n<head>n<title>Error</title>n</head>n<body>n"); //NOI18N

                // PENDING! Localize this for next official release
                pw.print("<h1>The resource did not process correctly</h1>n<pre>n");                
                pw.print(stackTrace);                
                pw.print("</pre></body>n</html>"); //NOI18N
                pw.close();
                ps.close();
                response.getOutputStream().close();
            } catch (Exception ex) {
            }
        } else {
            try {
                PrintStream ps = new PrintStream(response.getOutputStream());
                t.printStackTrace(ps);
                ps.close();
                response.getOutputStream().close();
            } catch (Exception ex) {
            }
        }
    }
    
    public static String getStackTrace(Throwable t) {
        String stackTrace = null;
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            t.printStackTrace(pw);
            pw.close();
            sw.close();
            stackTrace = sw.getBuffer().toString();
        } catch (Exception ex) {
        }
        return stackTrace;
    }
    
    public void log(String msg) {
        filterConfig.getServletContext().log(msg);        
    }
    
}

Servlet.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Vikram
 */
public class Servlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
       
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the   sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        
     
        
        response.setContentType("text/html");  
        PrintWriter out = response.getWriter();  
          
        out.print("Filter Success");  
        out.close(); 
        
    }

   
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

Output
op1

Похожее:  Модальное окно Bootstrap: разработка формы входа, регистрации и восстановления пароля | Bootstrap

op2
If wrong code entered,

op3
op4

1 Звезда2 Звезды3 Звезды4 Звезды5 Звезд (1 оценок, среднее: 5,00 из 5)
Загрузка...

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector