Angular with wordpress jwt auth - angularjs

I'm trying to make wordpress as a backend to my angularjs app, so I'm using the plugin rest-api with the jwt-auth
so when trying to login I get the following error
XMLHttpRequest cannot load http://localhost/back/wp-json/jwt-auth/v1/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://imider.ma' is therefore not allowed access. The response had HTTP status code 500.
I know i have to add CROS access, but I'm not familiar with wordpress, so any help?

https://docs.google.com/document/d/17zgUHZrvL5KVG2yKQE8NWgxNZn6V08xr65DBox5WVZ0/edit?usp=sharing
here is my tutorial of how to access the api
then you can use this to get the token
$http({
method:'post',
url:'',
data: {
username: '',
password: ''
}
}).then(function(results){
console.log(results);
})
then you can use this
$http({
method:'get',
url:'',
headers: { 'Authorization': 'Bearer <myTokenId>' }
}).then(function(results){
console.log(results);
})

I created a video detailing the process of installing and setting up the plugin. If you follow the steps I outlined there you should be good.
https://youtu.be/Mp7T7x1oxDk
The idea is that you also need to modify .htaccess and wp-config.php to make the plugin work with the existing API endpoints as well.
Just by installing the plugin and adding a SECRET_KEY, used to sign the token will make the JWT setup work but it will not allow you to use the tokens generated through that API with the existing REST API endpoints.

Related

CORS error on Axios PUT request from React to Spring API

