Обработка сессий в JSF при работе с API Socialauth, для входа - PullRequest
0 голосов
/ 02 декабря 2011

Я работал с API социальной аутентификации в JSF, чтобы получить логин через Facebook, я не знаю, правильно ли я создаю сессию.Я искал некоторые вещи из интернета и делал это.Теперь я догнал некоторую ошибку.

в соответствии с социальной аутентификацией, сначала нам нужно вызвать функцию, которая помогает получить URL-адрес аутентификации от Facebook, где мне нужно создать сеанс и установить для него атрибуты, с параметрами из Facebook после того, как пользовательрегистрируется в Facebook.

, так что моя первая страница просмотра будет просто содержать командную кнопку для вызова соответствующей функции.

            <h:form><h:commandButton value="submit" action="#{socialNetworkAuthentication.facebookAuthentication}"></h:commandButton></h:form>

затем функцию, которая вызывается ...

                 public String facebookAuthentication(){

    try{


           //Create an instance of SocialAuthConfgi object
           SocialAuthConfig config = SocialAuthConfig.getDefault();

 String propUrl="oauth_consumer.properties";


          //load configuration. By default load the configuration from oauth_consumer.properties.
          //You can also pass input stream, properties object or properties file name.
           config.load(propUrl);

          //Create an instance of SocialAuthManager and set config
          SocialAuthManager manager = new SocialAuthManager();
          manager.setSocialAuthConfig(config);

          //URL of YOUR application which will be called after authentication
           String successUrl = "http://chennaivolunteers.com/ChennaiVolunteers/faces/cv/employee-profile.xhtml";


        // get Provider URL to which you should redirect for authentication.
          // id can have values "facebook", "twitter", "yahoo" etc. or the OpenID URL
          String url = manager.getAuthenticationUrl("facebook", successUrl);

          // Store in session
          HttpServletRequest request=(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            HttpSession ses = request.getSession(true);

          ses.setAttribute("authManager", manager);
          System.out.println(url);
          FacesContext.getCurrentInstance().responseComplete();
       FacesContext.getCurrentInstance().getExternalContext().redirect(url);

        }

затем, наконец, я перенаправляю на соответствующий URL-адрес, указанный на facebook, после того как пользователь войдет в facebook, затем он автоматически перейдет к succesURL, который упоминался в приведенном выше коде.

В моем successURL у меня просто есть выходной текст.

                          <tr><td class="profile-head"><h:outputText id="name" value="#{employeeProfile.profileName}" /></td></tr>
            <tr><td class="content-black">
            <div class="padding-2"><h:outputText id="name" value="#{employeeProfile.profileName}" />

В бэк-бине я создал сеанс для получения атрибутов, которые я установил ранее.

                  public class EmployeeProfile {

public String profileName;

public String getProfileName() throws Exception  {

HttpServletRequest request=(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    HttpSession ses = request.getSession(true);
    SocialAuthManager m = (SocialAuthManager)ses.getAttribute("authManager");        
    AuthProvider provider = m.connect(SocialAuthUtil.getRequestParametersMap(request));
    Profile p = provider.getUserProfile();
      String userName=p.getFirstName();
      System.out.println(userName);

    return userName;

}

public void setProfileName(String profileName) {
    this.profileName = profileName;
}

, когда я печатал имя пользователяв консоли это происходит, но это не страница просмотра этого компонента поддержки, но есть два исключения, как показано ниже.

             1.  javax.faces.FacesException: Could not retrieve value of component with path : {Component-Path : [Class: javax.faces.component.UIViewRoot,ViewId: /cv/employee-profile.xhtml][Class: javax.faces.component.html.HtmlOutputText,Id: name]}
           Caused by: javax.el.ELException: /cv/employee-profile.xhtml at line 133 and column 105 value="#{employeeProfile.profileName}": Error reading 'profileName' on type socialServlet.EmployeeProfile       


            2.javax.faces.FacesException: This is not the same SocailAuthManager object that was used for login.Please check if you have called getAuthenticationUrl() method before calling connect()
              Caused by: This is not the same SocailAuthManager object that was used for login.Please check if you have called getAuthenticationUrl() method before calling connect()

Последнее - просто входвстроенное исключение API социальной аутентификации, но я не думаю, что в этом есть какая-либо проблема, потому что, когда я пробую это с сервлетом, все работает нормально, я думаю, что делаю какую-то ошибку в сеансе JSF.Но я не знаю, где я неправ.

1 Ответ

0 голосов
/ 03 декабря 2011

Моя проблема теперь исправлена ​​.. ошибка, которую я сделал, я снова вызвал функцию connect (). Теперь я сделал все в самом конструкторе. Работает нормально.

                public class EmployeeProfile {


public EmployeeProfile() throws Exception {
    // TODO Auto-generated constructor stub




        ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest)ectx.getRequest();
        HttpSession session = request.getSession(true);
         SocialAuthManager m = (SocialAuthManager)session.getAttribute("authManager"); 
         AuthProvider provider = m.connect(SocialAuthUtil.getRequestParametersMap(request));
         Profile p = provider.getUserProfile();
             String userName=p.getFirstName();    
              System.out.println(userName);
              setProfileName(userName);
              setBirthDate(p.getDob());
              setImageUrl(p.getProfileImageURL());
              p.getGender();


}
...