javax.servlet.ServletException: вход не выполнен - PullRequest
0 голосов
/ 26 октября 2018

да, я проверил каждый ресурс в StackOverflow, чтобы решить мою проблему, но не повезло теперь давайте перейдем к моему вопросу

Я слежу за одним проектом с открытым исходным кодом, но после успешной установки проекта я не могу войти в свое приложение используется аутентификация на основе форм, и я думаю, что механизм безопасности JDBC также используется

Warning:   WEB9102: Web Login Failed: com.sun.enterprise.security.auth.login.common.LoginException: Login failed: Security Exception
Severe:   javax.servlet.ServletException: Login failed
	at org.apache.catalina.authenticator.AuthenticatorBase.doLogin(AuthenticatorBase.java:959)
	at org.apache.catalina.authenticator.AuthenticatorBase.login(AuthenticatorBase.java:939)
	at org.apache.catalina.connector.Request.login(Request.java:2245)
	at org.apache.catalina.connector.Request.login(Request.java:2224)
	at org.apache.catalina.connector.RequestFacade.login(RequestFacade.java:1113)
	at edu.iit.sat.itmd4515.rindiragangaram.web.LoginController.doLogin(LoginController.java:88)
	at edu.iit.sat.itmd4515.rindiragangaram.web.LoginController$Proxy$_$$_WeldClientProxy.doLogin(Unknown Source)

Я получаю эту ошибку при входе в систему как зарегистрированный пользователь

теперь я приложил необходимые файлы для оценки проблемы

также, я не подтвердил, что этот проект потребует настройки области JDBC Я создал JDBC-область в Glassfish, но проблема снова не решена. Я не подтвержден, что в этой области также может быть ошибка Мне нужен совет по проблеме

Login.xhtml

<ui:define name="content">

        <h:panelGroup layout="block" class="container">
            <h1>User Authentication</h1>

            <h:form>
                <h:panelGroup styleClass="#{j_username.valid ? 'form-group' : 'form-group has-error'}" layout="block" >
                    <h:outputLabel class="control-label" for="j_username" value="Username" />
                    <h:inputText binding="#{j_username}" class="form-control" id="j_username" value="#{loginController.userName}" />
                    <h:message for="j_username" style=" color: red" />
                </h:panelGroup>
                <h:panelGroup styleClass="#{j_password.valid ? 'form-group' : 'form-group has-error'}" layout="block" >
                    <h:outputLabel class="control-label" for="j_password" value="Password" />
                    <h:inputSecret binding="#{j_password}" class="form-control" id="j_password" value="#{loginController.password}" />
                    <h:message for="j_password" style=" color: red" />
                </h:panelGroup>
                <h:commandButton class="btn btn-success" value="Login" action="#{loginController.doLogin()}" />
            </h:form>
        </h:panelGroup>
        

Контроллер входа

/*
 * 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.
 */
package edu.iit.sat.itmd4515.rindiragangaram.web;

import edu.iit.sat.itmd4515.rindiragangaram.ejb.CustomerService;
import edu.iit.sat.itmd4515.rindiragangaram.ejb.ManagerService;
import edu.iit.sat.itmd4515.rindiragangaram.ejb.UserService;
import edu.iit.sat.itmd4515.rindiragangaram.model.Customer;
import edu.iit.sat.itmd4515.rindiragangaram.model.Manager;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.ServletException;
import javax.validation.constraints.*;

/**
 *
 * @author Ravi Kumar Hazare
 */
@Named
@RequestScoped
public class LoginController extends BaseController {

    @EJB
    private ManagerService managerService;

    @EJB
    private CustomerService customerService;

    private static final Logger LOG = Logger.getLogger(LoginController.class.getName());
    @NotNull(message = "Username should not be empty")
    private String userName;
    @NotNull(message = "Password should not be empty")
    private String password;

    @Inject
    CustomerPortalController customerPortalController;

    /**
     * Default Constructor
     */
    public LoginController() {
    }

    //Utility methods 
    //vvvvvvvvvvvvvvvvvvvvv
    public String getRemoteUser() {

        return context.getExternalContext().getRemoteUser();
    }

    public boolean isCustomer() {

        return context.getExternalContext().isUserInRole("CUST_ROLE");
    }

    public boolean isManager() {

        return context.getExternalContext().isUserInRole("MANG_ROLE");
    }

    public boolean isManagerAndCustomer() {
        return context.getExternalContext().isUserInRole("MANG_ROLE") && context.getExternalContext().isUserInRole("CUST_ROLE");
    }

    public boolean isAdmin() {

        return context.getExternalContext().isUserInRole("ADMIN_ROLE");
    }