I am working on an update functionality using PUT. I have a React front end and Spring back-end API. Here is the following PUT request made from front-end:
updateStuff(username, id, stuff){
return Axios.put(`http://localhost:8080/stuff/${username}`, {stuff})
}
Controller to handle this request:
#RestController
#CrossOrigin(origins="http://localhost:3000")
public class StuffController {
#Autowired
private StuffService stuffService;
#PutMapping(path="/stuff/{username}/{id}")
public ResponseEntity<Stuff> updateStuff(#PathVariable String username,
#PathVariable long id,
#RequestBody Stuff stuff) {
Stuff response = stuffService.save(stuff);
return new ResponseEntity<Stuff>(stuff, HttpStatus.OK);
}
I am able to use the same service for GET and DELETE. I am also able to send request using REST client. But when I am trying using browser I am getting this error in console:
Access to XMLHttpRequest at 'http://localhost:8080/stuff/abc' from origin
'http://localhost:3000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No 'Access-
Control-Allow-Origin' header is present on the requested resource.
PUT http://localhost:8080/stuff/abc net::ERR_FAILED
Not able to figure out why its just happening for PUT request? How to resolve this? Appreciate your help and time!
EDIT:
Updated the front-end to:
updateStuff(username, id, stuff){
return Axios.put(`http://localhost:8080/stuff/${username}`, {
headers:{
'Access-Control-Allow-Origin':'*',
'Content-Type': 'application/json;charset=UTF-8',
}
})
}
Still its throwing the same error. So far Spring Security is not configured. I am just checking a simple update flow without any authentication or authorization.
EDIT 2: Request headers in browser has Access-Control-Allow-Origin: *:
I ran into a similar issue a while ago. Check if the variables of your model class in the backend have the same name as in your frontend. That fixed it for me.
The best way to deal with this cors policy is to add a proxy field in the pakage.json file.enter image description here
In reactjs application you can use your spring boot api's URL as proxy to avoid CORS issue.
package.
package.json
{
"proxy": "http://localhost:8080/",
"dependencies": {
.
.
.
}
}
axios
Axios.put(stuff/${username}, {stuff})

calling Https url on Http get request angularjs

I have a Https url and want to send request to get data from that URL , scenario 1:
from my browser If I hit the Url i get the response whereas from my Angularjs App I get always an error 401 , but if I hit the Api from browser I always get the correct response
for security reasons I couldn't use Url here but what I want is to:
$http({
method: "GET",
url: "https://urlAdresss/",
headers: {
"Accept-Language": "en-US, en;q=0.8",
"Content-Type": "application/json;charset=UTF-8"
},
}).then(function (_response) {
console.log(_response
}
I always get unauthorized I am network as well as On console any help will be greatly appreciated ,
but If I hit the same Url from browser I get the response It means the backend is working fine
I think I am missing something in my get request that's why getting the error
It seems a CORS (Cross-Origin Resource Sharing) issue.
In AngularJS side, you should use the following configuration in order for $http service to automatically send authorization headers to http requests.
var app = angular.module('app', [])
.config(function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
});
And in backend you should specify explicitly allowed origins (eg. http://localhost:8888).
Also, note some points from here.
If you want to allow credentials then your Access-Control-Allow-Origin must not use *.

ASP MVC Web api with Angular2 - Http header Access-Control

I have rest application with Angular2 and ASP MVC rest server and I have a problem with communication.
When I send get, I get this error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
When I added Access-Control-Allow-Origin to request, I get this error:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404.
Here is my code:
let headers = new Headers({ 'Access-Control-Allow-Origin': '*' })
this.http.get("http://localhost/App/Users", { withCredentials: true, headers: headers })
.subscribe(response => {
console.log("A");
}, error => {
console.log(error);
});
In web.config is enabled Windows authentication.
Where is problem?
The problem seems here is of CORS. Your angular and WebAPI are using different ports as you're using localhost. (Seems like they are two different projects).
To solve this you can install the nuget package using "Install-Package Microsoft.AspNet.WebApi.Cors" and then in your WebApiConfig file you can simply say "config.EnableCors()". Now the API which you're exposing to the angular part, has to be told that the CORS is supposed to be used there. So you can put the attribute over your controller mentioning the origin, headers and methods. It should work fine after that.
For more reference, you can check this link,
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
On server side when you enabled cors add:
corsAttr.SupportsCredentials = true;
Like this on MVC .net on Application_Start
var corsAttr = new EnableCorsAttribute("http://localhost:4200,http://domain1,http://domain2", "*", "*");
// Enable withCredentials
corsAttr.SupportsCredentials = true;
config.EnableCors(corsAttr);

AngularJs No 'Access-Control-Allow-Origin'

I'm trying to make a request with Angular like this:
(function () {
'use strict';
angular.module('app')
.service('requestService',requestService);
function requestService($http) {
this.post = function(url, data) {
return $http({
'method': 'POST',
'url': url,
'data': $.param(
data
)
});
}
}
})();
I receive the error in my console:
XMLHttpRequest cannot load http://lsupport.dev/api/v1/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
My http://localhost:3000 is build with Gulp. I've already searched a lot on the web, but I cannot find a solution.
You need to enable CORS on the server (remote) to permit the code to execute requests with a different domain.
CORS-Wikipedia
You must need access of the server in which your making the request OR owner of the server need to enable it.
Please check the following post in more details.
Header set Access-Control-Allow-Origin in .htaccess doesn't work
Access-Control-Allow-Origin Multiple Origin Domains?
Homestead is Nginx server Please follow the steps. To solve it.
Handling CORS with Nginx
Access Control Origin nothing to do with AngularJS, It server end issue to respond to the specific request there is different configuration based on your server type like Apache, Nginx.

Ajax authentication using CURL request: Ionic app, Django, Rest, Oauth2

I am successfully using a curl request to authenticate a user on my Django project with Django-social-auth using a Facebook token to return a token for my personal site. Quite simply, I have a Facebook token and I am converting it to a Django token in return, but I am only accomplishing this feat using a CURL request. The framework I am using comes from Philip Garnero (1).
The CURL request - curl -X POST -d "grant_type=convert_token&client_id=&client_secret=&backend=facebook&token=" http://localhost:8000/auth/convert-token
The confusion comes when I am trying to do this using an AJAX request.
Is there something wrong with the way my ajax is setup? Do I need to get a csrf token to begin with before I can convert my facebook token to a authenticated Django token?
Update: I am getting a 400 error unsupported_grant_type while running my ajax request through a proxy. The request is the same request I have successfully executing in both a curl command and a Postman command.
Ajax Request:
$http({
url: "proxy/url/...",
async: false,
crossDomain: true,
method: "POST",
data: {
"client_id": "...",
"client_secret": "...",
"grant_type": "password",
"username": "...",
"password": "..."
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status, headers, config) {
console.log("error status = " + status);
console.log(angular.toJson(data));
});
(1) - https://github.com/PhilipGarnero/django-rest-framework-social-oauth2
I figured out the issue, but I cant point to the specific thing I did in order to get it working. I will instead write down everything I did in order to get a working system. My particular example was for an ionic app that used facebook authentication and converted the token to a django csrf token which I used to track users.
My setup: Django, Django rest-framework Social Oauth2 (Philip Garnero's setup), Django social auth, angular js, cordova facebook plugin, ionic (3rd party app that acts as the frontend) and finally a configured proxy service.
Steps: Number one, make sure to have a rest api system installed. I used Philip Garnero's api (1). Once I got the installable package from Garnero in place I had to configure an ionic proxy service. I used Ionic's tutorial to get it in place (2). That document is worth reading to understand the gist of cross domain requests. Finally, what I couldn't find without testing and researching around were the correct headers to attach to the ajax request. I ended up solving it using a very useful tool called Postman.
Here is a dumb example of that "confusingly difficult" request:
$http.post(Url, queryStringData,
{headers: {
'Accept': '*/*',
"cache-control": "no-cache",
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data, status, headers, config) {
console.log(data.access_token);
}).error(function(data, status, headers, config) {
console.log("error status = " + status);
console.log(angular.toJson(data));
});
Please comment if you have questions. I will do my best to clean up the original post and may consider a tutorial if others are having the same issues. I spent 5 hours trying to crack this one.
(1)- https://github.com/PhilipGarnero/django-rest-framework-social-oauth2
(2)- http://blog.ionic.io/handling-cors-issues-in-ionic/

Resources