Reputation: 1120
In my app I've got this method :
RequestMapping(value = "/variable/add", method = RequestMethod.POST)
public @ResponseBody
Object addVariable(@RequestBody MyObject myObject) {
//do something
return saimVariable;
}
and authentication aspect :
@Around("execution(* pl.my.company.*.*(..))")
public Object advice(ProceedingJoinPoint joinPoint) {
ServletRequestAttributes t = (ServletRequestAttributes) RequestContextHolder
.currentRequestAttributes();
HttpServletRequest request = t.getRequest();
String username = (String) request.getParameter("username");
System.out.println("USER : " + username);
try {
if (username.equals("myname")) {
System.out.println("*** ACCESS GRANTED *** ");
Object response = joinPoint.proceed();
return response;
} else {
System.out.println();
return "ACCESS DENIED";
}
} catch (Throwable e) {
System.out.println(e.getMessage());
return "ACCESS DENIED";
}
}
}
I want to create REST service so for securitu I need to authenticate EVERY request, so i need to pass also a USERNAME, not only a JSON. But i don't know how to do it, because when i use @RequestParam("myObject")
instead of @RequestBody
it just don't work. So my question is :
How can I pass both JSON and other parameters (strings,ints ...etc) with ONE POST request?
Upvotes: 0
Views: 1385
Reputation: 34
1) First I'll suggest you to use Spring-Security. For checking every request there is a annotation in spring @PreAuthorize that will help to check every request before processing.
2)And If you want to use check current logged in user's username then their is no need of passing two parameter.You can check current logged in user by using following code.
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/current", method = RequestMethod.GET)
public @ResponseBody Users getCurrentLoggedInUser() throws Exception {
Object authenticatorPrincipalObject = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String userName = null;
if(authenticatorPrincipalObject != null && authenticatorPrincipalObject instanceof Users){
Users authenticatorPrincipal = (Users) authenticatorPrincipalObject;
userName = authenticatorPrincipal.getUsername();
}else if(authenticatorPrincipalObject != null){
userName = authenticatorPrincipalObject.toString();
}else{
return null;
}
return userService.getCurrentLoggedInUser(userName);
}
3)And i don't think in a single request we can pass both @RequestBody and @RequestParam . Spring MVC - Why not able to use @RequestBody and @RequestParam together
Upvotes: 1