проблема с использованием пользовательского царства в Apache Shiro.с JSF - PullRequest
0 голосов
/ 24 сентября 2018

Я пытаюсь использовать apache shiro с пользовательской областью (которая будет вызывать webservice для получения токена, передающего пользователя и пароль).однако, когда я пытаюсь войти в систему, ничего не происходит (также нет ошибки), дайте мне знать, если я пропустил какую-то конфигурацию

файл shiro.ini

[main]
sessionManager = org.apache.shiro.session.mgt.DefaultSessionManager

# ensure the securityManager uses our native SessionManager
securityManager.sessionManager = $sessionManager

#set the sessionManager to use an enterprise cache for backing storage:
sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO
securityManager.sessionManager.sessionDAO = $sessionDAO

user = com.xyz.so.myrep.web.JSFAwareUserFilter
user.loginUrl = /login.xhtml

# Auth
MyRealm = com.xyz.so.myrep.service.MyRealm
securityManager.realms = $MyRealm
MyRealmCredentialsMatcher = 
org.apache.shiro.authc.credential.AllowAllCredentialsMatcher
MyRealm.credentialsMatcher = $MyRealmCredentialsMatcher

#Remember Me
rememberMe = org.apache.shiro.web.mgt.CookieRememberMeManager
securityManager.rememberMeManager = $rememberMe

[urls]
/login.xhtml = user
/logout = logout
/javax.faces.resource/** = anon
/about.xhtml = anon
/admin.xhtml = user, roles[EMP_ADMIN]
/config.xhtml = user, roles[EMP_POWER,EMP_ADMIN]
/index.xhtml = user, roles[EMP_ADMIN,EMP_POWER,EMP_USER]
/** = user, roles[EMP_USER]

MyRealm.java

public class MyRealm extends AuthorizingRealm  {

  @Inject
  userAuthService userAuthService;
  UamsUserDetailsForuser9Login uamsUserDetailsForuser9Login  = new UamsUserDetailsForuser9Login();

  private CredentialsMatcher credentialsMatcher;

  public String getName() {
   return "CustomRealm";
  }

  public boolean supports(AuthenticationToken token) {
   return true;
  }

     public CredentialsMatcher getCredentialsMatcher() {
         return credentialsMatcher;
     }

     public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
         this.credentialsMatcher = credentialsMatcher;
     }

  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(
    AuthenticationToken token) throws AuthenticationException {

    Subject currentUser = SecurityUtils.getSubject();
    Session session = currentUser.getSession();

    if (!currentUser.isAuthenticated()) {

    UsernamePasswordToken upToken = (UsernamePasswordToken) token;
    uamsUserDetailsForuser9Login = userAuthService.login(upToken.getUsername(),upToken.getPassword().toString()); 
    session.setAttribute( "token", uamsUserDetailsForuser9Login.getTicket() );
    currentUser.login(token);
    }

   return new SimpleAuthenticationInfo("", "".toCharArray(), getName());
  }

  /* (non-Javadoc)
   * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
   */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
    // TODO Auto-generated method stub
    return null;
  }
}

Класс контроллера:

@ManagedBean(name = "shiroLogin")
@ViewScoped
public class ShiroLoginController implements Serializable {
    /**
   * 
   */
  private static final long serialVersionUID = 1L;

    private static final Logger log = LoggerFactory.getLogger(ShiroLoginController.class);

    private String username;
    private String password;
    private Boolean rememberMe;

    public ShiroLoginController() {
    }

    /**
     * Try and authenticate the user
     */
    public void doLogin() {
      try {
        ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
        SecurityUtils.getSubject().login(new UsernamePasswordToken(username, password));
        SavedRequest savedRequest = WebUtils.getAndClearSavedRequest((HttpServletRequest)ctx.getRequest());
        // If shiro,ini for a given role doesnt contain the "user" filter, the saved request will contain
        // login.jsp, so just in case someone forgets to add the user filter...
        String redURL = savedRequest != null ? savedRequest.getRequestUrl() : "index.xhtml";
        if (redURL.contains("login.jsp")) redURL = "index.xhtml";
        ctx.redirect(redURL);
    }
    catch (AuthenticationException | IOException e) {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Invalid user name or password!"));

    }
    }

    /**
     * Adds a new SEVERITY_ERROR FacesMessage for the ui
     * @param message Error Message
     */
    private void facesError(String message) {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String login) {
        this.username = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String senha) {
        this.password = senha;
    }

    public Boolean getRememberMe() {
        return rememberMe;
    }

    public void setRememberMe(Boolean lembrar) {
        this.rememberMe = lembrar;
    }
}

login.xhtml

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui" >
<h:body>

<ui:composition template="/WEB-INF/template.xhtml">
<ui:define name="content">

<h:form id="login" >
    <p:panelGrid columns="3" style="margin: auto">
        <f:facet name="header">Log in</f:facet>

        <p:outputLabel for="username" value="Username:" />
            <p:inputText id="username" value="#{shiroLogin.username}" required="true" styleClass="input-full-width" />
            <p:message for="username" display="both" />

            <p:outputLabel for="password" value="Password:" />
            <p:password id="password" value="#{shiroLogin.password}" required="true" styleClass="input-full-width" />
            <p:message for="password" display="both"  />

        <f:facet name="footer" >
                    <p:commandButton value="Login" action="#{shiroLogin.doLogin}" update="login" styleClass="input-full-width"/>
        </f:facet>
    </p:panelGrid>
</h:form>

</ui:define>
</ui:composition>

</h:body>
</html>

web.xml

org.apache.shiro.web.env.EnvironmentLoaderListener ShiroFilter org.apache.shiro.web.servlet.ShiroFilter ShiroFilter / * ЗАПРОСИТЬ ВПЕРЕД ВКЛЮЧЕНА ОШИБКА

<welcome-file-list>
    <welcome-file>index.xhtml</welcome-file>
</welcome-file-list>

<session-config>
    <session-timeout>600</session-timeout>
</session-config>
...