UserDetailsS​​ervice不会抛出自定义异常

时间:2016-03-18 13:01:29

标签: java spring authentication spring-security jsf-2.2

对于我的项目,我使用了Spring 4.2.5,Spring Security 4.0.4和JSF Mojarra。我将从我的自定义UserDetailsS​​ervice中抛出一个自定义异常。

@Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException{

    com.entity.User domainUser = userDAO.getUser(login);

    boolean enabled = false;
    boolean accountNonExpired = true;
    boolean credentialsNonExpired = true;
    boolean accountNonLocked = true;

    if(!enabled){
         throw new DisabledException("User is disabled!");
    }

    return new User(domainUser.getLogin(), 
                    domainUser.getPassword(), 
                    enabled, 
                    accountNonExpired,
                    credentialsNonExpired, 
                    accountNonLocked, 
                    getAuthorities(domainUser.getRole().getId()));
}

我的LoginBean是:

public String login() {
    RequestContext context = RequestContext.getCurrentInstance();
    FacesMessage msg = null;
    boolean loggedIn = false;

    try {
        SecurityContext secContext = SecurityContextHolder.getContext();
        Authentication auth = new UsernamePasswordAuthenticationToken(username, password);
        secContext.setAuthentication(auth);

        loggedIn = true;
        msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", username);
        return "/pages/index?faces-redirect=true";
    } catch (DisabledException e) {
        loggedIn = false;
        msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Login Error", e.getMessage());
    } catch (ServletException e) {
        loggedIn = false;
        msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Login Error", e.getMessage());
    }
    FacesContext.getCurrentInstance().addMessage(null, msg);
    context.addCallbackParam("loggedIn", loggedIn);
    return "/login";
}

所以如果我设置"启用"为true并提供正确的用户凭据一切正常。但如果我将其更改为false,我将无法在日志中看到任何异常并且无法登录。

我尝试使用此代码。它工作正常,但我只能看到"不良凭据"在任何情况下都是例外。

HttpServletRequest httpReq = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
httpReq.login(username, password);

我刚开始使用java和spring,所以你能解释一下 http Req.login(用户名,密码) getContext.setAuthentication(auth)之间的区别。在第一种情况下,我可以检索经过身份验证的用户,在第二种情况下,我会获得匿名身份验证的用户。

哪个是用户身份验证和自定义UserDetailsS​​ervice的正确解决方案。

P.S。我使用的是基于java的配置。

对不起如果以前回答过这个问题。我无法找到有效的解决方案。

更新1:

如果我发表评论

if(!enabled){
     throw new DisabledException("User is disabled!");
}

在调试中我可以看到默认异常:

org.springframework.security.authentication.DisabledException: User is disabled

但我仍然无法在我的LoginBean中捕捉到这一点。为什么呢?

更新2:

我在spring安全配置中做了一些更改,现在当我使用 HttpServletRequest httpReq.login(用户名,密码)时,我可以在我的咆哮(primefaces)中看到锁定的,过期的异常

那么如何自定义异常消息呢? 我仍然无法理解 HttpServletRequest登录 UsernamePasswordAuthenticationToken身份验证之间的区别。

0 个答案:

没有答案
相关问题