400 Bad Request error on Delete - angularjs

Me and my m8s are developing a manuscript handling system for our university using Spring MVC,angularJS etc. We have some issues with deleting a user from the database.
We get always HTTP Status 400 - Required String parameter 'userName' is not present
type Status report
message Required String parameter 'userName' is not present
description The request sent by the client was syntactically incorrect.
Controller:
#Secured({ "ROLE_ADMIN" })
#RequestMapping(value = "/delete/{userName}", method = RequestMethod.DELETE)
public void deleteUser(#RequestParam String userName) {
LOGGER.info("Deleted user: " + userName);
userManagerService.deleteUser(userName);
}
Method of the ManuscriptAdminService.js:
function deleteUser(userName){
$log.info("Delete selected user "+new Date());
$http.delete('delete/'+userName).then(function(data){
console.log(data);
},function(error){
$log.error("Error occured while admin tried to delete user "+new Date());
});
}
Method of the ManuscriptAdminController.js
vm.showModalUserDelete = function(index) {
$log.info("Show user delete modal "+new Date());
var modelInstance = $modal
.open({
animation : true,
templateUrl : 'htmlcontent/content/admin/modal/userDeleteManageModal.html',
controller : 'ManuscriptAdminModalinstacneController',
controllerAs : 'ManuscriptAdminModalinstacneController',
size : 300,
resolve : {
items : function() {
return ManuscriptAdminService.getUserName(index);
}
}
});
modelInstance.result.then(function (result) {
ManuscriptAdminService.deleteUser(result);
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};

You're using a URI template variable in /delete/{userName}, so you will need to use #PathVariable annotation on your parameter:
#Secured({ "ROLE_ADMIN" })
#RequestMapping(value = "/delete/{userName}", method = RequestMethod.DELETE)
public void deleteUser(#PathVariable String userName) {
LOGGER.info("Deleted user: " + userName);
userManagerService.deleteUser(userName);
}

Related

I send http post request with angular but it does not go to the asp.net mvc action and returns html layout tags

I am doing an angular application with asp.net mvc and i made a registration form with identity, I have layout and index mvc view which i just write in it ng-view tag and i inject html pages in it, I am doing a http post request from angular controller to mvc action method but the request does not go to the mvc action, whereas when i change th views to mvc views and make a templateUrl in angular map to mvc method it works well.
Can any one help me in this problem.
[HttpPost]
[AllowAnonymous]
public async Task<JsonResult> Register(RegisterViewModel model)
{
string message = "";
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
FirstName = model.FirstName,
MiddleName = model.MiddleName,
LastName = model.LastName,
UserName = model.Email,
Email = model.Email,
UserStatus = UserStatus.Waiting
};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
message = "Success";
}
else
{
AddErrors(result);
message = "InvalidEmail";
}
}
else
{
message = "Failed!";
}
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
and this is my angular controller
MyApp.controller('RegisterController', ['$scope','$http',function ($scope, $http) {
$scope.message = '';
$scope.isFormValid = false;
//Check Form Validation
$scope.$watch('f1.$valid', function (newValue) {
$scope.isFormValid = newValue;
});
//Save Data
$scope.SaveData = function (data) {
$scope.submitted = true;
$scope.message = '';
if ($scope.isFormValid) {
$http({
method: 'POST',
url: '/Account/Register',
data: data
}).then(function (response) {
// check your response (if a success status code was resolved)
console.log(response.data);
}, function (error) {
// check your error response
console.log(error);
});
} else {
$scope.message = "Please Fill the blanks";
}
}
}]);
and this is my html page:
<div ng-controller="RegisterController">
<form name="f1" ng-submit="SaveData(user)" novalidate>
controls here
</form
1) Check your browser console for any javascript errors, if you have any, resolve them and try again!
2) Check you have the correct ActionMethodSelectorAttribute attribute ([HttpPost]) over your controller method and that your method name is spelt correctly.
3) Check that you have the correct path in your request.
4) Check you are sending the correct data to the controller!!!
5) Check that the method is public.
6) Check that you are authorised to access that controller/method.
7) Check that you don't have any duplicate method names with either, a) the same parameters and name (if your not using an ActionMethodSelectorAttribute, or b) the same names and method select attributes.
8) Remove all parameters from your method, put a breakpoint at the start of the method, and try making the request and see if it hits the breakpoint. If it works without parameters and not with, then you are not passing the correct required data into the method.
9) Make your request and check the response!! (example below):
// make your request
$http({
method: 'POST',
url: '/Controller/Method',
data: {
foo: bar
}
}).then(function(response) {
// check your response (if a success status code was resolved)
console.log(response);
}, function(error) {
// check your error response
console.log(error);
});
If you have a 404 then your method was not found, if you have a 500 then something blew up in your code, if you have a 401 then you are unauthorised etc... This is really useful to actually know what is going on with your request...
10) Check your application is running!

