JavaEE + socialauth库,登录后要存储什么

时间:2015-02-18 14:52:58

标签: java oauth oauth-2.0 socialauth

我在本教程后面使用了socialauth库: https://github.com/3pillarlabs/socialauth/wiki/Getting-Started-with-implementing-SocialAuth

一切正常,我只是不明白在第3步结束后存储在哪里/什么。我的意思是我不想强迫用户登录每次点击。我试图从例子中弄清楚这一点,但我不能......

这就是我所拥有的:

@WebServlet("/success")
public class AfterOAuth extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // get the auth provider manager from session
            SocialAuthManager manager = (SocialAuthManager) req.getSession().getAttribute("authManager");

            // call connect method of manager which returns the provider object.
            // Pass request parameter map while calling connect method.
            Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(req);
            AuthProvider provider = manager.connect(paramsMap);

            // get profile
            Profile p = provider.getUserProfile();

            // you can obtain profile information
            resp.getOutputStream().print(p.getFirstName());

            // OK, everything is fine by now what should I store in my Session?
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

好的,我使用提供的CDI Class找到了一个解决方案,并简单地覆盖了init()和servlet部分:

package com.test.oauth;

import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Properties;

import javax.enterprise.context.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import config.KicEngineRootRessourceLoader;
import org.apache.log4j.Logger;
import org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.AuthProviderFactory;
import org.brickred.socialauth.Contact;
import org.brickred.socialauth.Profile;
import org.brickred.socialauth.SocialAuthConfig;
import org.brickred.socialauth.SocialAuthManager;
import org.brickred.socialauth.util.SocialAuthUtil;

/**
 * Created by kic on 19.02.15.
 */
@Named("socialauth")
@SessionScoped
public class SocialAuth implements Serializable {
    /**
     * Serial version UID generated by Eclipse
     */
    private static final long serialVersionUID = 1789108831048043099L;


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

    private String id;
    private Profile profile;
    private AuthProvider provider;
    private String status;
    private String viewUrl;


    private SocialAuthManager manager;
    private SocialAuthConfig config;


    public void init() {
        id = null;
        provider = null;
        config = new SocialAuthConfig().getDefault();
        try {
            Properties oauth = new Properties();
            KicEngineRootRessourceLoader.loadProperties(oauth, "oauth_consumer");
            config.load(oauth);

            manager = new SocialAuthManager();
            manager.setSocialAuthConfig(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public SocialAuth() {
        init();
    }

    public String getId() {
        return id;
    }

    /**
     * Sets the authentication provider. It is mandatory to do this before
     * calling login
     *
     * @param id
     *            Can either have values facebook, foursquare, google, hotmail,
     *            linkedin, myspace, twitter, yahoo OR an OpenID URL
     */

    public void setId(final String id) {
        this.id = id;
    }

    /**
     * Sets the view URL to which the user will be redirected after
     * authentication
     *
     * @param viewUrl
     *            Relative URL of the view, for example "/openid.xhtml"
     */
    public void setViewUrl(final String viewUrl) {
        this.viewUrl = viewUrl;
    }

    /**
     * Gets the relative URL of the view to which user will be redirected after
     * authentication
     *
     * @return relative URL of the view
     */
    public String getViewUrl() {
        return viewUrl;
    }

    /**
     * This is the most important action. It redirects the browser to an
     * appropriate URL which will be used for authentication with the provider
     * you set using setId()
     *
     * @throws Exception
     */
    public void login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //String url = manager.getAuthenticationUrl(req.getParameter("provider"), successUrl);
        String returnToUrl = viewUrl;
        String url = manager.getAuthenticationUrl(id, returnToUrl);

        // Store in session
        req.getSession().setAttribute("authManager", manager);

        // redirect
        log.info("Redirecting to:" + url);
        resp.sendRedirect(url);
    }

    /**
     * Verifies the user when the external provider redirects back to our
     * application
     *
     * @throws Exception
     */
    public void connect(HttpServletRequest request) throws Exception {
        provider = manager.connect(SocialAuthUtil.getRequestParametersMap(request));
        profile= provider.getUserProfile();
    }

    /**
     * Reinitializes the bean
     */
    public void logout() {
        init();
    }


    /**
     * Returns the Profile information for the user. Should be called only after
     * loginImmediately()
     *
     * @return Profile of the user
     */
    public Profile getProfile() {
        return profile;
    }

    /**
     * Status of the user to be updated on a provider like Facebook or Twitter.
     * Remember this will not give us the current status of the user
     *
     * @return status message to be updated
     */
    public String getStatus() {
        return status;
    }

    /**
     * Status of the user to be updated on a provider like Facebook or Twitter.
     * To actually update the status, call updateStatus action.
     *
     * @param status
     */
    public void setStatus(final String status) {
        this.status = status;
    }

    /**
     * Updates the status on the given provider. Exception will be thrown if the
     * provider does not provide this facility
     */
    public void updateStatus() throws Exception {
        provider.updateStatus(status);
    }

    /**
     * Gets the list of contacts available from the provider. This may be used
     * to import contacts of any user in your web application from your chosen
     * provider like Gmail, Yahoo or Hotmail
     *
     * @return list of contacts
     */
    public List<Contact> getContactList() throws Exception {
        return provider.getContactList();
    }
    /**
     * Retrieves the user profile from the provider.
     *
     * @return Profile object containing the profile information.
     * @throws Exception
     */
    public Profile getUserProfile() throws Exception {
        return provider.getUserProfile();
    }
}

现在我可以在任何需要的地方使用@Inject SocialAuth。