0

I need create custom xhtml login form. Configure spring without xml only annotations, but authenticationManager always is null

Login form

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" xmlns:p="http://primefaces.org/ui"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example</title>
</head>
<body>

<h:form prependId="false"   >
    <h:outputLabel value="User Id: " for="j_username" />
    <h:inputText id="j_username" label="User Id" required="true"
        value="#{loginBean.userName}" />
    <h:outputLabel value="Password: " for="j_password" />
    <h:inputSecret id="j_password" value="#{loginBean.password}" />
    <h:commandButton value="Submit" action="#{loginBean.login}" />
    </h:form>
    </body>
    </html>

Config

@Configuration
@EnableWebSecurity
@EnableGlobalAuthentication
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().authorizeRequests()
            .antMatchers("/home", "/css/**", "/**/*.css*", "/").permitAll()
            .anyRequest().authenticated().and().formLogin()
            .loginPage("/login").permitAll().and().logout()
            .logoutUrl("/logout").invalidateHttpSession(true)
            .logoutSuccessUrl("/");
}
@Override
protected void configure(AuthenticationManagerBuilder auth)
        throws Exception {
    auth.inMemoryAuthentication().withUser("user").password("password")
            .roles("USER");
}

@Bean
public AuthenticationManager authenticationManager() throws Exception {
    return super.authenticationManagerBean();

}
}

Want @Autowired in LoginBean class

 import java.io.IOException;
 import java.io.Serializable;

 import javax.faces.bean.ManagedProperty;
 import javax.inject.Named;
 import javax.servlet.ServletException;

 import org.springframework.context.annotation.Scope;
 import org.springframework.security.authentication.AuthenticationManager;
 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
 import org.springframework.security.core.Authentication;
 import org.springframework.security.core.AuthenticationException;
 import org.springframework.security.core.context.SecurityContextHolder;
 import org.springframework.stereotype.Component;
@Scope("request")
@Component
@Named(value="loginBean")
public class LoginBean implements Serializable {


@Autowired
private AuthenticationManager authenticationManager;

private static final long serialVersionUID = 1L;
private String userName;
private String password;


public String login() {
    try {
        Authentication request = new UsernamePasswordAuthenticationToken(
                this.getUserName(), this.getPassword());
        Authentication result = authenticationManager.authenticate(request);
        SecurityContextHolder.getContext().setAuthentication(result);
    } catch (AuthenticationException e) {
        e.printStackTrace();
    }
    return "secured";
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getPassword() {
    return password;
}

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

public AuthenticationManager getAuthenticationManager() {
    return authenticationManager;
}

public void setAuthenticationManager(
        AuthenticationManager authenticationManager) {
    this.authenticationManager = authenticationManager;
}

}

I'm trying inject authenticationManager

 @ManagedProperty(value = "#{authenticationManager}")
private AuthenticationManager authenticationManager;

or create constructor

    @Autowired
 public LoginBean(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}

or add @Autowired in setter, authenticationManager always is null. How can I Inject authenticationManager ?

Ones I try @ovverride authenticationManagerBean nothing I found spring security giude but I don't want use thymeleaf

Thanks for help

Community
  • 1
  • 1
luprogrammer
  • 155
  • 1
  • 3
  • 12
  • You are mixing CDI and Spring that isn't going to work. You end up with different instances managed by different containers. To use `@ManagedProperty` you have to use a JSF managed bean instead of `@Named` use `@ManagedBean`. – M. Deinum Dec 30 '14 at 15:27
  • Yes when I'm using `@ManagedProperty` I use `@ManagedBean` and `@RequestScoped` – luprogrammer Dec 30 '14 at 17:46
  • Make sure that you have setup Spring JSF integration correctly else it won't work. Also if the bean is `null` I would expect an exception in the case of `@ManagedBean` something along the lines of that no bean could be found. – M. Deinum Dec 30 '14 at 18:54
  • how do you redirect the user to the desired page after successfull auth? – desperado06 Jan 26 '16 at 12:17

1 Answers1

-1

Do you have below entry in your web.xml ? If you are using @Configuration then it is required.

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </init-param>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
           com.yourClass
        </param-value>
    </init-param>
</servlet>
Dave
  • 35
  • 10
  • This answer doesn't make sense, especially not in a JSF based application. You only need the `ContextLoaderListener`. – M. Deinum Dec 30 '14 at 18:53
  • I'm trying add ContextLoaderListener without `applicationContext` but I always get `Cannot initialize context because there is already a root application context present` [new question](http://stackoverflow.com/questions/27765984/cannot-initialize-context-already-a-root-application-context-present) – luprogrammer Jan 04 '15 at 13:46