2016-04-01 3 views
1

Мне нужно запомнить исходный URL-адрес Http Request, а затем перенаправить этот запрос в веб-форму для аутентификации пользователя. В случае успешной аутентификации пользователь должен быть перенаправлен на original URL, который был просто запомнен выше. Я использую JBoss 7.1.1 Final, стандартный web.xml и JBoss Войти Модуль org.jboss.security.auth.spi.DatabaseServerLoginModule:Внедрение пользовательского модуля ServerAuthModule для JBoss

Я упомянул следующие ссылки, которые не ответили на мой вопрос полностью:

Однако, после того, как impltementing мое решение, мой заказ ServerAuthModule не вызывается вообще. Что еще хуже, я не получил HttpResponse с сервера. Что-то сломалось, пожалуйста, помогите!

web.xml Мои:

 <security-constraint> 
      <web-resource-collection> 
       <web-resource-name>All resources in /pages/*</web-resource-name> 
       <description>All resources in /pages/*</description> 
       <url-pattern>/pages/*</url-pattern> 
       <http-method>GET</http-method> 
       <http-method>POST</http-method> 
      </web-resource-collection> 
      <auth-constraint> 
       <role-name>general</role-name> 
      </auth-constraint> 
     </security-constraint> 

     <security-constraint> 
      <display-name>Restrict direct access to the /resources folder.</display-name> 
      <web-resource-collection> 
       <web-resource-name>The /resources folder.</web-resource-name> 
       <url-pattern>/resources/*</url-pattern> 
      </web-resource-collection> 
      <auth-constraint /> 
     </security-constraint> 

     <login-config> 
      <auth-method>FORM</auth-method> 
      <form-login-config> 
       <form-login-page>/login.jsf</form-login-page> 
       <form-error-page>/loginFailed.jsf</form-error-page> 
      </form-login-config> 
     </login-config> 

     <security-role> 
      <role-name>general</role-name> 
     </security-role>  

Мой JBoss-web.xml:

<?xml version="1.0" encoding="UTF-8"?> 
    <jboss-web> 
     <security-domain>jBossJaasMysqlRealm</security-domain> 
     <valve> 
      <class-name>org.jboss.as.web.security.jaspi.WebJASPIAuthenticator</class-name> 
     </valve> 
    </jboss-web> 

Мой standalone.xml:

<security-domain name="jBossJaasMysqlRealm" cache-type="default"> 
       <authentication-jaspi> 
        <login-module-stack name="lm-stack"> 
         <login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule" flag="required"> 
          <module-option name="dsJndiName" value="java:/MySqlDS_IamOK"/> 
          <module-option name="principalsQuery" value="select password from user where username=?"/> 
          <module-option name="rolesQuery" value="select role, 'Roles' from user_role where username=?"/> 
         </login-module> 
        </login-module-stack> 
        <auth-module code="at.alex.ok.web.utils.RequestMarkerServerAuthModule" login-module-stack-ref="lm-stack"/> 
       </authentication-jaspi> 
      </security-domain> 

Мой заказ WebServerAuthModule:

import org.jboss.as.web.security.jaspi.modules.WebServerAuthModule; 

    public class RequestMarkerServerAuthModule extends WebServerAuthModule { 

     public static final String ORIGINAL_URL = "originalURL"; 

     protected static final Class[] supportedMessageTypes = new Class[] { 
       HttpServletRequest.class, HttpServletResponse.class }; 


     public void initialize(MessagePolicy reqPolicy, MessagePolicy resPolicy, 
       CallbackHandler cBH, Map opts) throws AuthException { 

      System.out.println(this.getClass().getName() + ".initialize() called"); 
     } 

     public Class[] getSupportedMessageTypes() { 
      return supportedMessageTypes; 
     } 

     public AuthStatus validateRequest(MessageInfo msgInfo, Subject client, 
       Subject server) throws AuthException { 
      try { 
       System.out.println(this.getClass().getName() + ".validateRequest() called"); 

       processAuthorizationToken(msgInfo, client); 
       return AuthStatus.SUCCESS; 

      } catch (Exception e) { 
       AuthException ae = new AuthException(); 
       ae.initCause(e); 
       throw ae; 
      } 
     } 

     private void processAuthorizationToken(MessageInfo msgInfo, Subject s) 
       throws AuthException { 

      HttpServletRequest request = (HttpServletRequest) msgInfo 
        .getRequestMessage(); 

      String originalURL = request.getRequestURL().toString(); 
      request.getSession().setAttribute(ORIGINAL_URL, originalURL); 
     } 


     public AuthStatus secureResponse(MessageInfo msgInfo, Subject service) 
       throws AuthException { 

      System.out.println(this.getClass().getName() + ".secureResponse() called"); 

      return AuthStatus.SEND_SUCCESS; 
     } 

     public void cleanSubject(MessageInfo msgInfo, Subject subject) 
       throws AuthException { 
      System.out.println(this.getClass().getName() + ".cleanSubject() called"); 

    } 

} 
+1

JBoss 7.1.1 и JASPIC являются нет друзей. –

ответ

-1

Этот вопрос вставлен невообразимо, потому что: Для перенаправления на первоначально запрошенный URL после успешного входа в систему нет необходимости реализовывать пользовательский ServerAuthModule для JBoss.

Интерфейс javax.servlet.RequestDispatcher имеет константу FORWARD_REQUEST_URI, которая обозначает имя атрибута Http-Request, под которым исходный URI запроса становится доступным процессору пересылаемого запроса.

Использование JSF 2.2 и View-Scoped бэк боба LoginBean, мое решение просто получить первоначально запрошенной URL в методе @PostConstruct подкладочного фасоли, и сохранить его в атрибут сессии, следующим образом:

@ManagedBean(name="loginBean") 
@ViewScoped 
public class LoginBean { 

    private String originalURL; 

    @PostConstruct 
    private void init() { 
     ExternalContext extCtx = FacesContext.getCurrentInstance().getExternalContext(); 

     String origURL = (String) extCtx.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI); 

     HttpServletRequest request = (HttpServletRequest) extCtx.getRequest(); 
     HttpSession session = (HttpSession)extCtx.getSession(false); 

     if (session == null){ 
      session = (HttpSession)extCtx.getSession(true); 
     } 

     if (origURL!=null && session.getAttribute(ORIGINAL_URL) == null){ 
      String applicationName = request.getContextPath(); 
      origURL = origURL.substring(applicationName.length(), origURL.length()); 
      session.setAttribute(ORIGINAL_URL, origURL); 
     } 
    } 

Затем в методе логин() одного и того же опорного боба, перенаправить пользователя на первоначально запрошенной URL в случае входа в систему прошла успешно, например так:

public String login() { 

    HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest(); 

    try { 
     request.login(this.getLogin(), this.getPassword()); 
    } catch (ServletException e) { 
     // handle bad username/password here 
    } 

    return this.originalURL + "?faces-redirect=true"; 
}