JSF / Spring Security-添加其他登录字段不会调用自定义过滤器

时间:2018-09-23 13:48:41

标签: java jsf spring-security

我有一个Web应用程序,需要在其中使用以下三个字段登录:用户,密码和部门。

当我尝试运行此命令时,登录有效,但是未调用自定义过滤器,因此没有部门。

我一直在尝试添加自定义的用户名和密码过滤器,并传递一个字符串,以后可以解析。我没有任何成功,这让我发疯。

SecurityConfig扩展了WebSecurityConfigurerAdapter

static void Main(string[] args)
{
    ///*-------checking args length-----*/      
    if (args.Length>0) //It means the Application should run without UI
    {
            MergeProcess mergeProcess = null;             
            if(mergeProcess!=null)
            {
                //MessageBox.Show("Starting PPTViewFiles in Simple_Mode");
                mergeProcess.Start();
                Application.Run();
            }                       
    }
    else //It means the Application should run with UI
    {
        Application.Run(new PPTViewFileGUI());
    }               
}

}

登录视图

@Override
protected void configure(HttpSecurity http) throws Exception {

    http
        .addFilterBefore(authenticationFilter(), 
                UsernamePasswordAuthenticationFilter.class);

    // Authentication control
    http
        .authorizeRequests()
        .antMatchers("/login.xhtml").permitAll() // All everyone to see login page
        .antMatchers("/javax.faces.resource/**").permitAll() // All everyone to see resources
        .antMatchers("/resources/**").permitAll() // All everyone to see resources
        .anyRequest().authenticated(); // Ensure any request to application is authenticated

    // Login control
    http
        .formLogin()
            .loginPage("/login.xhtml")
            .usernameParameter("userInput")
            .passwordParameter("passwordInput")
            .defaultSuccessUrl("/home.xhtml", true)
            .failureUrl("/login.xhtml?error=true");

    // logout
    http
        .logout()
            .logoutUrl("/logout")
            .invalidateHttpSession(true)
            .logoutSuccessUrl("/login.xhtml");

    // not needed as JSF 2.2 is implicitly protected against CSRF
    http
        .csrf().disable();
} 

public CustomAuthenticationFilter authenticationFilter() throws Exception {
    CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
    filter.setAuthenticationManager(authenticationManagerBean());
    filter.setAuthenticationFailureHandler(failureHandler());
    return filter;
}

public SimpleUrlAuthenticationFailureHandler failureHandler() {
    return new SimpleUrlAuthenticationFailureHandler("/login?error=true");
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authProvider());
}   

@Bean
public DaoAuthenticationProvider authProvider() {
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(userDetailsService);
    authProvider.setPasswordEncoder(new EncryptionConfig());
    return authProvider;
}

UsernamePasswordAuthenticationFilter

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:p="http://primefaces.org/ui"
    xmlns:ui="http://java.sun.com/jsf/facelets">

    <h:head>
        <f:facet name="first">
            <meta http-equiv="X-UA-Compatible" content="IE=edge" />
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
            <meta name="apple-mobile-web-app-capable" content="yes" />
        </f:facet>

        <title>Login</title>

        <h:outputScript name="js/ripple.js" library="ultima-layout" />
        <h:outputScript name="js/layout.js" library="ultima-layout" />
    </h:head>

    <h:body styleClass="login-body">
        <h:form prependId="false" >
            <div class="card login-panel ui-fluid">
                <div class="ui-g">
                    <div class="ui-g-12">
                        <p:graphicImage name="images/logo.png" />
                    </div>
                    <div class="ui-g-12">
                        <h:panelGroup styleClass="md-inputfield">
                            <p:inputText id="userInput" />
                            <label>Username</label>
                        </h:panelGroup>
                    </div>
                    <div class="ui-g-12">
                        <h:panelGroup styleClass="md-inputfield">
                            <p:password id="passwordInput" />
                            <label>Password</label>
                        </h:panelGroup>
                    </div>
                    <div class="ui-g-12">
                        <h:panelGroup styleClass="md-inputfield">
                            <p:selectOneMenu id="departmentInput" value="#{loginController.selectedDepartmentId}">
                                <f:selectItem itemLabel="---" itemValue="" />
                                <f:selectItems 
                                    value="#{loginController.allDepartments}" 
                                    var="dept"
                                    itemLabel="#{dept.departmentName}"
                                    itemValue="#{dept.departmentId}" />
                            </p:selectOneMenu>
                        </h:panelGroup>
                    </div>
                    <div class="ui-g-12">
                        <p:commandButton value="Sign In" icon="ui-icon-person" ajax="false" />
                    </div>
                </div>
            </div>

            <div class="login-footer"></div>
        </h:form>

        <h:outputStylesheet name="css/ripple.css" library="ultima-layout" />
        <h:outputStylesheet name="css/layout-blue-grey.css" library="ultima-layout" />
        <h:outputStylesheet name="css/custom_login.css" />
    </h:body>
</html>

修改

我发现的第一个问题-登录名上的form操作需要指向/ login操作。我做到了,现在进入过滤器。也就是说,用户名仍然为空,密码仍然为空。

编辑2

已更改密码输入为密码,用户名输入为用户名。我在SecurityConfig中删除了usernameParameter和passwordParameter设置。我修复了令牌,现在可以在自定义UserDetails中获取它。

我的BCrypt安全性检出并返回“ true”。

我仍然获得以下堆栈跟踪:

public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    public static final String SPRING_SECURITY_DEPARTMENT_KEY = "department";

  @Override
  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

      CustomAuthenticationToken authRequest = getAuthRequest(request);
      setDetails(request, authRequest);

      return this.getAuthenticationManager().authenticate(authRequest);
  }

  private CustomAuthenticationToken getAuthRequest(HttpServletRequest request) {

      String username = obtainUsername(request);
      String password = obtainPassword(request);
      String department = obtainDepartment(request);

      if (username == null) {
          username = "";
      }
      if (password == null) {
          password = "";
      }
      if (department == null) {
          department = "";
      }

      //(username)(separator)(department)
      String usernameDomain = String.format("%s%s%s", 
              username.trim(), 
              String.valueOf(Character.LINE_SEPARATOR), 
              department);

      return new CustomAuthenticationToken(usernameDomain, password, department);
  }

  private String obtainDepartment(HttpServletRequest request) {
      return request.getParameter(SPRING_SECURITY_DEPARTMENT_KEY);
  }
}

1 个答案:

答案 0 :(得分:1)

对于您的CustomAuthenticationFilter,您没有设置与Spring的默认usernamepassword不同的表单参数名称。