appengine에 로그인하여 app 엔진에 액세스하고 App Engine의 User Service API에 액세스하려고합니다. 기본적으로 누가 내 서블릿에 로그인했는지 볼 수 있기를 원합니다. 나는 안드로이드에서 authtoken을 가져 와서 앱 엔진에서 ASID (또는 SACID) 쿠키를 gettting하는 인증 흐름을 사용하고 있습니다. 쿠키는 http 요청과 함께 appengine 서블릿으로 전송됩니다. 이 모든 코드는 작동하지만이 코드를 사용하여 사용자를 얻으려는 경우 다음과 같이 나타납니다.android 클라이언트에서 appengine에 로그인
UserService userService = UserServiceFactory.getUserService();
User user= userService.getCurrentUser();
사용자는 항상 null입니다. 내 질문에 내가 여기서 뭔가를 놓친거야? 사용자 서비스가 null 사용자를 반환하는 이유는 무엇입니까? 아래는 내 appengine 및 android 코드입니다. 어떤 도움이라도 대단히 감사하겠습니다!
앱 엔진 :
public class MyServlet extends HttpServlet {
public void process(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
resp.setContentType("text/plain");
UserService userService = UserServiceFactory.getUserService();
User user= userService.getCurrentUser();
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
process(req, resp);
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
process(req, resp);
}
}
안드로이드 코드 :
public class AppEngineClient {
static final String BASE_URL = Util.getBaseUrl(this);
private static final String AUTH_URL = BASE_URL + "/_ah/login";
private static final String AUTH_TOKEN_TYPE = "ah";
private final Context mContext;
private final String mAccountName;
private static final String TAG = "AppEngineClient";
public AppEngineClient(Context context, String accountName) {
this.mContext = context;
this.mAccountName = accountName;
}
public HttpResponse makeRequest(String urlPath, List<NameValuePair> params) throws Exception {
HttpResponse res = makeRequestNoRetry(urlPath, params, false);
if (res.getStatusLine().getStatusCode() == 500) {
res = makeRequestNoRetry(urlPath, params, true);
}
return res;
}
private HttpResponse makeRequestNoRetry(String urlPath, List<NameValuePair> params, boolean newToken)
throws Exception {
// Get auth token for account
Account account = new Account(mAccountName, "com.google");
String authToken = getAuthToken(mContext, account);
if (newToken) { // invalidate the cached token
AccountManager accountManager = AccountManager.get(mContext);
accountManager.invalidateAuthToken(account.type, authToken);
authToken = getAuthToken(mContext, account);
}
// Get SACSID cookie
DefaultHttpClient client = new DefaultHttpClient();
String continueURL = BASE_URL;
URI uri = new URI(AUTH_URL + "?continue=" +
URLEncoder.encode(continueURL, "UTF-8") +
"&auth=" + authToken);
HttpGet method = new HttpGet(uri);
final HttpParams getParams = new BasicHttpParams();
HttpClientParams.setRedirecting(getParams, false); // continue is not used
method.setParams(getParams);
HttpResponse res = client.execute(method);
Header[] headers = res.getHeaders("Set-Cookie");
if (res.getStatusLine().getStatusCode() != 302 ||
headers.length == 0) {
return res;
}
String sascidCookie = null;
for (Header header: headers) {
if (header.getValue().indexOf("SACSID=") >=0) {
// let's parse it
String value = header.getValue();
String[] pairs = value.split(";");
ascidCookie = pairs[0];
}
}
// Make POST request
uri = new URI(BASE_URL + urlPath);
HttpPost post = new HttpPost(uri);
UrlEncodedFormEntity entity =
new UrlEncodedFormEntity(params, "UTF-8");
post.setEntity(entity);
post.setHeader("Cookie", ascidCookie);
post.setHeader("X-Same-Domain", "1"); // XSRF
res = client.execute(post);
return res;
}
private String getAuthToken(Context context, Account account) throws PendingAuthException {
String authToken = null;
AccountManager accountManager = AccountManager.get(context);
try {
AccountManagerFuture<Bundle> future =
accountManager.getAuthToken (account, AUTH_TOKEN_TYPE, false, null, null);
Bundle bundle = future.getResult();
authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
if (authToken == null) {
throw new PendingAuthException(bundle);
}
} catch (OperationCanceledException e) {
Log.w(TAG, e.getMessage());
} catch (AuthenticatorException e) {
Log.w(TAG, e.getMessage());
} catch (IOException e) {
Log.w(TAG, e.getMessage());
}
return authToken;
}
public class PendingAuthException extends Exception {
private static final long serialVersionUID = 1L;
private final Bundle mAccountManagerBundle;
public PendingAuthException(Bundle accountManagerBundle) {
super();
mAccountManagerBundle = accountManagerBundle;
}
public Bundle getAccountManagerBundle() {
return mAccountManagerBundle;
}
}
}
세션을 사용할 수 있습니다. 나는 브라우저에서 시도하고 동일한 오류가 발생했습니다. 좀 더 파고해야 겠어. 감사합니다. – Patrick
web.xml에서 리소스에 대한 인증이 필요합니까? –
나는 그것을 지금 추가하고 테스트하지 않았다. 아직도 운이 없다. 이제 로그인 페이지로 리디렉션됩니다. – Patrick