2015-07-30 4 views
1

Я использую конфигурацию Spring Security Java на основе Java. Но не может вызвать действие процесса, когда пользователь отправляет регистрационную форму. Вот мой конфигурационный и java-файл. , пожалуйста, дайте мне знать, где я делаю что-то неправильно. Спасибо заранее.Spring Security Пользовательский вход с использованием Java Config Based

1) Spring безопасности Java Config класса

@Configuration 
@EnableWebMvcSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 
    @Autowired 
    UserService userService; 
    @Bean 
    public AuthenticationManager authenticationManager() throws Exception{ 
     AuthenticationManager authenticationManager = new ProviderManager(
        Arrays.asList(authenticationProvider())); 
      return authenticationManager; 
     } 
    @Bean 
    public AuthenticationProvider authenticationProvider() throws  Exception { 
     DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); 
     authenticationProvider.setUserDetailsService(userService); 
     authenticationProvider.afterPropertiesSet(); 
     return authenticationProvider; 
     } 
     @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.authorizeRequests().antMatchers("/**").permitAll() 
     .antMatchers("/process/success").authenticated() 
     .and() 
     .formLogin() 
     .usernameParameter("username") 
     .passwordParameter("password") 
     .loginPage("/") 
     .failureUrl("/?auth=fail") 
     .loginProcessingUrl("/process") 
     .and().logout().logoutUrl("/logout") 
     .invalidateHttpSession(true).deleteCookies("JSESSIONID") 
     .permitAll(); 
     } 
} 

2) Jsp Войти Страница.

<form name="f" action="./process" method="post"> 
    <fieldset> 
    <legend>Please Login</legend> 
    <c:if test="${'fail' eq param.auth}"> 
    <div style="color: red"> 
    Login Failed!!!<br /> Reason : 
    ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message} 
    </div> 
    </c:if> 
    <c:if test="${'succ' eq param.out}"> 
    <div style="color: blue"> 
    <h2>You have been successfully logged out.</h2> 
    ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message} 
    </div> 
    </c:if> 
    <div class="alert alert-success">${param.logout}</div> 
    <label for="username">Username</label> <input type="text"id="username" name="username" /> <label for="password">Password</label> 
    <input type="password" id="password" name="password" /> 
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> 
    <div class="form-actions"> 
    <button type="submit" class="btn">Log in</button> 
    </div> 
    </fieldset> 
    </form> 

3) Здесь Главная Контроллер

@Controller 
public class HomeController { 
    @Autowired 
    AuthenticationManager authenticationManager; 
    @RequestMapping(value = "/", method = RequestMethod.GET) 
    public String index() { 
     System.out.println("index....."); 
     return "index"; 
    } 
    @RequestMapping(value = "/process", method = RequestMethod.POST) 
    public String process(@PathVariable("username") String userName, 
     @PathVariable("password") String password, 
     HttpServletRequest request, RedirectAttributes redirectAttr) { 
     try { 
      UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userName, password); 
      Authentication authenticate = authenticationManager.authenticate(token); 
      SecurityContextHolder.getContext().setAuthentication(authenticate); 
     } catch (AuthenticationException e) { 
      System.out.println(e.getMessage()); 
     } 
     System.out.println("login....." + request.getSession(false)); 
     return "redirect:/process/success"; 
    } 
    @RequestMapping(value = "/process/success", method = RequestMethod.GET) 
    public String success() { 
     System.out.println("success....."); 
     return "success"; 
    } 
    @RequestMapping(value = "/logout", method = RequestMethod.GET) 
    public String logout(HttpServletRequest request) { 
     System.out.println("logout....." + request.getSession(false)+ " is new " + request.getSession(false).isNew()); 
     request.getSession(false).invalidate(); 
     return "index"; 
    } 
} 

ответ

0

Проблема заключается в том, что Spring Security использует фильтры, и запрос обычно перехватываются и обрабатываются UsernamePasswordAuthenticationFilter. Поэтому он не может связаться с вашим контроллером.

Spring Security использует фильтр для обработки логина для вас, и вы даже не должны думать о том, чтобы использовать контроллер для этого. Вы должны прочитать (снова) справочное руководство и начать с учебника.

+0

Мы хотим использовать пользовательский URL-адрес для входа. http://docs.spring.io/autorepo/docs/spring-security/3.2.2.RELEASE/apidocs/org/springframework/security/config/annotation/web/builders/HttpSecurity.html#formLogin() –