2013-12-20 44 views
10
  1. 創建登錄頁面JavaConfiguration對Spring 4.0 +安全3.2 + j_spring_security_check

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
    <!DOCTYPE html> 
    <html> 
        <head> 
         <meta charset="ISO-8859-1"> 
         <title>Test</title> 
         <script src="static/js/jquery-1.10.2.min.js"></script> 
         <script src="static/js/app-controller.js"></script> 
        </head> 
        <body> 
         <div>Login</div> 
         <form name="f" action="<c:url value="/j_spring_security_check"/>" method="POST"> 
          <label for="password">Username</label>&nbsp;<input type="text" id="j_username" name="j_username"><br/> 
          <label for="password">Password</label>&nbsp;<input type="password" id="j_password" name="j_password"><br/> 
          <input type="submit" value="Validate">&nbsp;<input name="reset" type="reset"> 
          <input type="hidden" id="${_csrf.parameterName}" name="${_csrf.parameterName}" value="${_csrf.token}"/> 
         </form> 
         <hr/> 
         <c:if test="${param.error != null}"> 
          <div> 
           Failed to login. 
           <c:if test="${SPRING_SECURITY_LAST_EXCEPTION != null}"> 
            Reason: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" /> 
           </c:if> 
          </div> 
         </c:if> 
         <hr/> 
         <input type="button" value="Echo" id="echo" name="echo" onclick="AppController.echo();"> 
         <div id="echoContainer"></div> 
    
        </body> 
    </html> 
    
  2. 聲明一個WebSecurityConfigurer 這裏是我失蹤爲j_username和爲j_password

    @Configuration 
    @EnableWebSecurity 
    @ComponentScan(basePackages = {"com.sample.init.security"}) 
    public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter { 
    
        @Inject 
        private AuthenticationProvider authenticationProvider; 
    
        @Inject 
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
         auth.authenticationProvider(authenticationProvider); 
        } 
    
        @Override 
        protected void configure(HttpSecurity http) throws Exception { 
         http 
          .authorizeRequests() 
           .antMatchers(
             "/resources/**", 
             "/static/**", 
             "/j_spring_security_check", 
             "/AppController/echo.html").permitAll() 
           .anyRequest().authenticated() 
           .and() 
          .formLogin() 
           .usernameParameter("j_username") /* BY DEFAULT IS username!!! */ 
           .passwordParameter("j_password") /* BY DEFAULT IS password!!! */ 
           .loginProcessingUrl("/j_spring_security_check") 
           .loginPage("/") 
           .defaultSuccessUrl("/page") 
           .permitAll() 
           .and() 
          .logout() 
           .permitAll(); 
        } 
    
        @Override 
        public void configure(WebSecurity web) throws Exception { 
         web 
          .ignoring() 
           .antMatchers("/static/**"); 
        } 
    
    } 
    
  3. 申報WebMvcConfigurer

    @EnableWebMvc 
    @Configuration 
    @ComponentScan(basePackages = { 
         "com.app.controller",   
         "com.app.service", 
         "com.app.dao" 
    }) 
    public class WebMvcConfigurer extends WebMvcConfigurerAdapter { 
    
        @Bean 
        public ViewResolver viewResolver() { 
         InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); 
         viewResolver.setPrefix("/WEB-INF/view/"); 
         viewResolver.setSuffix(".jsp"); 
         return viewResolver; 
        } 
    
        @Override 
        public void addViewControllers(ViewControllerRegistry registry) { 
         registry.addViewController("/page").setViewName("page"); 
        } 
    
        @Override 
        public void addResourceHandlers(ResourceHandlerRegistry registry) { 
         registry.addResourceHandler("static/**").addResourceLocations("static/"); 
        } 
    
    } 
    
  4. 聲明一個安全初始化程序

    public class SecurityWebAppInitializer 
        extends AbstractSecurityWebApplicationInitializer { } 
    
  5. 聲明一個應用Initialzer

    public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer { 
    
        @Override 
        protected Class<?>[] getRootConfigClasses() {  
         return new Class<?>[]{WebSecurityConfigurer.class}; 
        } 
    
        @Override 
        protected Class<?>[] getServletConfigClasses() { 
         return new Class<?>[]{WebMvcConfigurer.class, DataSourceConfigurer.class}; 
        } 
    
        @Override 
        protected String[] getServletMappings() { 
         return new String[]{"/"}; 
        } 
    
    } 
    
  6. 實現自定義的身份驗證提供

    @Component 
    @ComponentScan(basePackages = {"com.app.service"}) 
    public class CustomAuthenticationProvider implements AuthenticationProvider { 
    
        private static final Logger LOG = LoggerFactory.getLogger(CustomAuthenticationProvider.class); 
    
        @Inject 
        private AppService service; 
    
        @Override 
        public Authentication authenticate(Authentication authentication) throws AuthenticationException { 
    
         //Thread.dumpStack(); 
         String username = authentication.getName(); 
         String password = authentication.getCredentials().toString(); 
    
         String message = String.format("Username: '%s' Password: '%s'", username, password); 
         UserBean userBean = service.validate(username, password);  
         LOG.debug(message); 
         if (userBean != null) { 
          List<GrantedAuthority> grantedAuths = new ArrayList<>(); 
          grantedAuths.add(new SimpleGrantedAuthority("USER")); 
          return new UsernamePasswordAuthenticationToken(userBean, authentication, grantedAuths); 
         } else { 
          String error = String.format("Invalid credentials [%s]", message); 
          throw new BadCredentialsException(error); 
         } 
        } 
    
        @Override 
        public boolean supports(Class<?> authentication) { 
         return authentication.equals(UsernamePasswordAuthenticationToken.class); 
        } 
    
    } 
    

我在跳過EchoController,AppService,AppDao和UserBean。

謝謝。

+0

@zeh:什麼是您的驗證參數看起來像方法驗證?它的屬性值是什麼? – vincentks

+0

@vincentks證書和委託人都是空的。檢查螢火蟲網絡控制檯中的兩個參數。看起來他們在某個時候丟失了。在我使用新的Spring特性(Java配置)時,也許Spring Security會搜索另一個參數對名稱(而不是j_username和j_password),我猜測。 – zeh

+0

我只是增加了一個控制器,繞過驗證的帶有回聲方法,carring用戶名和密碼,它們是空的,以及使用@RequestParam – zeh

回答

20

在3.2版本中,post參數已從j_username更改爲username,並將j_password更改爲password。登錄網址也從/ j_spring_security_check更改爲/ login。

請參閱此鏈接以解釋實施此更改的原因:http://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/reference/htmlsingle/#jc-httpsecurity。這些都是變化:

  • GET /登錄渲染/ spring_security_login的登錄頁面,而不是

  • POST /登錄認證用戶,而不是/ j_spring_security_check

  • username參數默認爲用戶名,而不是j_username

  • 密碼參數默認爲密碼而不是j_password

而這對於一個登錄表單的例子:http://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/reference/htmlsingle/#jc-form

+0

我使用3.2-RC2,併爲j_username和爲j_password仍在工作......沒有他們改變PARAM和來自RC2的網址名稱? –

+1

@ pasemes確實!我剛來這裏更新代碼。我在這裏找到了http://docs.spring.io/spring-security/site/docs/3。2.x/apidocs/org/springframework/security/config/annotation/web/builders/HttpSecurity.html但是正如你之前提到的那樣,爲你指點,謝謝。 – zeh