与用户和管理员的登录Java会话过滤器 [英] Java session filters with users and admin login

查看:287
本文介绍了与用户和管理员的登录Java会话过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的web应用程序,我有2个主要部分。

On my web application, i have 2 main sections


  1. 用户

  2. 管理

我使用的Java会话过滤器来检查用户会话,并允许访问网站的特定部分。因此,用户只能访问用户页面部分,管理员可以访问管理部分。

I am using java session filter to check for user session and allow access to specific part of the website. Hence user have access to only the user pages section and administrator have access to admin section.

对于用户会话过滤器已经实现,它工作正常。它会检查用户(来自数据库的用户名和密码 - MySQL的),并允许访问在限制子文件夹,在那里我已经XHTML页面

The session filter for Users is already implemented and it works fine. it checks for user(username and password from database - mysql) and gives access to the restricted subfolder, where I've xhtml pages.

如果我想过滤器根据他们的用户级别来检查管理部分验证(管理员用户名和密码存储在数据库),并允许他们访问。

if i wanted filters to check for admin section authentication(admin username and password are stored in db) and allow them access based upon their user level.

我需要创造1多个过滤 - 管理

do i need to create 1 more filter - admin?

目前,这里是我实施用户:

currently here is my implementation for User:

package com.shadibandhan.ControllerLayer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Cookie;

/**
 *
 * @author MUDASSIR
 */
public class SessionFilter implements Filter {

    private ArrayList<String> urlList;
    private String toGoTo = null;
    private boolean userCookieExists = false;

