Гость
Целевая тема:
Создать новую тему:
Автор:
Форумы / Java [игнор отключен] [закрыт для гостей] / Нужен пример авторизации с сайта для одноклассников / 3 сообщений из 3, страница 1 из 1
05.10.2012, 12:30:18
    #37985183
ArmenA
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Нужен пример авторизации с сайта для одноклассников
Я использовал socialauth - http://socialauth.in/socialauthdemo/
но для класников надо расширять его, я сделал класс, но после запроса классники дают еррор - "Use post only".. ничего не понимаю

у кого есть пример на java для логина из сайта на одноклассники, вот мой пример, secure kej/value передаются из вне...

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.
267.
268.
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
281.
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
292.
293.
294.
295.
296.
297.
298.
299.
300.
301.
302.
303.
304.
305.
306.
307.
308.
309.
310.
311.
312.
313.
314.
315.
316.
317.
318.
319.
320.
321.
322.
323.
324.
325.
326.
327.
328.
329.
330.
331.
332.
333.
334.
335.
336.
337.
338.
339.
340.
341.
342.
343.
344.
345.
346.
347.
348.
349.
350.
351.
352.
353.
354.
355.
356.
357.
358.
359.
360.
361.
362.
363.
364.
public class OdnoklassnikiImpl extends AbstractProvider implements AuthProvider,
		Serializable {
	private static final long serialVersionUID = 8644510564735754296L;
	private static final String PROFILE_URL = "http://www.odnoklassniki.ru/profile/";
//	private static final String CONTACTS_URL = "";
	//private static final String UPDATE_STATUS_URL = "";
	private static final String PROFILE_IMAGE_URL = "http://i113.odnoklassniki.ru/getImage?photoId";
	private static final String PUBLIC_PROFILE_URL = "";
	private static final Map<String, String> ENDPOINTS;
	private final Log LOG = LogFactory.getLog(OdnoklassnikiImpl.class);

	private Permission scope;
	private OAuthConfig config;
	private Profile userProfile;
	private AccessGrant accessGrant;
	private OAuthStrategyBase authenticationStrategy;

	// set this to the list of extended permissions you want
	private static final String[] AllPerms = new String[] { "first_name",
			"email"};
	private static final String[] AuthPerms = new String[] { "first_name",
			"last_name"};

	static {
		ENDPOINTS = new HashMap<String, String>();
		ENDPOINTS.put(Constants.OAUTH_AUTHORIZATION_URL,
				"http://api.odnoklassniki.ru/oauth/token.do");
		ENDPOINTS.put(Constants.OAUTH_ACCESS_TOKEN_URL,
				"http://api.odnoklassniki.ru/fb.do");
	}

	/** api.odnoklassniki.ru/oauth/token.do?client_id=CBAJFPIGABABABABA&response_type=code&redirect_uri=http%3A%2F%2Fmusescriptum.com%2Fsocialauth.do&scope=publish_stream,email,user_birthday,user_location
	 * Stores configuration for the provider
	 * 
	 * @param providerConfig
	 *            It contains the configuration of application like consumer key
	 *            and consumer secret
	 * @throws Exception
	 */
	public OdnoklassnikiImpl(final OAuthConfig providerConfig) throws Exception {
		config = providerConfig;
		if (config.getCustomPermissions() != null) {
			scope = Permission.CUSTOM;
		}
		authenticationStrategy = new OAuth2(config, ENDPOINTS);
		authenticationStrategy.setPermission(scope);
		authenticationStrategy.setScope(getScope());
	}

	/**
	 * Stores access grant for the provider
	 * 
	 * @param accessGrant
	 *            It contains the access token and other information
	 * @throws Exception
	 */
	@Override
	public void setAccessGrant(final AccessGrant accessGrant) throws Exception {
		this.accessGrant = accessGrant;
		authenticationStrategy.setAccessGrant(accessGrant);
	}

	/**
	 * This is the most important action. It redirects the browser to an
	 * appropriate URL which will be used for authentication with the provider
	 * that has been set using setId()
	 * 
	 */
	@Override
	public String getLoginRedirectURL(final String successUrl) throws Exception {
		return authenticationStrategy.getLoginRedirectURL(successUrl);
	}

	/**
	 * Verifies the user when the external provider redirects back to our
	 * application.
	 * 
	 * @return Profile object containing the profile information
	 * @param httpReq
	 *            Request object the request is received from the provider
	 * @throws Exception
	 */

	@Override
	public Profile verifyResponse(final HttpServletRequest httpReq)
			throws Exception {
		Map<String, String> params = SocialAuthUtil
				.getRequestParametersMap(httpReq);
		return doVerifyResponse(params);
	}

	/**
	 * Verifies the user when the external provider redirects back to our
	 * application.
	 * 
	 * 
	 * @param requestParams
	 *            request parameters, received from the provider
	 * @return Profile object containing the profile information
	 * @throws Exception
	 */

	@Override
	public Profile verifyResponse(final Map<String, String> requestParams)
			throws Exception {
		return doVerifyResponse(requestParams);
	}

	private Profile doVerifyResponse(final Map<String, String> requestParams)
			throws Exception {
		LOG.info("Retrieving Access Token in verify response function");
		if (requestParams.get("error_reason") != null
				&& "user_denied".equals(requestParams.get("error_reason"))) {
			throw new UserDeniedPermissionException();
		}
		accessGrant = authenticationStrategy.verifyResponse(requestParams);

		if (accessGrant != null) {
			LOG.debug("Obtaining user profile");
			return authOdnoklassnikiLogin();
		} else {
			throw new SocialAuthException("Access token not found");
		}
	}

	private Profile authOdnoklassnikiLogin() throws Exception {
		String presp;

		try {
			Response response = authenticationStrategy.executeFeed(PROFILE_URL);
			presp = response.getResponseBodyAsString(Constants.ENCODING);
		} catch (Exception e) {
			throw new SocialAuthException("Error while getting profile from "
					+ PROFILE_URL, e);
		}
		try {
			LOG.debug("User Profile : " + presp);
			JSONObject resp = new JSONObject(presp);
			Profile p = new Profile();
			p.setValidatedId(resp.getString("uid"));
			p.setFirstName(resp.getString("first_name"));
			p.setLastName(resp.getString("last_name"));
			p.setEmail(resp.getString("email"));
			if (resp.has("location")) {
				p.setLocation(resp.getJSONObject("location").getString("name"));
			}
			if (resp.has("birthday")) {
				String bstr = resp.getString("birthday");
				String[] arr = bstr.split("/");
				BirthDate bd = new BirthDate();
				if (arr.length > 0) {
					bd.setMonth(Integer.parseInt(arr[0]));
				}
				if (arr.length > 1) {
					bd.setDay(Integer.parseInt(arr[1]));
				}
				if (arr.length > 2) {
					bd.setYear(Integer.parseInt(arr[2]));
				}
				p.setDob(bd);
			}
			if (resp.has("gender")) {
				p.setGender(resp.getString("gender"));
			}
			p.setProfileImageURL(String.format(PROFILE_IMAGE_URL,
					resp.getString("id")));
			String locale = resp.getString("locale");
			if (locale != null) {
				String a[] = locale.split("_");
				p.setLanguage(a[0]);
				p.setCountry(a[1]);
			}
			p.setProviderId(getProviderId());
			userProfile = p;
			return p;

		} catch (Exception ex) {
			throw new ServerDataException(
					"Failed to parse the user profile json : " + presp, ex);
		}
	}

	/**
	 * Updates the status on the chosen provider if available. This may not be
	 * implemented for all providers.
	 * 
	 * @param msg
	 *            Message to be shown as user's status
	 * @throws Exception
	 */

	@Override
	public void updateStatus(final String msg) throws Exception {
//		LOG.info("Updating status : " + msg);
//		if (msg == null || msg.trim().length() == 0) {
//			throw new ServerDataException("Status cannot be blank");
//		}
//		StringBuilder strb = new StringBuilder();
//		strb.append("message=").append(msg);
//		strb.append("&access_token").append("=").append(accessGrant.getKey());
//		Response serviceResponse;
//		try {
//			serviceResponse = authenticationStrategy.executeFeed(
//					UPDATE_STATUS_URL, MethodType.POST.toString(), null, null,
//					strb.toString());
//			if (serviceResponse.getStatus() != 200) {
//				throw new SocialAuthException(
//						"Status not updated. Return Status code :"
//								+ serviceResponse.getStatus());
//			}
//		} catch (Exception e) {
//			throw new SocialAuthException(e);
//		}

	}

	/**
	 * Gets the list of contacts of the user. this may not be available for all
	 * providers.
	 * 
	 * @return List of contact objects representing Contacts. Only name will be
	 *         available
	 */

	@Override
	public List<Contact> getContactList() throws Exception {
		List<Contact> plist = new ArrayList<Contact>();
//		LOG.info("Fetching contacts from " + CONTACTS_URL);
//		String respStr;
//		try {
//			Response response = authenticationStrategy
//					.executeFeed(CONTACTS_URL);
//			respStr = response.getResponseBodyAsString(Constants.ENCODING);
//		} catch (Exception e) {
//			throw new SocialAuthException("Error while getting contacts from "
//					+ CONTACTS_URL, e);
//		}
//		try {
//			LOG.debug("User Contacts list in json : " + respStr);
//			JSONObject resp = new JSONObject(respStr);
//			JSONArray data = resp.getJSONArray("data");
//			LOG.debug("Found contacts : " + data.length());
//			for (int i = 0; i < data.length(); i++) {
//				JSONObject obj = data.getJSONObject(i);
//				Contact p = new Contact();
//				String name = obj.getString("name");
//				if (name != null) {
//					String nameArr[] = name.split(" ");
//					if (nameArr.length > 1) {
//						p.setFirstName(nameArr[0]);
//						p.setLastName(nameArr[1]);
//					} else {
//						p.setFirstName(obj.getString("name"));
//					}
//					p.setDisplayName(name);
//				}
//				p.setId(obj.getString("id"));
//				p.setProfileUrl(PUBLIC_PROFILE_URL + obj.getString("id"));
//				plist.add(p);
//			}
//		} catch (Exception e) {
//			throw new ServerDataException(
//					"Failed to parse the user profile json : " + respStr, e);
//		}
		return plist;
	}

	/**
	 * Logout
	 */
	@Override
	public void logout() {
		accessGrant = null;
		authenticationStrategy.logout();
	}

	/**
	 * 
	 * @param p
	 *            Permission object which can be Permission.AUHTHENTICATE_ONLY,
	 *            Permission.ALL, Permission.DEFAULT
	 */
	@Override
	public void setPermission(final Permission p) {
		LOG.debug("Permission requested : " + p.toString());
		this.scope = p;
		authenticationStrategy.setPermission(this.scope);
		authenticationStrategy.setScope(getScope());
	}

	/**
	 * Makes HTTP request to a given URL.It attaches access token in URL.
	 * 
	 * @param url
	 *            URL to make HTTP request.
	 * @param methodType
	 *            Method type can be GET, POST or PUT
	 * @param params
	 *            Not using this parameter in Google API function
	 * @param headerParams
	 *            Parameters need to pass as Header Parameters
	 * @param body
	 *            Request Body
	 * @return Response object
	 * @throws Exception
	 */
	@Override
	public Response api(final String url, final String methodType,
			final Map<String, String> params,
			final Map<String, String> headerParams, final String body)
			throws Exception {
		LOG.info("Calling api function for url	:	" + url);
		Response response = null;
		try {
			response = authenticationStrategy.executeFeed(url, methodType,
					params, headerParams, body);
		} catch (Exception e) {
			throw new SocialAuthException(
					"Error while making request to URL : " + url, e);
		}
		return response;
	}

	/**
	 * Retrieves the user profile.
	 * 
	 * @return Profile object containing the profile information.
	 */
	@Override
	public Profile getUserProfile() throws Exception {
		if (userProfile == null && accessGrant != null) {
			authOdnoklassnikiLogin();
		}
		return userProfile;
	}

	@Override
	public AccessGrant getAccessGrant() {
		return accessGrant;
	}

	@Override
	public String getProviderId() {
		return config.getId();
	}

	private String getScope() {
		StringBuffer result = new StringBuffer();
		String arr[] = null;
		if (Permission.AUTHENTICATE_ONLY.equals(scope)) {
			arr = AuthPerms;
		} else if (Permission.CUSTOM.equals(scope)
				&& config.getCustomPermissions() != null) {
			arr = config.getCustomPermissions().split(",");
		} else {
			arr = AllPerms;
		}
		result.append(arr[0]);
		for (int i = 1; i < arr.length; i++) {
			result.append(",").append(arr[i]);
		}
		return result.toString();
	}
}
...
Рейтинг: 0 / 0
05.10.2012, 14:50:38
    #37985465
grasoff.net
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Нужен пример авторизации с сайта для одноклассников
мне кажется, что закомментированый код лучше вырезать перед тем как постишь в форумы
...
Рейтинг: 0 / 0
20.11.2012, 18:44:39
    #38045889
monokuroboo
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Нужен пример авторизации с сайта для одноклассников
В методе doVerifyResponse необходимо указать использование POSt запроса:
accessGrant = authenticationStrategy.verifyResponse(requestParams, MethodType.POST.toString());
...
Рейтинг: 0 / 0
Форумы / Java [игнор отключен] [закрыт для гостей] / Нужен пример авторизации с сайта для одноклассников / 3 сообщений из 3, страница 1 из 1
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]