SHOEISHA iD

※旧SEメンバーシップ会員の方は、同じ登録情報(メールアドレス&パスワード)でログインいただけます

DeveloperZine(デベロッパージン)- エンジニアの意思決定を支える技術情報メディア ProductZine

CodeZine編集部では、現場で活躍するデベロッパーをスターにするためのカンファレンス「Developers Summit」や、エンジニアの生きざまをブーストするためのイベント「Developers Boost」など、さまざまなカンファレンスを企画・運営しています。

Zusaar開発者に学ぶソーシャルアプリ入門

WebアプリにSNSアカウントでのログインを実装する

Zusaar開発者に学ぶソーシャルアプリ入門(1)

mixiの場合

アプリケーション登録

 mixiの場合、アプリケーション登録に先立ってパートナー登録をする必要があります。パートナー登録の手順は法人と個人で異なるようです。

 本稿で対象にしているOAuth API(mixi Graph API)を個人で使用する場合は、クレジットカードの登録が必要となるため、注意してください。

 パートナー登録が完了したらPartner Dashboardから[mixi Graph API]-[新規サービス追加]と進みます。

 必要事項を入力しますが、Facebookの場合と同じく「リダイレクト URL」は開発用と本番用で設定を変える必要がありますので、本番公開時には複数アプリを登録してもよいでしょう。

 登録が完了しました。ここでも「Consumer Secret」は絶対に他人に知られないようにしてください。

サンプルコード

 mixiのOAuthはバージョン2.0です。Facebookと同様、ライブラリに頼らない実装も現実的ですが、ここではmixiの中の人が作成した非公式ライブラリ「mgapi-java-client」を使ってみます。

mixiへリダイレクトするServlet(/source/src/sample/mixi/LoginServlet.java)
package sample.mixi;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jp.eisbahn.mgapi.auth.Authorization;
import jp.eisbahn.mgapi.auth.ClientConfig;
import jp.eisbahn.mgapi.auth.Device;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        ClientConfig clientConfig = new ClientConfig();
        clientConfig.loadFromResource("/mixi.properties");

        String[] scopes = { "r_profile"};
        String display = "pc";
        Device device = Device.PC;
        Authorization authorization = new Authorization();
        authorization.redirect(response, clientConfig, scopes, display, device);
        return;
    }
}

 上記が「mixiアカウントでログイン」で実行されるコードです。mgapi-java-clientの場合、Consumer Key、Consumer Secretは指定されたPropertyファイルに指定された形式で保存する必要があります。ユーザーはmixiにリダイレクトされ以下の画面が表示されます。

 「同意する」をクリックすると、特殊なパラメータとともに以下のコードにリダイレクトされます。

mixiからリダイレクトされるServlet(/source/src/sample/mixi/CallbackServlet.java)
package sample.mixi;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jp.eisbahn.mgapi.api.ApiAccessException;
import jp.eisbahn.mgapi.api.Client;
import jp.eisbahn.mgapi.api.people.PeopleRequest;
import jp.eisbahn.mgapi.api.people.PeopleResponse;
import jp.eisbahn.mgapi.api.people.Person;
import jp.eisbahn.mgapi.auth.ClientConfig;
import jp.eisbahn.mgapi.auth.Token;
import jp.eisbahn.mgapi.auth.TokenProducer;
import jp.eisbahn.mgapi.http.BasicHttpFetcher;

@SuppressWarnings("serial")
public class CallbackServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        /*
         * アクセストークンの取得
         */
        final String code = request.getParameter("code");
        ClientConfig clientConfig = new ClientConfig();
        clientConfig.loadFromResource("/mixi.properties");

        TokenProducer producer = new TokenProducer();
        producer.setHttpFetcher(new BasicHttpFetcher());
        producer.setClientConfig(clientConfig);
        final Token token = producer.issue(code);
        final String accessToken = token.getAccessToken();
        final String refreshToken = token.getRefreshToken();

        /*
         * APIの実行
         */
        final Token token2 = new Token(refreshToken, accessToken, 0);
        Client client = new Client();
        client.setHttpFetcher(new BasicHttpFetcher());
        PeopleRequest mixiRequest = new PeopleRequest();
        mixiRequest.setUserId("@me");
        mixiRequest.setGroupId("@self");
        PeopleResponse peopleResponse;
        try {
            peopleResponse = client.send(token2, mixiRequest);
        } catch (ApiAccessException e) {
            throw new RuntimeException(e);
        }
        List entries = peopleResponse.getEntries();
        final Person me = entries.get(0);

        /*
         * ログイン処理
         */
        Map map = new HashMap();
        map.put("service", "mixi");
        map.put("userId", me.getId());
        map.put("name", me.getDisplayName());
        map.put("accessToken", token.getAccessToken());
        request.getSession().setAttribute("loginUser", map);

        response.sendRedirect(request.getContextPath() + "/");
    }
}

 ここでアクセストークンを取得します。

 mixiもFacebookと同じくOAuthのバージョンは2.0なのですが若干仕様が異なります(OAuth2.0の中でも細かいバージョンの違いがある訳です)。具体的にはアクセストークンの他にリフレッシュトークンという文字列も必要となります。mixiのアクセストークンの有効期限は15分と短く、それを過ぎた場合はリフレッシュトークンを用いてアクセストークンを更新する必要があります。

次のページ
注意点

この記事は参考になりましたか?

この記事の著者

石井 賢司(イシイ ケンジ)

 会社員時代にGoogle App Engineに出会い傾倒、新規事業としてGAEを使った『決済できるソーシャルイベントプラットフォーム「Zusaar」』を立ち上げる。現在はフリーランスのエンジニアとして活動しつつ新たなサービスも模索中。Blog: http://d.hatena.ne.jp/knj77 ...

※プロフィールは、執筆時点、または直近の記事の寄稿時点での内容です

この記事は参考になりましたか?

この記事をシェア

CodeZine(コードジン)
https://codezine.jp/article/detail/6572 2012/06/01 14:00

イベント

CodeZine編集部では、現場で活躍するデベロッパーをスターにするためのカンファレンス「Developers Summit」や、エンジニアの生きざまをブーストするためのイベント「Developers Boost」など、さまざまなカンファレンスを企画・運営しています。

新規会員登録無料のご案内

  • ・全ての過去記事が閲覧できます
  • ・会員限定メルマガを受信できます

メールバックナンバー