    //^^^^^^^^^^^^^^^^^^^^
    // Action methods 
    // vvvvvvvvvvvvvvvvvvvvv
    // method call for the initial login
    public String doLogin() {

        Customer c = new Customer();
        Manager m = new Manager();

        try {
            request.login(userName, password);

            if (isCustomer()) {
                c = customerService.findByUsernameOnly(userName);

                LOG.info(c.toString());
                if (c.isDisabled()) {

                    request.logout();
                    context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                            "Your account is disabled, Please contact the administrator.",
                            "Your account is disabled, Please contact the administrator."));
                    // Redirect to the login page again. 
                    return "/login.xhtml";
                }
            } else if(isManager()){
                m = managerService.findByUsername(userName);
                
                LOG.info(m.toString());
                if(m.isDisabled()){
                    
                    request.logout();
                    context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                            "Your account is disabled, Please contact the administrator.",
                            "Your account is disabled, Please contact the administrator."));
                    // Redirect to the login page again. 
                    return "/login.xhtml";
                    
                }
                
            }

        } catch (ServletException ex) {
            // Log the exception if login fails
            LOG.log(Level.SEVERE, null, ex);
            // Provide a readable error to the end users
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Login Failed ! Please verify your username and/or password.",
                    "Please refer the console for the full log of the error/exception"));
            // Redirect to the login page again. 
            return "/login.xhtml";
        }
        // Render the below page if login is successful
        return "/welcome.xhtml?faces-redirect=true";
    }

    // method call for the logout
    public String doLogout() {

        if (isCustomer()) {
            customerPortalController.emptyCart();
        }
        try {
            request.logout();
        } catch (ServletException ex) {
            // Logging the exception if logout fails.
            LOG.log(Level.SEVERE, null, ex);
            // Pass message to end users 
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Logout was not successful !",
                    "Oops !! Something went wrong, please log back in and logout."));
            return "/login.xhtml";
        }
        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
                "You have successfully logged out !!",
                "Logout successful, close the browser or login back.."));
        return "/login.xhtml";
    }
    //^^^^^^^^^^^^^^^^^^^^^

    /**
     * Get the value of userName
     *
     * @return the value of userName
     */
    public String getUserName() {
        return userName;
    }

    /**
     * Set the value of userName
     *
     * @param userName new value of userName
     */
    public void setUserName(String userName) {
        this.userName = userName;
    }

    /**
     *
     * @return
     */
    public String getPassword() {
        return password;
    }

    /**
     *
     * @param password
     */
    public void setPassword(String password) {
        this.password = password;
    }

}

Сервис пользователя

/*
 * 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.
 */
package edu.iit.sat.itmd4515.rindiragangaram.ejb;

import edu.iit.sat.itmd4515.rindiragangaram.model.security.User;
import java.util.List;
import javax.ejb.Stateless;

/**
 *
 * @author Ravi Kumar Hazare
 */
@Stateless
public class UserService extends BaseService<User> {

    public UserService() {
        super(User.class);
    }

    @Override
    public List<User> findAll() {
        return getEntityManager().createNamedQuery("User.findAll", User.class).getResultList();
    }

    public User findByUsername(String userName, boolean disabled) {
        return getEntityManager().createNamedQuery("User.findByUsername", User.class)
                .setParameter("username", userName)
                .setParameter("disabled", disabled)
                .getSingleResult();
    }

    public User findByUsernameWithoutDisableField(String userName) {
        return getEntityManager().createNamedQuery("User.findByUsernameWithoutDisableField", User.class)
                .setParameter("username", userName)
                .getSingleResult();
    }
}

Модель безопасности User.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.
 */
package edu.iit.sat.itmd4515.rindiragangaram.model.security;

import com.google.common.hash.Hashing;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;

/**
 *
 * @author Ravi Kumar Hazare
 */
@Entity
@Table(name = "security_user")
@NamedQueries({
    @NamedQuery(name = "User.findAll", query = "select u from User u")
    ,
    @NamedQuery(name = "User.findByUsername", query = "select u from User u where u.userName = :username AND u.disabled =:disabled")
    ,
    @NamedQuery(name = "User.findByUsernameWithoutDisableField", query = "select u from User u where u.userName = :username")

})
public class User {

    @Id
    private String userName;
    private String password;
    private boolean disabled;

    @ManyToMany
    @JoinTable(name = "sec_user_groups", joinColumns = @JoinColumn(name = "USERNAME"),
            inverseJoinColumns = @JoinColumn(name = "GROUPNAME"))
    private List<Group> groups = new ArrayList<>();

    // Default constructor
    public User() {
    }

