Magento OAuth客户登录
本文关键字:登录 客户 OAuth Magento | 更新日期: 2023-09-27 18:21:45
为了客户移动登录,我正试图通过Magento的OAuth系统进行身份验证-php有很多例子,但我只能找到C#的部分。如果可能的话,我希望避免使用浏览器,并以编程方式执行登录。
REST API的身份验证和使用包含在PCL库中-与.NET 4.5、Xamarin.IOS、Xamaring.Android和Windows Phone Silverlight兼容。因此,我不得不使用诸如RestSharp.portable.之类的可移植库
迄今为止的进展:
到目前为止,我已经能够检索到未经授权的代币;oauth_token和oauth_taken_secret,但我无法完成接下来的两个步骤/oauth/authenticate和/oauth/token。Magento官方指南(http://www.magentocommerce.com/api/rest/authentication/oauth_authentication.html)建议下一步操作是访问/oauth/authorize,允许用户登录,然后从回调url中恢复两个url参数。然而,当我在浏览器中尝试此操作时,它只是将我重定向到/index.php/customer/account/login/-我希望它重定向到我的回调url(localhost),这样我就可以通过使用位置cookie检测重定向,然后以这种方式检索令牌。
有人能就如何完成授权提出建议吗?
身份验证过程:
var magento = new MagentoHelper();
await magento.OAuthInitiate();
await magento.OAuthAuthorize();
await magento.OAuthToken();
Magento操作:
public class MagentoHelper
{
public readonly string ServiceUrl = ""; // e.g. http://127.0.0.1
public readonly string MagentoService = ""; // e.g. /magento
public readonly string ConsumerKey = "";
public readonly string ConsumerSecret = "";
public readonly string CustomerUsername = "";
public readonly string CustomerPassword = "";
private RestClient _client;
private MagentoTools _magentoTools;
private string _oauthToken;
private string _oauthTokenSecret;
public MagentoHelper()
{
_client = new RestClient(ServiceUrl);
_magentoTools = new MagentoTools();
}
/// <summary>
/// Retrieve unauthorized tokens from OAuth service
/// </summary>
public async Task OAuthInitiate()
{
var request = new RestRequest(MagentoService + "/oauth/initiate", HttpMethod.Post);
string nonce = _magentoTools.GetNonce();
string timestamp = _magentoTools.GetTimestamp();
var parameters = new Dictionary<string, string>();
parameters.Add("oauth_callback", "http://localhost:8888");
parameters.Add("oauth_consumer_key", ConsumerKey);
parameters.Add("oauth_nonce", nonce);
parameters.Add("oauth_signature_method", "HMAC-SHA1");
parameters.Add("oauth_timestamp", timestamp);
parameters.Add("oauth_version", "1.0");
var postUrl = new Uri(ServiceUrl + MagentoService + "/oauth/initiate");
var signature = OAuth1.GetSignature("POST", postUrl, parameters, ConsumerSecret, "").ToString();
parameters.Add("oauth_signature", OAuth1.EncodeString(signature));
string authHeader = _magentoTools.GetAuthorizationHeader(parameters.ToList());
request.Parameters.Add(new Parameter() { Type = ParameterType.HttpHeader, Name = "Authorization", Value = authHeader });
try
{
var response = await _client.Execute(request);
string data = Encoding.UTF8.GetString(response.RawBytes, 0, response.RawBytes.Length);
var queryParameters = _magentoTools.FillFromString(data, true);
_oauthToken = queryParameters["oauth_token"];
_oauthTokenSecret = queryParameters["oauth_token_secret"];
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Navigate to OAuth login page, extract form post URL and submit user credentials.
/// Upon redirection, store the redirection url in preparation for extraction of the new tokens.
/// </summary>
public async Task OAuthAuthorize()
{
var webClient = new HttpClient();
var loginUrl = new Uri(_client.BaseUrl.ToString() + MagentoService.Trim('/') + "/oauth/authorize" + "?oauth_token=" + _oauthToken).ToString();
// Get the login page and find the form post action url and the formkey
var loginPage = new HtmlDocument();
using (var responseStream = await webClient.GetStreamAsync(loginUrl))
{
loginPage.Load(responseStream);
}
var loginForm = loginPage.GetElementbyId("login-form");
var postUrl = loginForm.GetAttributeValue("action", string.Empty);
// Post the user credentials to the post action url
var postRequest = (HttpWebRequest)WebRequest.Create(postUrl);
postRequest.Method = "POST";
postRequest.ContentType = "application/x-www-form-urlencoded";
postRequest.CookieContainer = new CookieContainer();
var postData = String.Format("login%5busername%5d={0}&login%5bpassword%5d={1}&oauth_token={2}", CustomerUsername, CustomerPassword, _oauthToken);
byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
using (var requestStream = await postRequest.GetRequestStreamAsync())
{
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
}
using (var response = await postRequest.GetResponseAsync())
{
if (response.Headers["location"] == null) throw new Exception("location is null");
}
}
public async Task OAuthToken()
{
await Task.Yield();
}
}
我已经为Magento REST API创建了一个C#客户端。它不是PCL,但应该可以工作。它使用RestSharp。代码位于https://github.com/nickvane/Magento-RestApi
该客户端用于与Magento进行后端集成,无需用户交互。登录过程实际上会进行一些屏幕抓取。有关身份验证过程的详细说明,请参阅https://github.com/nickvane/Magento-RestApi/wiki/Authentication-steps
如果库不能直接编译到PCL,那么您肯定可以复制大量代码。任何修复都欢迎作为拉取请求。
使用OAuth1,您无法绕过登录。用户必须明确登录并为您(客户端)提供对其资源的访问权限。因此,无论万磁王与否,您都无法绕过登录。
OAuth2中有一些方法不能让用户登录(ClientCredentials Grant Pattern),但这些方法保留给高度信任的客户端,我确信Magneto不支持
已编辑它是这样工作的:
- 您的应用程序(客户端)将请求未经授权的令牌以及重定向url
http://myapp.com/RedirectHere
- 您的应用程序调用/authorize URL,在这种情况下,授权服务器(Magneto)将为用户提供一个登录页面,用户登录后,Magneto将使用oauth_verifier在重定向URL上将其重定向回您的服务器。类似
http://myapp.com/RedirectHere?oauth_verifier=90J98DJ89FQ30F9KQE0R
- 然后,您的应用程序将调用/oauth/token,并提供以下所有详细信息,服务器将使用oauth令牌进行响应。
- oauth_consumer_key
- oauth_nonce
- oauth_签名_方法
- oauth_签名
- oauth_timestamp
- oauth_token
- oauth_verifier
- oauth_version
希望这能有所帮助。