I was playing around with the WordPress Rest API, and I was downloading this plugin called WP OAuth Server (by Justin Greer), and I have built my own OAuth connection.
I have one problem: I get Error 400, and it says: The grant type was not specified in the request.
Here is my code so far:
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="assets/css/app.css" type="text/css">
</head>
<body>
<div id="result"></div>
<!--<script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=places"></script>-->
<script type="text/javascript" src="assets/js/app.js"></script>
</body>
</html>
JavaScript:
/**
* OAUTH 2 LOGIN
*/
+function () {
var $CLIENT_CODE = 'fc8uhbwlo4niqhngrjsdl3tbp3cndpidfs61w77g';
var $CLIENT_ID = 'llsfdwZzO7qVHBzM4nhfcq1jFW2L8O';
var $CLIENT_SECRET = 'auaCKn8JWXQmSyYrl3PDi23klIhotp';
var $AUTHORIZATION_ENDPOINT = 'http://domain.dev/oauth/authorize';
var $TOKEN_ENDPOINT = 'http://domain.dev/oauth/token';
$.ajax({
url: $AUTHORIZATION_ENDPOINT + '?client_id=' + $CLIENT_ID + '&client_secret=' + $CLIENT_SECRET + '&response_type=code',
}).done(function (url) {
$('#result').html(url);
fetchSomething();
}).fail(function (errorThrown) {
console.log("Error" > errorThrown.responseText);
})
function fetchSomething() {
$.ajax({
type: 'POST',
url: $TOKEN_ENDPOINT + '?grant_type=authorization_code&code=' + $CLIENT_CODE,
}).done(function (success) {
console.log(success);
}).fail(function (error) {
console.log(error);
});
}
}();
CodePen
This was my solution
$.ajax({
url: 'http://' + domain + '?oauth=token',
type: 'POST',
data: {
grant_type: grantType,
code: code,
client_id: clientID,
client_secret: clientSecret,
redirect_uri: redirect
}
}).done(function (token) {
console.log(token);
}).fail(function (fail) {
console.log(fail.responseJSON.error);
});
Related
Google OAuth Popup continues without switching back to Return URL after successful External Login in Web Application asp.net 4.5
The code:
javascript for click event:
<script type = "text/javascript">
#google-signin-button{
document.getElementById("google-signin-button").addEventListener("click", getAccessToken);
}
html code for Google OAuth Button:
<script src="https://accounts.google.com/gsi/client" async defer></script>
<div id="g_id_onload"
data-client_id="MyClientid"
data-context="signin"
data-ux_mode="popup"
data-login_uri="https://localhost:XXXXX/login.aspx"
data-auto_select="true"
data-itp_support="true">
</div>
<div class="g_id_signin" id="google-signin-button"
<script src="https://gridnow.net/GoogleAuthentication.js" defer></script>
data-type="standard"
data-shape="rectangular"
data-theme="outline"
data-text="signin_with"
data-size="large"
data-logo_alignment="left">
</div>
Expected the control to return ReturnUrl from popup
GoogleAuthentication.js code is as follows:
function getAccessToken() {
if (location.hash) {
if (location.hash.split('access_token=')) {
var accessToken = location.hash.split('access_token=')[1].split('&')[0];
if (accessToken) {
isUserRegistered(accessToken);
}
}
}
}
function isUserRegistered(accessToken) {
$.ajax({
url: '/api/Account/UserInfo',
method: 'GET',
headers: {
'content-type': 'application/JSON',
'Authorization' : 'Bearer ' + accessToken
},
success: function (response) {
if (response.HasRegistered) {
localStorage.setItem('accessToken', accessToken);
localStorage.setItem('userName', response.Email);
window.location.href = "Data.html";
}
else {
signupExternalUser(accessToken);
}
}
});
}
function signupExternalUser(accessToken) {
$.ajax({
url: '/api/Account/RegisterExternal',
method: 'POST',
headers: {
'content-type': 'application/json',
'Authorization': 'Bearer ' + accessToken
},
success: function () {
window.location.href =
"/api/Account/ExternalLoginprovider=Google&response_type=token&client_id=self&redirect_uri=http%3a%2f%2flocalhost%3a61358%2fLogin.aspx&state=GerGr5JlYx4t_KpsK57GFSxVueteyBunu02xJTak5m01";
}
});
}
I have created small webpage, I want to create post using WordPress rest api, but I send data but this error displayed How do I pass data could you please check and update.
post.html:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
var ourPostData = {
"title" : "siva",
"content" : "Hi this welcome",
"status": "publish",
'excerpt': 'Read this awesome post',
'password': 'siva',
'slug':'new-test-post'
};
alert(JSON.stringify(ourPostData))
$.ajax({
type:"POST",
url:"http://127.0.0.1/wordpress/wp-json/wp/v2/posts",
data:JSON.stringify(ourPostData),
dataType:"json",
username: "siva",
password: "siva",
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
},
contentType:"Application/json",
success:function(callback){
console.log(callback)
}
});
});
</script>
</head>
<body>
</body>
</html>
Error
jquery-1.7.js:8157 OPTIONS http://localhost:8080/DigitalWallet/subscriber/add/ 403
send # jquery-1.7.js:8157
ajax # jquery-1.7.js:7635
(anonymous) # CallTest.js:9
dispatch # jquery-1.7.js:3319
eventHandle # jquery-1.7.js:2925
index.html:1 Failed to load http://localhost:8080/DigitalWallet/subscriber/add/: Response for preflight does not have HTTP ok status.
My Client code is follow
$(document).ready(function() {
$('#butCallAjax').click(function() {
jQuery.support.cors = true;
alert("awa");
var data0 = {
number: '0719402280',
agent_number: '0719402243',
agent_pin: '1234'
};
var json = JSON.stringify(data0);
$.ajax({
type: "POST",
dataType: "text",
data: json,
contentType: "application/json; charset=utf-8",
url: "http://localhost:8080/DigitalWallet/subscriber/add/",
success: function(data) {
alert(data);
},
error: function(msg, url, line) {
alert('error trapped in error: function(msg, url, line)');
alert('msg = ' + msg + ', url = ' + url + ', line = ' + line);
}
});
});
});
And this is my User HTML part
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="http://code.jquery.com/jquery-1.7.js" type="text/javascript"></script>
<script src="js/custom/CallTest.js" type="text/javascript"></script>
</head>
<body>
<button id="butCallAjax">Get data</button>
<select id="cboFastBikes" name="cboFastBikes"></select>
</body>
</html>
This is my service
#RequestMapping(value = "/agent/add/", method = RequestMethod.POST)
public String addAgent(#RequestBody Agent agent) throws Exception {
Log4JUtil.logger.info("Agent,agent_save_request,Request=" + agent.toString()+"|"+agent.getName()+"|"+agent.getNumber());
String Text = "";
try {
agentValidation.fieldValidation(agent);
String number = agent.getNumber();
try {
Agent dbagent = agentService.findByNumber(number);
if (dbagent != null) {
throw new AgentAlreadyExistsException();
} else {
agentService.saveOrUpdate(agent);
agentService.createWallet(number);
Text = "0|Created|Active|Agnt";
}
} catch (Exception exp) {
throw exp;
}
} catch (Exception ex) {
Log4JUtil.logger.info("Agent,agent_save_request,Request=" + agent.toString() + "," + ex.toString());
throw ex;
}
return Text;
}
This service is working fine. I used postman to check the service. Please help me to figure out this problem
Salaamun Alekum
My AJAX Call Is Not Calling The Controller Action In ASP.NET MVC Web Applicaiton Project
Bellow Is My AJAX Call In Javascript And Next Is Controller's Action
AJAX Call
var requestUrl = '/Home/GetCurrentUser';
$.ajax({
url: requestUrl,
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data)
{
debugger;
alert(data);
},
error: function (xhr, status, error)
{
debugger;
alert(error);
}
The Controller Action
[SharePointContextFilter]
public JsonResult GetCurrentUser()
{
CurrentUserModel um = new CurrentUserModel();
try
{
Microsoft.SharePoint.Client.User spUser = null;
var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
if (clientContext != null)
{
spUser = clientContext.Web.CurrentUser;
clientContext.Load(spUser, user => user.Title, user => user.Email, user => user.LoginName);
clientContext.ExecuteQuery();
um.Name = spUser.Title;
um.Email = spUser.Email;
um.LoginName = spUser.LoginName;
}
}
SharePointBoxOnline.Common.User u = UserManager.Instance.GetUserByEmail(um.Email);
if (u != null)
{
um.ClientId = u.FK_Client_ID;
um.UserId = u.User_ID;
}
}
catch (Exception e)
{
SharePointBoxOnlineAppWeb.Classes.LogsManager.LogException(e.Message, e.StackTrace, System.Web.HttpContext.Current.Request.Url.ToString(), "Added logging functionality to store the exception information in the Database", DateTime.Now);
}
return Json(um, JsonRequestBehavior.AllowGet);
}
Errors Results In AJAX Are
error.description
Invalid character
status
parsererror
xhr.responseText
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Error</title>
<link href="/Content/css?v=MDbdFKJHBa_ctS5x4He1bMV0_RjRq8jpcIAvPpKiN6U1" rel="stylesheet"/>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h2>An unexpected error has occurred.</h2>
<p>Please try again by launching the app installed on your site.</p>
</div>
</div>
<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
{"appName":"Internet Explorer","requestId":"673b269bf2c74e39a9496d69f3e0b62e"}
</script>
<script type="text/javascript" src="http://localhost:14069/4b2e31c8e2cf413facce9558ed0cb3ff/browserLink" async="async"></script>
<!-- End Browser Link -->
</body>
</html>
Thank You Stackoverflow And Members Of Stackoverflow Please Let Me Know If You Require Further Details
Thank You
$.ajax({
url: requestUrl,
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data)
{
debugger;
alert(data);
},
error: function (xhr, status, error)
{
debugger;
alert(error);
}
});
I am able to POST the message to the yammer, but the messages are getting posted to the default network and I need to post in a different network.
Here is my current test code:
<html>
<head>
<title>A Yammer App</title>
<script src="https://assets.yammer.com/platform/yam.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
yam.config({appId: "######"});
</script>
</head>
<body>
<button onclick='post()'>Yammer Update!</button>
<script>
function post() {
yam.getLoginStatus( function(response) {
if (response.authResponse) {
postdata();
} else {
yam.login( postdata);
}
});
}
function postdata()
{
yam.request(
{ url: "https://www.yammer.com/api/v1/messages.json"
, method: "POST"
, data: { "body" : "Message Throug app","group_id":"3156478"}
, success: function (msg) { alert("Post was Successful!: " + msg); }
, error: function (msg) { alert("Post was Unsuccessful..." + msg); }
}
);
}
</script>
</body>
</html>
Add the below function in your yam.request before sending it .
beforeSend: function (req) {
//send the access_token in the HTTP header
req.headers.Authorization = "Bearer #########SSA";
}
The bearer will the autorization token for that network you are targetting.