I am working on login application.
For that, I am calling a backend service which is a post call. It returns a cookie. Inside cookie, there is a token. I need that token.
I am trying to get that token, but it is coming null when I try to access in using $cookie.get method.
Can anyone suggest me what could be the possible reason?
Here is the code:
$http({
url:"http://10.11.0.11:4440/j_security_check",
method:"POST",
data:data,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response) {
console.log("Login Success!!");
console.log( "cookie ", response.headers('Set-Cookie') ); //Returning NULL
console.log("cookies"+$cookies.get('JSESSIONID')); //Returning undefined
$location.url("/report");
}, function errorCallback() {
$scope.loginError = "Invalid username/password combination.";
$scope.result = 'error';
console.log('Login failed');
});
Here is the snap of response which I am getting in my browser's network tool:
Related
I have a REST API developed using Play Framework/Java and front end developed in Angular JS.
I am trying to call a POST method fron the Angular Client to the server using the following code:
$scope.login = function () {
console.log('login called');
var loginURL = 'http://localhost:9000/login';
var loginInfo = {
'email': $scope.email,
'password': $scope.password
};
$http({
url: loginURL,
method: 'POST',
data: loginInfo,
headers: { 'Content-Type': 'application/json' }
}).then(function (response) {
console.log('SUCCESS: ' + JSON.stringify(response));
$scope.greeting = response.status;
}, function (response) {
console.log('ERROR: ' + JSON.stringify(response));
});
}
This is the code at my server:
public Result doLogin() {
ObjectNode result = Json.newObject();
result.put("status", "success");
return ok(result).withHeader("Access-Control-Allow-Origin", "*");
}
And this is the application conf file:
#allow all hosts.
play.filter.hosts {
allowed = ["."]
}
#allow CORS requests.
play.filters.cors {
allowedOrigins = ["*"]
}
Yet even after enabling CORS, I am getting error in console in both Firefox and Google Chrome:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9000/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
ERROR: {"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://localhost:9000/login","data":{"email":"xxx","password":"xxx"},"headers":{"Content-Type":"application/json","Accept":"application/json, text/plain, /"}},"statusText":""}
I do know that the server is sending the correct response and the correct header because when I do the POST from Postman, I can see the response and also the headers containing {"Access-Control-Allow-Origin", "*"} in Postman.
So then, what could be the problem? Is there something I am missing from the Client side?
The difference between POSTMAN request and browser request is browser sends an OPTIONS request before the actual POST / GET request.
To be able to accept OPTION request with your play framework allowedHttpMethods = ["GET", "POST" ,"OPTIONS"]
for follow this link
Play Framework 2.3 - CORS Headers
This causes a problem accessing CORS request from a framework (like angularjs). It becomes difficult or the framework to find what was the options request for and take action properly.
For fixing your problem you will need to analyze how the options request going and how it's being interpreted and how to overcome. But in general, I suggest using "fetch" built-in request for this, which supports the promises so can be chained easily with angularjs code
so your code will look something like this
$scope.login = function () {
console.log('login called');
var loginURL = 'http://localhost:9000/login';
var loginInfo = {
'email': $scope.email,
'password': $scope.password
};
fetch(loginURL, {
method: 'post',
headers: {
"Content-type": "application/json"
},
body: loginInfo
}).then(function (response) {
console.log('SUCCESS: ' + JSON.stringify(response));
$scope.greeting = response.status;
}, function (response) {
console.log('ERROR: ' + JSON.stringify(response));
});
}
Although my backend is working correctly and I'm getting correct response from Postman crafted request
I can't see response in my angularJS controller. ( i execute this call inside controller to simplify situation )
$scope.click = function (auction_id) {
$http({
url: baseUrl + 'auctions/' + auction_id +'/followers',
headers: {
'Content-Type' : 'application/vnd.api+json'
},
method: 'POST'
})
.then(function(response) {
console.log(response);
})
.catch(function(response) {
return response;
});
};
I'm passing token with httpInterceptor which is working fine for the rest of my app.
URL is correct because I'm getting valid error number in console:
POST ##################/v1/auctions/172/followers
422 (Unprocessable Entity)
CategoryCtrl.js:64 undefined
64 line is that one console log in success .then(function....
Headers in (which I believe is) response headers from postman tab (third from Body in first screenshot)
Why response is undefined?
*Hashes in url code are mine.
From your REST API request, you're getting response with status 422, that means you've got a client error. Regarding your request, you have to handle a request when error will come. To handle error in asynchronous requests there is a second parameter of .then(mySuccessMethod(), myMethodOnError()) method.
More details about .then() and .catch() methods for promisses.
$scope.click = function (auction_id) {
$http({
url: baseUrl + 'auctions/' + auction_id +'/followers',
headers: {
'Content-Type' : 'application/vnd.api+json'
},
method: 'POST'
})
.then(function(response) {
console.log(response);
}, function(error) {
// Here goes your code to handle an error with status 4XX
console.log(error)
})
.catch(function(response) {
// Catch will come when you throw an error
return response;
});
};
When you made the request in Postman, you pass the token in the Auth attribute of the header in the request. In your code, you did not.
I am trying to implement Jsonwebtoken in my react native app. I followed the video tutorial on their official site and it worked fine. However, I kept getting errors "UnauthorizedError: No authorization token was found" every time I try to make api calls. The api calls all work as expected except I would still get errors like that. I tried the same api calls in postman, they don't give me errors. I found it's possibly because I didn't pass the token back after the api calls?
Here is where I initiate the express-jwt
var expressJWT = require('express-jwt')
app.use(expressJWT({secret: 'I like different tastes'}).unless({path:['/api/users/login', '/api/users/register', '/api/users/register/facebook']}))
Here is where I log in and create and pass back a jwt to my client side
login: function(req,res){
if (req.body.purpose == 'login'){
User.findOne({'localUser.email': req.body.email,}, function(err, user){
if (err){
console.log(err)
res.status(500).json('error')
}
else if(user == null){
res.status(404).json('not found');
}
else{
if (passwordHash.compareSync(req.body.password, user.localUser.password)){
var myToken = jwt.sign({username: user.localUser.name}, 'I like different tastes')
var tmpUser = user.toJSON()
tmpUser.token = myToken
res.status(200).json(tmpUser);
}
else{
res.status(401).json('wrong credentials')
}
}
})
}
else{
res.status(400).json('You are hacked bro')
}
And this is an example of the api calls I make after I log in.
fetchPost() {
var _this = this
return fetch(uri.network.uri + '/api/posts/fetch', {
method: 'POST',
headers: {
'Authorization': 'Bearer '+this.props.activeUser.token,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
purpose: 'fetchPost',
latitude: this.state.currentRegion.latitude,
longitude: this.state.currentRegion.longitude,
maxSearch: MAX_SEARCH
})
})
.then((response) => {
if (response.status != 200){
Alert.alert(
'Sorry',
'Unexpected errors!'
);
return
}
else{
return response.json();
}
})
.then((responseJson)=>{
console.log(responseJson)
})
.catch((error) => {
console.error(error);
});
}
this.props.activeUser.token is the token I passed back from the second function in server side
it worked fine and I get the data I want. I also believe I was passing the right token since I tried passing a random token which resulted in incorrect response.
The problem is that I would get UnauthorizedError: No authorization token was found.
This is really weird. I am using AngularJS in my app. During login, I make an HTTP POST request ; data is sent properly and I receive the right response. Then I logout - which returns me back to the login page - and I do the same http req but the data is not sent by the post request. Upon console.log I see that the $scope data is correct - just the POST data is not being sent.
If I do a hard refresh of the login page it works again. So my problem is that consecutive requests are not being made without refreshes. Here is my login function -
$scope.login = function() {
var request = $http({
method: "POST",
url: URL + "login",
crossDomain: true,
data: this.loginData
});
request.success(function(data) {
var response = angular.fromJson(data);
if(!response["error"]) {
sessionStorage.email = response["email"];
sessionStorage.password = response["password"];
sessionStorage.userId = response["id"];
$location.path('/dashboard');
} else {
$scope.responseMessage = response["message"][0];
}
});
request.error(function(data) {
console.log(data);
});
}
And this is my logout function -
$scope.logout = function() {
sessionStorage.clear();
$location.path("/login");
}
Found the answer and posting it here in case anyone runs into a similar problem.
Setting a header for content type works:
var request = $http({
method: "POST",
url: URL + "login",
crossDomain: true,
headers: {
"content-type": "application/json"
},
data: this.loginData
});
I am new to angularjs am tying to learn it but some problems faced me, actually they are two problems:
First Problem: $http.post never works as there is no action and there is no response. However, $http.get is able to work.
Second Problem: Because of the first problem I call my restful webservice by $http.get, but the web service response status always is -1. Though the web service is able to do its work successfully and always response data null, can any one help me.
this my angular part:
var app = angular.module('myLogin',[]);
app.controller('loginController',function($scope,$http){
$scope.login=function(){
var username = $scope.username;
var password = $scope.pass;
$http.get("http://localhost:8080/spring/webservice/login/"+username+"/"+password)
.success(function(data,status){
alert("data : "+data);
alert("Data Inserted Successfully");
window.location.href = "chatScreen.html";
})
.error(function(data,status){
alert("Status: "+status);
window.location.href = "login.html";
});
}
});
and this my web service:
/**
* web service part
*/
#RequestMapping(value="webservice/login/{name}/{pass}", method=RequestMethod.GET)
#ResponseStatus(value = HttpStatus.OK)
public ResponseEntity<String> weblogin(#PathVariable("name") String name, #PathVariable("pass") String pass)
{
System.out.print("username : "+name);
System.out.print(pass);
UserService service = new UserService();
List<UserBean> users = service.getUsers();
if(users!=null)
{
for(UserBean user : users)
if( ( user.getUsername().equals(name) ) && ( user.getPassword().equals(pass) ) )
{
System.out.print("success");
username = name;
//model.addAttribute("result", "Welcome to chat..");
MessageService messageService = new MessageService();
List<MessageBean> messages = messageService.getMessage(username);
String userMessages="";
if(messages != null)
{
for(MessageBean msg : messages)
userMessages +="\n"+msg.getSender() + ": " + msg.getMessage()+" \n";
}
else
userMessages +="You have no Messages !";
//model.addAttribute("whoSendToMe", userMessages);
return new ResponseEntity(HttpStatus.OK);
}
}
return new ResponseEntity<String>("faild", HttpStatus.NOT_FOUND);
}
refer this may be this will give you idea how to approach your problem:-
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this is asynchronous call back
// you will get your data here comming from rest
}, function errorCallback(response) {
// called asynchronously if an error occurs
});
share your code so we will try to solve it
If you use method GET and you receive a -1 returned, it means normally that you are giving a wrong URL.
As for then POST method you should use this syntax:
return $http({
method: 'POST',
url: 'index.php/email/createDeliverable',
data: $.param({
csrfTokenName: --your token--,
userName: user.name,
password: password
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
Remember to add the headers part.
Your server may need a CSRF token validation, in this case you need to pass it, see un my example: csrfTokenName: --your token--,