2014-03-30 43 views
2

我剛開始使用Spring Security進行驗證的項目,該驗證使用Java配置代替XML。這是我的課SecurityConfig.java:我與Spring Security的應用程序不會超出登錄頁面

@Configuration 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    public void configure(AuthenticationManagerBuilder auth) throws Exception { 
     auth 
      .inMemoryAuthentication() 
       .withUser("kleber") 
       .password("123") 
       .roles("USER"); 
    } 

    protected void configure(HttpSecurity http) throws Exception { 
     http 
      .csrf() 
       .disable() 
      .authorizeRequests() 
       .antMatchers("/css/**", "/fonts/**", "/image/**", "/js/**").permitAll() 
       .anyRequest().authenticated() 
       .and() 
      .formLogin() 
       .loginPage("/spring/index").permitAll() 
          .loginProcessingUrl("/spring/login").permitAll() 
       .usernameParameter("login") 
       .passwordParameter("senha") 
       .defaultSuccessUrl("/spring/home") 
       .failureUrl("/spring/erro-login") 
       .and() 
      .logout() 
       .logoutUrl("/spring/logout") 
       .logoutSuccessUrl("/spring/index").permitAll(); 
    } 

} 

有了這個配置,我可以到達登錄頁面,但之後,我告訴我的credencials(用戶名和密碼),系統返回到這個相同的登錄頁面,儘管用戶名和密碼知情是正確的。

所有這些網址中的類SecurityConfig通知被映射在此控制器:

@Controller 
@RequestMapping(value="spring") 
public class SpringController { 

    @RequestMapping(value="index") 
    public ModelAndView index() { 
     ModelAndView mav = new ModelAndView(); 
     mav.setViewName("index"); 
     return mav; 
    } 

    @RequestMapping(value="home") 
    public ModelAndView home() { 
     ModelAndView mav = new ModelAndView(); 
     mav.setViewName("home"); 
     return mav; 
    } 

    @RequestMapping(value="doLogin", method=RequestMethod.POST) 
    public void doLogin(HttpServletRequest request, HttpServletResponse response) { 
     // 
    } 

    @RequestMapping(value="logout") 
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException { 
     request.getSession().invalidate(); 
     response.sendRedirect(request.getContextPath()); 
    } 

} 

我做錯了嗎?

- >仍與上述話題:

我需要實現這個「loginProcessingUrl」,這是在我的控制器這樣映射:

@RequestMapping(value="doLogin", method=RequestMethod.POST) 
public void doLogin(HttpServletRequest request, HttpServletResponse response) { 
    // 
} 

我已經在我的應用程序兩類其,根據我讀的文章,將這一過程需要,但我可能是錯的,也許我需要另一種方法:

SampleAuthenticationManager

public class SampleAuthenticationManager implements AuthenticationManager { 
    static final List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>(); 

    static 
    { 
    AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER")); 
    } 

    public Authentication authenticate(Authentication auth) throws AuthenticationException 
    { 
    if (auth.getName().equals(auth.getCredentials())) 
    { 
     return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(), AUTHORITIES); 
    } 
    throw new BadCredentialsException("Bad Credentials"); 
    } 

} 

DefaultAuthenticationProcessingFilter

public class DefaultAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter { 

    private static final String INTERCEPTOR_PROCESS_URL = "/spring/doLogin"; 

    private static AuthenticationManager am = new SampleAuthenticationManager(); 

    protected DefaultAuthenticationProcessingFilter() { 
     super(INTERCEPTOR_PROCESS_URL); 
     // TODO Auto-generated constructor stub 
    } 

    @Override 
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { 
     // TODO Auto-generated method stub 

     String login = request.getParameter("login"); 
     String senha = request.getParameter("senha"); 

     Authentication input = new UsernamePasswordAuthenticationToken(login, senha); 
     Authentication output = null; 
     try { 
      output = am.authenticate(input); 
      SecurityContextHolder.getContext().setAuthentication(output); 
      getSuccessHandler().onAuthenticationSuccess(request, response, output); 
     } catch (AuthenticationException failed) { 
      getFailureHandler().onAuthenticationFailure(request, response, failed); 
     } 

     return output; 
    } 

} 

在這種情況下,我應該如何實現從我的控制器方法doLogin?考慮到在這一刻我正在使用inMemory身份驗證,以便以後擴展我的項目以使用數據庫。

+0

我沒有看到任何地方你註冊你的AuthenticationManager或AuthenticationProvider實現。使用authenticationmanagerbuilder的行正在註冊一些內置的管理器和提供者。此外,auth.getName()。equals(auth.getCredentials())這一行將暗示用戶名和密碼(或任何憑據)必須與您的經理驗證相同。 –

回答

2

好吧,我設法解決了我的問題;在我看來,我在SecurityConfig和Url中通知的Url弄得一團糟。我需要記住未來:在課堂上,始終使用//。在視圖中,始終使用。

在我的情況,意見是這樣寫的:

的index.jsp - >登錄頁

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Insert title here</title> 
</head> 
<body> 

<c:url value="/spring/login" var="loginUrl"/> 
<form method="post" action="${loginUrl}"> 
    usu&aacute;rio: <input type="text" name="login" size=20> <br/> 
    senha: <input type="password" name="senha" size=20> <br/> 
    <input type="submit" value="entrar"> <br/> 
</form> 

</body> 
</html> 

回到Home.jsp - >在 「命運」 頁面(儀表板):僅用於此項目狀態下的測試目的

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Insert title here</title> 
</head> 
<body> 

<h2> 
    <c:out value="${pageContext.request.remoteUser}"/> 
    <a href="<c:out value="${pageContext.request.contextPath}/spring/logout"/>">Logout</a> 
</h2> 

</body> 
</html> 

最終代碼fo r該類SecurityConfig.java

@Configuration 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    public void configure(AuthenticationManagerBuilder auth) throws Exception { 
     auth 
      .inMemoryAuthentication() 
       .withUser("kleber") 
       .password("123") 
       .roles("USER"); 
    } 

    protected void configure(HttpSecurity http) throws Exception { 
     http 
      .csrf() 
       .disable() 
      .authorizeRequests() 
       .antMatchers("/css/**", "/fonts/**", "/image/**", "/js/**").permitAll() 
       .anyRequest().authenticated() 
       .and() 
      .formLogin() 
       .loginPage("/spring/index").permitAll() 
       .loginProcessingUrl("/spring/login").permitAll() 
       .usernameParameter("login") 
       .passwordParameter("senha") 
       .successHandler(new CustomAuthenticationSuccessHandler()) 
       .failureHandler(new CustomAuthenticationFailureHandler()) 
       .and() 
      .logout() 
       .logoutUrl("/spring/logout") 
       .logoutSuccessUrl("/spring/index").permitAll(); 
    } 

} 
相關問題