Warning
This page is located in archive.

REST, HTTP headers, Authentication, Project

HTTP headers, security

Short intro to authentication methods and HTTP headers HTTP headers

Authentisation methods

One can use several ways for user authentication:

Authentization using Jersey Filter

Download the example: Jersey-security-filter.zip

Application

The application uses the ServletFilter instance to filter the requests for the HelloWorldResource.

See the application descriptor web.xml first:

    <servlet>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>cz.cvut.fel.aos</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>AuthenticationFilter</filter-name>
        <filter-class>cz.cvut.fel.aos.AuthFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>AuthenticationFilter</filter-name>
        <url-pattern>/rest/*</url-pattern>
    </filter-mapping>

Except registering the Jersey ServletContainer, we also register the filter from the package cz.cvut.fel.aos.AuthFilter. The filter is chained by the application server to the chain of filters used to filter the requests comming for the specific URL patterns. The doFilter method of the filter is called for each request. You can see that in the method we check the http headers username and password. If these are correct, the user may continue to the resource. If not, the traffic is filtered:

 @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain filter) throws IOException, ServletException {
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;

            String username = httpRequest.getHeader("username");
            String password = httpRequest.getHeader("password");

            AuthService authService = new AuthService();

            boolean isAuthenticated = authService.authenticate(username,
                    password);

            if (isAuthenticated) {
                filter.doFilter(request, response);
            } else {
                if (response instanceof HttpServletResponse) {
                    HttpServletResponse httpResponse = (HttpServletResponse) response;
                    httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                }
            }
        }
    }

Project

See the page for project assignment

courses/a4m36aos/cviceni/class_15_10_2015.txt · Last modified: 2015/10/14 17:19 by kopriste