Not hitting with Web API two different GET methods

Implemented webapi routing and having two different route methods for for retrieving values but it is differentiated by supplying parameter type.
Api methods are getting hit for the corresponding action methods if we simply specify "apiurl/api/contact/search/sri" and "apiurl/api/contact/get/2" in direct browser url.
But when comes to communicate with angular to webapi, api is not getting hit.
//angular service
contact.search = function (inputName) {
return $http({
method: 'GET',
url: url + 'api/contact/search',
//params: { name: inputName }
data: { name: inputName }
});
//return $http.get(url + 'api/contact/search', name);
}
//WebAPI
[HttpGet]
[Route("search/{name:alpha}")]
public IHttpActionResult GetContacts([FromBody]string name)
{
repository = new ContactRepository();
if (string.IsNullOrEmpty(name))
{
var message = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("Search Name can not be empty")
};
throw new HttpResponseException(message);
}
return Ok(repository.GetContact(name));
}
// GET api/contact/5
[HttpGet]
[Route("get/{id:int}")]
public IHttpActionResult Get(int id)
{
repository = new ContactRepository();
if (id == 0)
{
var message = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent("Issue with Passed Id Parameter.") };
throw new HttpResponseException(message);
}
return Ok(repository.GetContact(id));
}
When you use data: { name: inputName }, it is appended to the url in the following way:
...api/contact/search?name=inputName
but what you want is this:
...api/contact/search/inputName
So, you have two options.
Either change your angular code:
return $http({
method: 'GET',
url: url + 'api/contact/search/' + inputName,
});
or change your API to accept QUERY params.
Hope it helps

AngularJS/Spring MVC, HttpSession not persistent

