2017-03-01 26 views
0

我正在使用Spring Boot Security框架的Web应用程序。我有一个关于用户login的问题。我想定制错误消息并将其发送回页面,以便我可以显示消息。我在这里定义的是wrong user namewrong user password。我在做什么是如下:春季开机安全登录返回自定义错误消息

SecurityConfig:

@Configuration 
@EnableWebSecurity 
@EnableGlobalMethodSecurity(prePostEnabled = true) 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

    private SuccessLoginHandler successLoginHandler() { 
     return new SuccessLoginHandler(); 
    } 

    @Override 
    @Bean 
    public UserDetailsService userDetailsService() { 
     return new UserDetailService(); 
    } 

    @Override 
    protected void configure(AuthenticationManagerBuilder auth) 
      throws Exception { 
     auth.userDetailsService(userDetailsService()).passwordEncoder(new UserPasswordEncoder()); 
    } 

    @Bean 
    @Override 
    protected AuthenticationManager authenticationManager() throws Exception { 
     return super.authenticationManager(); 
    } 

    @Override 
    public void configure(WebSecurity web) throws Exception { 
     web.ignoring().antMatchers("/js/**"); 
     web.ignoring().antMatchers("/img/**"); 
     web.ignoring().antMatchers("/css/**"); 
    } 

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

     http.csrf().disable() 
       .authorizeRequests() 
       .antMatchers("/home","/login").permitAll() 
       .anyRequest().authenticated() 
       .and() 
       .formLogin() 
       .loginPage("/login") 
       .usernameParameter("username") 
       .passwordParameter("password") 
       .successHandler(successLoginHandler()) 
       .permitAll() 
       .and() 
       .logout() 
       .permitAll(); 

    } 
} 

UserDetailService

@Service 
@Scope("singleton") 
class UserDetailService implements UserDetailsService { 

    private AccountDataService accountDataService; 

    @Override 
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 
     UserEx user = accountDataService.mGetUserExByMobile(username); 
     if (user == null) { 
      throw new UsernameNotFoundException("not found"); 
     } 

     List<UserGrantedAuthority> authorities = getAuthorities(user.getMobile()); 
     return new org.springframework.security.core.userdetails.User(user.getMobile(), 
       user.getPassword(), authorities); 
    } 

    private List<UserGrantedAuthority> getAuthorities(String mobile) { 
     List<UserGrantedAuthority> authorities = new ArrayList<>(); 

     List<Permission> permissionList = accountDataService.mGetPermissionList(mobile); 

     for (Permission perm : permissionList) { 
      authorities.add(new UserGrantedAuthority(perm.getAuthority())); 
     } 
     return authorities; 
    } 

    public AccountDataService getAccountDataService() { 
     return accountDataService; 
    } 

    @Autowired 
    public void setAccountDataService(AccountDataService accountDataService) { 
     this.accountDataService = accountDataService; 
    } 
} 

UserGrantedAuthority

public class UserGrantedAuthority implements GrantedAuthority { 

    private final String authority; 

    public UserGrantedAuthority(String authority) { 
     Assert.hasText(authority, "A granted authority textual representation is required"); 
     this.authority = authority; 
    } 

    public String getAuthority() { 
     return this.authority; 
    } 

} 

UserPasswordEncoder

public class UserPasswordEncoder implements PasswordEncoder { 

    @Override 
    public String encode(CharSequence rawPassword) { 
     return null; 
    } 

    @Override 
    public boolean matches(CharSequence rawPassword, String encodedPassword) { 
     try { 
      if (encodedPassword.equals(Helper.md5(rawPassword.toString()))) { 
       //Helper.md5 is just a static method to encode the password. 
       return true; 
      } 
      return false; 
     } catch (Exception e) { 
      return false; 
     } 
    } 
} 

SuccessLoginHandler

@Component 
class SuccessLoginHandler implements AuthenticationSuccessHandler { 

    @Override 
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { 

     String password = request.getParameter("password"); 

     // TODO: logic when login success 

     response.sendRedirect("/index"); 
    } 
} 

正如你所看到的,我创建了一个成功的处理程序来处理用户活动后成功登录。我认为它可能类似于创建一个定制的失败处理程序,并将其设置为failureHandler(),SecurityConfig。我试过如下,但我只能重定向页面,我不知道如何同时发送一些额外的消息。

public class FailureLoginHandler implements AuthenticationFailureHandler { 

    @Override 
    public void onAuthenticationFailure(
      HttpServletRequest request, 
      HttpServletResponse response, 
      AuthenticationException e) throws IOException, ServletException { 


     //what to do to send back some message? 

     response.sendRedirect("/login?error"); 

    } 
} 

我是Spring Boot的新手,任何建议都将非常感谢。

+1

请按照[OWASP指导方针](https://www.owasp.org/index.php/Authentication_Cheat_Sheet#Authentication_and_Error_Messages)对用户进行身份验证,并且不要返回邀请攻击者探测和猜测用户帐户的消息,并且密码 –

回答

0

在FailureHandler设置下面的URL

/login?error=<Some_Error_Code> 

获取登录控制器错误代码,并设置基于错误代码适当地在UI显示错误消息。