    // Constructor with two arguments
    public User(String userName, String password) {
        this.userName = userName;
        this.password = password;
    }

    // Constructor with three arguments
    public User(String userName, String password, boolean enabled) {
        this.userName = userName;
        this.password = password;
        this.disabled = enabled;
    }

    public void addGroup(Group g) {
        if (!this.groups.contains(g)) {
            this.groups.add(g);
        }
        if (!g.getUsers().contains(this)) {
            g.getUsers().add(this);
        }
    }

    /* This method will hash the clear text string stored in the "password" instant variable and reset the variable with a hashed password using
    *  Google guava library, refer : http://www.baeldung.com/sha-256-hashing-java
     */
    @PrePersist
    @PreUpdate
    private void hashingClearTextPassword() {
        String sha256hex = Hashing.sha256()
                .hashString(this.password, StandardCharsets.UTF_8)
                .toString();

        this.password = sha256hex;
    }

    /**
     * Get the value of userName
     *
     * @return the value of userName
     */
    public String getUserName() {
        return userName;
    }

    /**
     * Set the value of userName
     *
     * @param userName new value of userName
     */
    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isDisabled() {
        return disabled;
    }

    public void setDisabled(boolean disabled) {
        this.disabled = disabled;
    }

    public List<Group> getGroups() {
        return groups;
    }

    public void setGroups(List<Group> groups) {
        this.groups = groups;
    }

    @Override
    public String toString() {
        return "User{" + "userName=" + userName + ", password=" + password + ", disabled=" + disabled + ", groups=" + groups + '}';
    }

}

db structure

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
        <param-value>true</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <security-constraint>
        <display-name>Customer Security Constraint</display-name>
        <web-resource-collection>
            <web-resource-name>Customer Content</web-resource-name>
            <description>Customer Content</description>
            <url-pattern>/customer/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <description>Customer only</description>
            <role-name>CUST_ROLE</role-name>
        </auth-constraint>
    </security-constraint>
    <security-constraint>
        <display-name>Manager Security Constraint</display-name>
        <web-resource-collection>
            <web-resource-name>Manager Content</web-resource-name>
            <description>Manager Content</description>
            <url-pattern>/manager/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <description>Manager only</description>
            <role-name>MANG_ROLE</role-name>
        </auth-constraint>
    </security-constraint>
    <security-constraint>
        <display-name>Common Access Constraint</display-name>
        <web-resource-collection>
            <web-resource-name>Common</web-resource-name>
            <description>Everyone can access with credentials</description>
            <url-pattern>/welcome.xhtml</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <description>Common access</description>
            <role-name>CUST_ROLE</role-name>
            <role-name>MANG_ROLE</role-name>
            <role-name>ADMIN_ROLE</role-name>
        </auth-constraint>
    </security-constraint>
    <security-constraint>
        <display-name>Admin Security Constraint</display-name>
        <web-resource-collection>
            <web-resource-name>Manager Content</web-resource-name>
            <description>Manager Content</description>
            <url-pattern>/admin/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <description>Admin only</description>
            <role-name>ADMIN_ROLE</role-name>
        </auth-constraint>
    </security-constraint>
    <login-config>
        <auth-method>FORM</auth-method>
        <realm-name>itmd4515Realm</realm-name>
        <form-login-config>
            <form-login-page>/login.xhtml</form-login-page>
            <form-error-page>/error.xhtml</form-error-page>
        </form-login-config>
    </login-config>
    <security-role>
        <description>This is a customer role.</description>
        <role-name>CUST_ROLE</role-name>
    </security-role>
    <security-role>
        <description>This is a manager role.</description>
        <role-name>MANG_ROLE</role-name>
    </security-role>
    <welcome-file-list>
        <welcome-file>login.xhtml</welcome-file>
    </welcome-file-list>
    <security-role>
        <description>Administrator role</description>
        <role-name>ADMIN_ROLE</role-name>
    </security-role>
</web-app>

Glassfish-web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app error-url="">
  <security-role-mapping>
    <role-name>CUST_ROLE</role-name>
    <group-name>CUSTOMERS</group-name>
  </security-role-mapping>
  <security-role-mapping>
    <role-name>MANG_ROLE</role-name>
    <group-name>MANAGERS</group-name>
  </security-role-mapping>
  <security-role-mapping>
    <role-name>ADMIN_ROLE</role-name>
    <group-name>ADMINISTRATORS</group-name>
  </security-role-mapping>
  <class-loader delegate="true"/>
  <jsp-config>
    <property name="keepgenerated" value="true">
      <description>Keep a copy of the generated servlet class' java code.</description>
    </property>
  </jsp-config>
</glassfish-web-app>
...