如何使用Spring Security验证Bean中的登录名? [英] How to validate a login inside a bean using spring security?

查看:119
本文介绍了如何使用Spring Security验证Bean中的登录名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在学习Spring,并且在PrimeFaces中使用JSF.

So I'm learning Spring and I'm using JSF with PrimeFaces.

我的问题:

我想知道如何(如果可能)使用bean中的布尔函数对用户凭证进行身份验证和授权,如下所示:

I would like to know how (if possible) to authenticate and authorize user credentials using a boolean function in a bean, like this:

public boolean check() {
  boolean isLoginValid = false;
  if (//run something like j_spring_security_check) {
      //obtain user authorizations....
      isLoginValid = true;
  }
  return isLoginValid;
}

原因:

public void doLogin() {
    RequestContext context = RequestContext.getCurrentInstance();

    FacesMessage msg;
    boolean loggedIn;

    if (check() //would use the functin here) {
        loggedIn = true;
        msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", usuario);
    } else {
        loggedIn = false;
        msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Invalid credentials");
    }

    FacesContext.getCurrentInstance().addMessage(null, msg);
    context.addCallbackParam("loggedIn", loggedIn);
    context.addCallbackParam("authorization", this.auth #obtained in check());
}

这样,我可以通过ajax将布尔值发送到我的按钮,就像这样:

This way I could have the boolean sent to my button via ajax, like this:

<p:commandButton id="loginButton" value="Login" update=":growl"   
                          actionListener="#{loginBean.doLogin}"   
                          oncomplete="handleLoginRequest(xhr, status, args)"/>

function handleLoginRequest(xhr, status, args) {
            if(args.validationFailed || !args.loggedIn) {  
                jQuery('#dialog').effect("shake", { times:3 }, 100);
            } else {
                jQuery('#dialog').effect("shake", { times:1 }, 200);
                //And redirect to the right page.
            }  
        }

谢谢!

推荐答案

借助SpringBeanFacesELResolver,您可以从Spring Application Context中解析托管属性Authentication Manager,并且JSF的IOC将Bean注入到您的支持Bean中

With the help of SpringBeanFacesELResolver, you can have the managed property Authentication Manager resolved from the Spring Application Context and JSF's IOC injects the bean to your backing bean.

为此,将SpringBeanFacesELResolver添加到您的faces-config.xml中,如下所示:

For this add SpringBeanFacesELResolver to your faces-config.xml like this:

<application>
    <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>

,然后在您的支持bean中,可以对传递的Authentication对象进行身份验证,如下所示:

and then in your backing bean you can authenticate the passed Authentication object like below:

public class LoginBean implements Serializable {
    private static final long serialVersionUID = 1L;
    private String userName;
    private String password;
    @ManagedProperty(value="#{authenticationManager}")
        private AuthenticationManager authenticationManager;
        public AuthenticationManager getAuthenticationManager() {
        return authenticationManager;
    }

    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        this.authenticationManager= authenticationManager;
    }

    public String doLogin() {
        Authentication authenticationRequestToken =
              new UsernamePasswordAuthenticationToken( userName, password );
        //authentication action
        try {
            Authentication authenticationResponseToken =
                authenticationManager.authenticate(authenticationRequestToken);
            SecurityContextHolder.getContext().setAuthentication(authenticationResponseToken);
            //ok, test if authenticated, if yes reroute
            if (authenticationResponseToken.isAuthenticated()) {
                //lookup authentication success url, or find redirect parameter from login bean
                return "/secure/examples";
            }
        } catch (BadCredentialsException badCredentialsException) {
            FacesMessage facesMessage =
                new FacesMessage("Login Failed: please check your username/password and try again.");
            FacesContext.getCurrentInstance().addMessage(null,facesMessage);
        } catch (LockedException lockedException) {
            FacesMessage facesMessage =
                new FacesMessage("Account Locked: please contact your administrator.");
            FacesContext.getCurrentInstance().addMessage(null,facesMessage);
        } catch (DisabledException disabledException) {
            FacesMessage facesMessage =
                new FacesMessage("Account Disabled: please contact your administrator.");
            FacesContext.getCurrentInstance().addMessage(null,facesMessage);
        }

        return null;
    }
}

另请参阅:

更新

如果由于某种原因而无法使用@ManagedProperty.您可以通过将JSF ManagedBean制成Spring托管的组件来尝试使用Spring @Autowired批注. 为此,请像这样注释Bean:

If you are unable to use the @ManagedProperty for some reason. You can try to use Spring @Autowired annotation by making the JSF ManagedBean into a Spring-managed Component. For that annotate the bean like this:

@Component
@Scope("request")
public class LoginController implements Serializable {
    @Autowired
    private AuthenticationManager authenticationManager;
        //bean getters and setters

像这样将component-scan元素添加到您的Spring Application上下文中:

and add component-scan element to your Spring Application context like this:

<context:component-scan base-package="com.examples"/>

对于您关于使用authentication-success-handler-ref的问题,由于我们正在手动进行身份验证,因此您恐怕可以使用它.如果您的要求只是根据用户角色转发到适当的url.您可以执行以下操作:

For you question regarding using authentication-success-handler-ref, I am afraid you can use that since we are manually doing the authentication. If your requirement is to just forward to appropriate url based of user role. You can do something like this:

if (authenticationResponseToken.isAuthenticated()) {
   String userTargetUrl = "/general/main";
   String adminTargetUrl = "/secure/examples";
   Set<String> roles = AuthorityUtils.authorityListToSet(authenticationResponseToken.getAuthorities());
   if (roles.contains("ROLE_ADMIN")) {
      return adminTargetUrl;
   }
   else if(roles.contains("ROLE_USER")) {
      return userTargetUrl;
   }
}

这篇关于如何使用Spring Security验证Bean中的登录名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