    @Override
    public void init(FilterConfig config) throws ServletException {

        System.out.println("****************************************");
        System.out.println("***Session Filter Servlet initialized***");
        System.out.println("****************************************");
        String urls = config.getInitParameter("avoid-urls");
        System.out.println("The urls to avoid are = " + urls);
        StringTokenizer token = new StringTokenizer(urls, ",");

        urlList = new ArrayList<String>();

        while (token.hasMoreTokens()) {
            urlList.add(token.nextToken());

        }
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {

        System.out.println("This is the doFilter method");

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String contextRelativeURI = null;
        String contextRelativeURIForAdmin = null;



            contextRelativeURI = request.getRequestURI().substring(request.getContextPath().length());


        String contextPath = request.getContextPath();
        String remoteHost = request.getRemoteHost();
        String url = contextPath + contextRelativeURI;
        System.out.println("-----------------> Servlet path is = " + contextRelativeURI);
        System.out.println("-----------------> Context path is " + contextPath);
        System.out.println("-----------------> URL is " + url);
        System.out.println("-----------------> Remote Host is " + remoteHost);
        boolean allowedRequest = false;

        if (urlList.contains(contextRelativeURI)) {
            allowedRequest = true;
        }

        if (!allowedRequest) {
            HttpSession session = request.getSession(false);
            if (null == session) {

                System.out.println("Session is not present");
                response.sendRedirect(contextPath);
                return;

            }
            if (null != session) {

                System.out.println("Session is present");
                System.out.println("\nSession no. is = " + session.getId());

                if (session.getAttribute("logged-in") == "true") {
                    System.out.println("Session logged-in attribute is true, " + session.getAttribute("sessionUsername") + " is logged in.");



                        RequestDispatcher dispatcher = request.getRequestDispatcher(contextRelativeURI);
                        dispatcher.forward(request, response);
                        return;
                } else {
                    System.out.println("Session logged-in attribute is not true");
                    response.sendRedirect(contextPath);
                    return;
                }
            }
        }

        chain.doFilter(req, res);
    }

    @Override
    public void destroy() {
    }
}

这是我对过滤器的web.xml映射

This is my web.xml mapping for the filter

<filter>
        <filter-name>SessionFilter</filter-name>
        <filter-class>
            com.shadibandhan.ControllerLayer.SessionFilter
        </filter-class>
        <init-param>
            <param-name>avoid-urls</param-name>
            <param-value></param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>SessionFilter</filter-name>
        <url-pattern>/com.shadibandhan.Restricted/*</url-pattern>
    </filter-mapping>

现在,做我把在禁区文件夹还管理页面?或者我把它们放在另外一个单独的文件夹?
我也看到了servlet身份验证方法,这里提到其中建议在Tomcat的变化-users.xml文件,但我已经我的用户名和密码在数据库中。

Now, do i put the admin pages in the restricted folder also ? or i put them in another separate folder ? I also seen the servlet authentication method mentioned here which recommends changes in the tomcat-users.xml file but i've my usernames and passwords in the db.

请推荐建议的方法。

推荐答案

那么,保护Web应用程序的最佳方法是使用容器管理的认证让您的应用程序并不需要处理认证和授权机制。这一机制被称为 JAAS 在Java世界中。

Well, the best way of securing a web application is using the container managed authentication so your application doesn't need to handle the authentication and authorisation mechanism. That mechanism is called JAAS in the Java world.

使用容器管理的认证通常需要在servlet应用程序位的配置 - 除了在你的web应用程序所需的变革 - 但你会更安全。既然你说你使用Tomcat,然后我会给你最好的答案我可以说基于servlet容器上,其他人都以不同的方式进行配置。

Using the container managed authentication usually requires a bit of configuration on the servlet application - apart the changes required in your web application - but you'll be more secure. Since you said that you were using Tomcat then I will give you the best answer I can based on that servlet container, others are configured in a different way.

1。配置Tomcat域

所有的拳,忘了的tomcat-users.xml中(它是不安全的),并决定你如何去存储你的认证数据,LDAP服务器?数据库?该数据库?一旦你决定,你将需要修改 server.xml中文件在 CONF 在Tomcat中的文件夹添加一个新的< A HREF =htt​​p://tomcat.apache.org/tomcat-7.0-doc/realm-howto.html相对=nofollow>境界。类型境界创建将取决于在你的previous决定。

Fist of all, forget about the tomcat-users.xml (it's insecure) and decide how you are going to store your authentication data, an LDAP server? a database? which database?. Once you have decided you will need to modify your server.xml file under conf folder in Tomcat to add a new realm. The type of realm to create will depend in your previous decision.

和我们的状态明显:将用户添加到存储

And let's state the obvious:Add users to the storage.

2。配置Web应用程序

你现在需要配置的认证方式在你的web应用端。这样做是修改的web.xml / WEB-INF

You'll need now to configure the authentication method in your web application side. This is done modifying the web.xml file under /WEB-INF.

您可以基本身份验证或的基于表单的身份验证。我使用后者,因为它让我用定制的形式向最终用户提供preFER。

You may choose between Basic authentication or Form based authentication. I prefer using the latter as it allows me to provide with a customised form to the end users.

一些我提供这里的链接,描述由步骤的处理步骤。它们还包括关于如何限制访问您的应用程序不同类型的用户,即部分信息:

Some of the links I'm providing here describe the process step by step. They also include information regarding how to limit access to parts of your application to different kind of users, i.e.:

<security-constraint>
  <web-resource-collection>
    <web-resource-name>AdminPages</web-resource-name>
    <description> accessible by authorised users </description>
    <url-pattern>/admin/*</url-pattern>
    <http-method>GET</http-method>
  </web-resource-collection>
  <auth-constraint>
    <description>These are the roles who have access</description>
    <role-name>ADMIN</role-name>
  </auth-constraint>
</security-constraint>

3。知道用户

所有配置后您的应用程序应该能够知道在的HttpServletRequest getRemoteUser()方法手段的用户名C>。

After all that configuration your application should be able to know the username by means of the getRemoteUser() method in HttpServletRequest.

编辑:

我会建议使用同桌的管理员和用户,也将让使用角色它们之间的区别。如果你的管理​​实体需要附加字段不应该适用于普通用户然后链接两个表,只是处理管理​​之一,当 HttpServletRequest.isUserInRole(ADMIN)收益真正

I'd suggest to use same table for admins and users and just make the difference between them using roles. If your admin entity needs additional fields that shouldn't be available for regular users then link both tables and just deal with the admin one when HttpServletRequest.isUserInRole("ADMIN") returns true.

这篇关于与用户和管理员的登录Java会话过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