AbpMVCAuthorize does not work on HTTPGet method in FileController - aspnetboilerplate

I am attempting to modify the FileController controller in Web.Core so the user is required to log in to download a file.
Adding the [AbpMvcAuthorize] to the method causes a 404. Why can't I just add the [AbpMvcAuthorize] annotation to a HTTPGet method?
[AbpMvcAuthorize]
public async Task<ActionResult> File(string fileName)
{
...
}
This annotation works on the HTTPPost methods. I think it is because the AuthToken is set. That is not possible on HTTPGets pasted directly into the browser.

Related

how to apply post method to all request mappings in spring

How i can access to request POST data from different url-s to one controller method, for example I have /countries & /countries/{id} URL, It works very good with first one, because my code is
#RequestMapping(value = {"/{id}", "/{id}/"}, method = RequestMethod.GET)
public String getCountry(#PathVariable(value = "id", required = true) int id,ModelMap model) {
}
#RequestMapping(method = RequestMethod.POST)
public String deleteCountry(ModelMap model,HttpServletRequest request) {
}
And when I try to request POST data from second url I'm getting
HTTP Status 405 - Request method 'POST' not supported
Which is expectable because I haven't POST method with this mapping, but if I will be made one method for one mapping my code will be too ugly ant terrible, what solution I can use?
Hum why not add the "array" of value to your second method as well ?
#RequestMapping(value = {"", "/{id}"},method = RequestMethod.POST)
public String deleteCountry(ModelMap model,
HttpServletRequest request) {
Btw using POST verb to call an action that looks like it will delete the resource seems wrong, it should be a DELETE verb used
EDIT
But in reality, you should be creating 2 methods, as both those method are not supposed to do the same thing.
POST /countries should be creating country resources
POST /countries/{id} should be doing something else.
For an update prefer PUT /countries/{id}
And for a delete, prefer DELETE /countries/{id}
There is one way to have separate handler interceptors for different controllers.
Refer this link for details.
bind Spring HandlerInterceptor only to one controller
But I feel, it may be good you can create a common method to share business logic for this.
As Interceptor comes with proxy class for your controller which can be avoided unless you have complex logic.

Can I specify that a controller level request mapping is not valid for a specific method into a Spring MVC controller class?

I am working on a Spring MVC application and I have the following problem into a controller class that is annotated with #RequestMapping("/profilo/") at class level.
So I have something like this:
#Controller
#RequestMapping("/profilo/")
public class ProfiloController extends BaseController {
..................................................................
..................................................................
SOME CONTROLLER METHOD THAT WORK CORRECTLY
..................................................................
..................................................................
#RequestMapping(value = "utenze/{username}/confermaEmail/{email:.+}", method = RequestMethod.GET)
public String confermaModificaEmail(#PathVariable String username, #PathVariable String email, Model model) {
logger.debug("INTO confermaModificaEmail(), indirizzo e-mail: " + email);
.......................................................................
.......................................................................
.......................................................................
}
}
So, as you can see in the previous code snippet, I have this ProfiloController class that is annotated with #RequestMapping("/profilo/") so it means that all the HTTP Request handled by the controller method of this class have to start with the /profilo/ in the URL.
It is true for all the method of this class except for the confermaModificaEmail() method that have to handle URL as:
http://localhost:8080/my-project/utenze/mario.rossi/confermaEmail/a.nobili#siatec.net
that don't tart with /profilo/.
So can I specify that for this specific method of the controller the #RequestMapping("/profilo/") controller level mapping is not valid and have to be not considered?
This is not possible.
Spring has maintained a proper #Controller structure which says for all endpoints related to ControllerName (i.e .Portfolio in your case) should be kept in this class.
Ideally, any other url not related to the functionality should be kept as part of a different Controller class.
If still you want to keep in same controller, try calling the endPoint url confermaModificaEmail() by redirecting the http call from "/portfolio/<"sample"> to the required url. But this is not recommended.

How to use send.redirect() while working with Spring MVC

I was trying to redirect to a dynamic page from Interceptors and Handler Mapping program. I have already defined a controller which handles and redirects (/hello.htm) through model (I have only this controller in my program). Until this point it is working fine. Apart from this, I registered a handler which will redirect to a page once it satisfies some condition.
public class WorkingHoursInterceptor extends HandlerInterceptorAdapter {
#Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("In Working Hours Interceptor-pre");
Calendar c=Calendar.getInstance();
if(c.get(Calendar.HOUR_OF_DAY)<10||c.get(Calendar.HOUR_OF_DAY)>20){
response.sendRedirect("/WEB-INF/jsp/failure.jsp");
return false;
}
return true;
..............
..............
}
But once it comes to response.sendRedirect, it is showing resource not found even though the mentioned page is present. I tried to redirect to "WEB-INF/jsp/hello.jsp" as well but keeps showing the same error. If the condition in the interceptor is not satisfied, the program works fine.
Below is shown the only controller present in the program.
#Controller
public class MyController {
#RequestMapping("/hello.htm")
public ModelAndView sayGreeting(){
String msg="Hi, Welcome to Spring MVC 3.2";
return new ModelAndView("WEB-INF/jsp/hello.jsp","message",msg);
}
}
(The controller for handling hello.html works fine if I change the interceptor condition)
Instead of redirecting, if I just print a message in the console, the program works fine. But once it comes to redirect it shows the error. Do I need to specify a separate controller to handle this request? Will this redirection request go to the dispatcher-servlet?
You need to add redirect: prefix in the view name, the code for redirect will look like:
#RequestMapping(value = "/redirect", method = RequestMethod.GET)
public String redirect() {
return "redirect:finalPage";
}
OR
#RequestMapping(value = "/redirect", method = RequestMethod.GET)
public ModelAndView redirect() {
return new ModelAndView("redirect:finalPage");
}
You may get a detail description from here:
enter link description here

Is there an equivalent of a "beforeHandler" for spring 4?

I have a controller with a requestmapping..
#Controller
public class TestController {
private static final String template = "Hello there, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/hello")
public #ResponseBody String hello() {
return "Hello";
}
}
How can I make it such that everytime a user goes to a RequestMapping, or whichever url, some other method is called to println to the console the URL the user is at before it actually enters the method "hello"?
I would like to use this method to ensure users have proper credentials in the future. I see there are #PreAuthorize annotation, but there doesnt seem to be a method associated with it that I can write my own logic, i.e. do a simple println to the console with the current URL the user is at.
You have a number of options.
With Spring, you can implement and register a HandlerInterceptor and implement its preHandle method to log the request URL, which you can reconstruct with the various HttpServletRequest methods.
With pure servlet-api, you can implement and register your own Filter which logs the request URL and then continues the chain, with doFilter(..).
You can also use AOP, advise all your #RequestMapping annotated methods with a #Before advice that logs the URL.