We are developing a web application, we're using Spring MVC (along with Spring Boot and Spring Security) and AngularJS.
Therefore, we have two distinct servers running for the application.
We are trying to store the user session backend, to ensure a proper level of security, so we tried to use the HttpSessionobject, but every time we want to retrieve the existing session, a new instance is created (we've checked the session ids).
Here's what we're doing to login :
$scope.authenticate = function () {
var postObject = new Object();
postObject.mail = $scope.userName;
postObject.password = $scope.userPassword;
$http({
url: "http://localhost:8080/login",
method: "POST",
dataType: "json",
data: postObject,
headers: {
"Content-Type": "application/json"
}
}).success(function successCallback(response, status) {
if (status == 200) {
$scope.messageAuth = "Login successful"
$scope.go('/services');
}
})
.error(function errorCallback(error, status) {
$scope.messageAuth = "Error " + response;
});
};
Then, we check the credentials, if they are correct, we store the user information into a new session :
#RestController
public class UserController {
#Resource
UserService userService;
#CrossOrigin
#RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<User> loginSubmit(#RequestBody User user, HttpServletRequest request, HttpSession session) {
if (isAuthorized(user)) {
User authenticatedUser = this.userService.getUserByMail(user.getMail());
authenticatedUser.setPassword(null);
session.invalidate();
HttpSession newSession = request.getSession(true);
newSession.setAttribute("USER_ROLE", authenticatedUser.getRole());
System.out.println("/login : SESSION ID = " + newSession.getId());
System.out.println("/login : " + newSession.getAttribute("USER_ROLE"));
return ResponseEntity.ok(authenticatedUser);
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(null);
}
}
#RequestMapping("/user")
public String user(Principal user, HttpServletRequest request, HttpSession session) {
System.out.println("/user : SESSION ID = " + session.getId());
System.out.println("/user : " + (String) request.getSession(false).getAttribute("USER_ROLE"));
return (String) session.getAttribute("USER_ROLE");
}
And finally, from the Angular app, we'd like to get the user information by calling /user like this :
var f = function() {
$http.get('http://localhost:8080/user').success(function successCallback(response) {
console.log(response);
}).error(function() {
console.log('error');
})
};
We've already tried pretty much every we found about how to manage a session with Spring Security, maybe the problem comes from the Angular part?
Any help would be greatly appreciated,
Thanks in advance
We found the solution, we just needed to add a few config lines in our app.js file :
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
More information here : link
Hopefully it will help someone, someday!

ExtJs standard form submit with jsonData for file download

I'm trying to download a file from WebApi using ExtJs 4.2.3. After reading Extjs 4 downloading a file through ajax call, it looks like my best bet is to use the standard form.submit, however, my data is not passing as expected to the WebApi controller - using the below code, items comes through null.
Controller
public HttpResponseMessage Post(string exportType, List<PcAvailableComponent> items)
{
var dataToExport = _service.ExportItems(exportType, items);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new MemoryStream(dataToExport);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
Standard Submit
expForm.submit({
url: AppRootUrl + 'api/AdminDataExport?exportType=' + exportType,
//this doesn't work
jsonData: items,
waitMsg: 'Generating export...',
success: function (form, action) {
if (typeof expWindow !== "undefined") {expWindow.close();}
},
failure: function(form, action) {
Ext.Msg.alert('Failed', 'An error has occurred while generating the export: ' + JSON.parse(action.response.responseText)['ExceptionMessage']);
}
});
Ajax submit (works but can't get file back)
Ext.Ajax.request({
url: AppRootUrl + 'api/AdminDataExport',
params: {
exportType: 'PricingAndCosting'
},
jsonData: items,
method: 'POST',
success: function (response) {
expWindow.close();
console.log("success!");
}
});
Ended up abandoning WebApi for this controller, and just passing the JSON as a string, then deserializing it on the server side:
[HttpPost]
public ActionResult Index(string exportType, string items)
{
var dataToExport = _service.ExportItems(exportType, JsonConvert.DeserializeObject<List<PcAvailableComponent>>(items));
Response.AddHeader("Content-Disposition", "inline; filename=" + exportType + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".xlsx");
return File(dataToExport, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}

Nested Service promise not resolved in then()

I got a service which first need to retrieve an accesstoken and then a User object. When this is done, further UI actions needs to be taken. The problem I have is that login().then() is invoked with a valid Session.accesstoken but a non-resolved promise for the Session.user. So I can't do any logic based on the user's info (e.g. role, etc.)
The following code I have:
In controllers.js (login() is invoked upon form credentials button click)
.controller('LoginController',
function($scope, SessionService) {
$scope.credentials = {
username : '',
password : ''
};
$scope.login =
function() {
SessionService.login($scope.credentials).then(function() {
console.info("succesfully logged in as user " + JSON.stringify(Session));
// further UI actions..
});
};
})
In services.js
.factory('SessionService',
function(User, Session, AuthorizationService) {
return {
login : function(credentials) {
return AuthorizationService.requestToken(credentials)
.then(function(token) {
console.info("Got token: " + token);
if (!!token) {
Session.create(token);
console.info("Fetching user...");
return User.get({
id : 'me'
});
} else {
throw (new Error("Could not log in"));
}
}).then(function(user) {
console.info("Got user: " + user);
if (!!user) {
Session.user = user;
} else {
throw (new Error("Could not fetch user"));
}
});
},
};
})
Here is the output of the console:
Got token: cf9c0eba82d872508f7dcc0b234f0d52 services.js:120
Fetching user...
services.js:124 Got user: [object Object]
services.js:132 succesfully logged in as user
{"token":"cf9c0eba82d772508f7dcc0b234f0d52","user":{"$promise":{},"$resolved":false}}
The User object is created by $resource and is not a promise; it is the actual object that will eventually be populated with the user info, but at this point of the code it contains nothing.
The solution is simple: from the first then do:
return User.get({...}).$promise;
The next then will be invoked with the user object as expected, but only when the data is actually fetched.

Resources