can't store parameter in session (Spring MVC)

I have the following problem with annotation based Spring MVC:
I have two Controllers (LoginController, AdminController) and I can pass an object (loggedInUser of type BonjourUser) form the LoginController to the AdminController by persisting it in the session. So far so good.
To prevent hotlinking, on the initial "GET" the AdminController verifies it received a valid admin-user when it is called.
This works fine the first Time, because the loginController added the object to the session.
Now here comes my problem:
Once the admin has logged in and tries to reaccess the admin-page (eg via a link in the JSP) the user-object seems to have vanished from the session, for I get a HttpSessionRequiredException for the "loggedInUser" attribute.
AFAIK the object should not be removed from the session unless I call setComplete() on the session. (I am not calling this method!) So why is the attribute removed from the session? I read here that you cannot pass session attribues between controllers. But then here it is said that it is possible. I also think it should work, since I already pass a parameter between controllers, when I redirect from the LoginController to the AdminController.
So here is the code:
LoginController:
#Controller
#SessionAttributes("loggedInUser")
public class LoginController extends BonjourController
{
[...]
#RequestMapping(value = {"/home"}, method = RequestMethod.POST)
public String validate(#ModelAttribute(value = "command") BonjourUser user, ModelMap map, HttpSession session)
{
[...]
map.addAttribute("loggedInUser", loggedInUser);
[...]
return "redirect:/admin";
}
}
And the AdminController:
#Controller
#RequestMapping(value = "/admin")
#SessionAttributes("loggedInUser")
public class AdminController extends BonjourController
{
#RequestMapping(method = RequestMethod.GET)
public String loginAdmin(#ModelAttribute("loggedInUser") BonjourUser loggedInUser, ModelMap map, HttpSession session)
{
//check if access is authorized
if(loggedInUser == null)
{
return "redirect:/login";
}
[...]
}
}
The link I use in the admins' jsp (which leads to the exception) looks like this
Once more to admin section
Basicaly I get the same exception when I just enter this in my browsers URL-bar:
http://localhost:8080/Bonjour/admin
The exception looks like this:
org.springframework.web.HttpSessionRequiredException: Expected session attribute 'loggedInUser'
So what do I need to change to ensure the user-object (loggedInUser) is not removed from the session?
Thanks in advance,
Maex
Update Spring to the latest version and it should work. See the comment to this answer: https://stackoverflow.com/a/9412890/1981720
I tried 3 different versions of spring now:
3.1.1
3.2.2
3.2.3
Always the same problem. The debugger tells me this:
I pass from login to admin:
object is perfectly stored in the session -> attributes map.
I use a link or re-type the url to access the same page again:
no object any more in session -> attributes map.
My bad - I blocked cookies!
So the session had no chance to be persisted except for POST requests, therefor the login worked but the GET for the same page did not...

Resources