How to make #PreAuthorize having higher precedence than #Valid or #Validated - spring-mvc

I am using spring boot, and I have enabled the global method security in WebSecurityConfigurerAdapter by
#EnableGlobalMethodSecurity(prePostEnabled = true, order = Ordered.HIGHEST_PRECEDENCE)
And Below is my controller code
#PreAuthorize("hasAnyRole('admin') or principal.id == id")
#RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public User updateUser(#PathVariable("id") String id, #Valid #RequestBody UserDto userDto)
{ ....}
However, when a non-admin user try to do a PUT request, the JSR303 validator will kick in before #PreAuthorize.
For example, non-admin user ended up getting something like "first name is required" instead of "access denied". But after user supplied the first name variable to pass the validator, access denied was returned.
Does anyone know how to enforce the #PreAuthorize get checked before #Valid or #Validated?
And I have to use this kind of method-level authorization instead of url-based authorization in order to perform some complex rule checking.

I had the same issue and I found this post. The comment of M. Deinum helps me to understand what was going wrong
Here is what I did :
The public method has the #PreAuthorize and do the check
There is NO #Valid on the #RequestBody parameter
I create a second method, private, where I do the DTO validation. Using the #Valid annotation
The public methods delegates the call to the private one. The private method is called only is the public method is authorized
Example :
#RequestMapping(method = RequestMethod.POST)
#PreAuthorize("hasRole('MY_ROLE')")
public ResponseEntity createNewMessage(#RequestBody CreateMessageDTO createMessageDTO) {
// The user is authorized
return createNewMessageWithValidation(createMessageDTO);
}
private ResponseEntity createNewMessageWithValidation(#Valid CreateMessageDTO createMessageDTO) {
// The DTO is valid
return ...
}

For the same scenario, I have found reccomendations to implement security via spring filters.
Here is similar post : How to check security acess (#Secured or #PreAuthorize) before validation (#Valid) in my Controller?
Also, maybe a different approach - try using validation via registering a custom validator in an #InitBinder (thus skip the #valid annotation).
To access principal object in filter class:
SecurityContextImpl sci = (SecurityContextImpl)
session().getAttribute("SPRING_SECURITY_CONTEXT");
if (sci != null) {
UserDetails cud = (UserDetails) sci.getAuthentication().getPrincipal();
}
In this case /{id} is a path param in the URL. To access path params in filter or interceptor class:
String[] requestMappingParams = ((HandlerMethod)handler).getMethodAnnotation(RequestMapping.class).params()
for (String value : requestMappingParams) {.

Use WebSecurityConfigurerAdapter.configure(HttpSecurity http) instead of #PreAuthorize
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
{
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.mvcMatchers( "/path/**").hasRole("admin");
}
}

Related

Spring security Authentication parameter in #Controller handler method [duplicate]

I have a Spring MVC web app which uses Spring Security. I want to know the username of the currently logged in user. I'm using the code snippet given below . Is this the accepted way?
I don't like having a call to a static method inside this controller - that defeats the whole purpose of Spring, IMHO. Is there a way to configure the app to have the current SecurityContext, or current Authentication, injected instead?
#RequestMapping(method = RequestMethod.GET)
public ModelAndView showResults(final HttpServletRequest request...) {
final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
...
}
If you are using Spring 3, the easiest way is:
#RequestMapping(method = RequestMethod.GET)
public ModelAndView showResults(final HttpServletRequest request, Principal principal) {
final String currentUser = principal.getName();
}
A lot has changed in the Spring world since this question was answered. Spring has simplified getting the current user in a controller. For other beans, Spring has adopted the suggestions of the author and simplified the injection of 'SecurityContextHolder'. More details are in the comments.
This is the solution I've ended up going with. Instead of using SecurityContextHolder in my controller, I want to inject something which uses SecurityContextHolder under the hood but abstracts away that singleton-like class from my code. I've found no way to do this other than rolling my own interface, like so:
public interface SecurityContextFacade {
SecurityContext getContext();
void setContext(SecurityContext securityContext);
}
Now, my controller (or whatever POJO) would look like this:
public class FooController {
private final SecurityContextFacade securityContextFacade;
public FooController(SecurityContextFacade securityContextFacade) {
this.securityContextFacade = securityContextFacade;
}
public void doSomething(){
SecurityContext context = securityContextFacade.getContext();
// do something w/ context
}
}
And, because of the interface being a point of decoupling, unit testing is straightforward. In this example I use Mockito:
public class FooControllerTest {
private FooController controller;
private SecurityContextFacade mockSecurityContextFacade;
private SecurityContext mockSecurityContext;
#Before
public void setUp() throws Exception {
mockSecurityContextFacade = mock(SecurityContextFacade.class);
mockSecurityContext = mock(SecurityContext.class);
stub(mockSecurityContextFacade.getContext()).toReturn(mockSecurityContext);
controller = new FooController(mockSecurityContextFacade);
}
#Test
public void testDoSomething() {
controller.doSomething();
verify(mockSecurityContextFacade).getContext();
}
}
The default implementation of the interface looks like this:
public class SecurityContextHolderFacade implements SecurityContextFacade {
public SecurityContext getContext() {
return SecurityContextHolder.getContext();
}
public void setContext(SecurityContext securityContext) {
SecurityContextHolder.setContext(securityContext);
}
}
And, finally, the production Spring config looks like this:
<bean id="myController" class="com.foo.FooController">
...
<constructor-arg index="1">
<bean class="com.foo.SecurityContextHolderFacade">
</constructor-arg>
</bean>
It seems more than a little silly that Spring, a dependency injection container of all things, has not supplied a way to inject something similar. I understand SecurityContextHolder was inherited from acegi, but still. The thing is, they're so close - if only SecurityContextHolder had a getter to get the underlying SecurityContextHolderStrategy instance (which is an interface), you could inject that. In fact, I even opened a Jira issue to that effect.
One last thing - I've just substantially changed the answer I had here before. Check the history if you're curious but, as a coworker pointed out to me, my previous answer would not work in a multi-threaded environment. The underlying SecurityContextHolderStrategy used by SecurityContextHolder is, by default, an instance of ThreadLocalSecurityContextHolderStrategy, which stores SecurityContexts in a ThreadLocal. Therefore, it is not necessarily a good idea to inject the SecurityContext directly into a bean at initialization time - it may need to be retrieved from the ThreadLocal each time, in a multi-threaded environment, so the correct one is retrieved.
I agree that having to query the SecurityContext for the current user stinks, it seems a very un-Spring way to handle this problem.
I wrote a static "helper" class to deal with this problem; it's dirty in that it's a global and static method, but I figured this way if we change anything related to Security, at least I only have to change the details in one place:
/**
* Returns the domain User object for the currently logged in user, or null
* if no User is logged in.
*
* #return User object for the currently logged in user, or null if no User
* is logged in.
*/
public static User getCurrentUser() {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal()
if (principal instanceof MyUserDetails) return ((MyUserDetails) principal).getUser();
// principal object is either null or represents anonymous user -
// neither of which our domain User object can represent - so return null
return null;
}
/**
* Utility method to determine if the current user is logged in /
* authenticated.
* <p>
* Equivalent of calling:
* <p>
* <code>getCurrentUser() != null</code>
*
* #return if user is logged in
*/
public static boolean isLoggedIn() {
return getCurrentUser() != null;
}
To make it just show up in your JSP pages, you can use the Spring Security Tag Lib:
http://static.springsource.org/spring-security/site/docs/3.0.x/reference/taglibs.html
To use any of the tags, you must have the security taglib declared in your JSP:
<%# taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
Then in a jsp page do something like this:
<security:authorize access="isAuthenticated()">
logged in as <security:authentication property="principal.username" />
</security:authorize>
<security:authorize access="! isAuthenticated()">
not logged in
</security:authorize>
NOTE: As mentioned in the comments by #SBerg413, you'll need to add
use-expressions="true"
to the "http" tag in the security.xml config for this to work.
If you are using Spring Security ver >= 3.2, you can use the #AuthenticationPrincipal annotation:
#RequestMapping(method = RequestMethod.GET)
public ModelAndView showResults(#AuthenticationPrincipal CustomUser currentUser, HttpServletRequest request) {
String currentUsername = currentUser.getUsername();
// ...
}
Here, CustomUser is a custom object that implements UserDetails that is returned by a custom UserDetailsService.
More information can be found in the #AuthenticationPrincipal chapter of the Spring Security reference docs.
I get authenticated user by
HttpServletRequest.getUserPrincipal();
Example:
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.support.RequestContext;
import foo.Form;
#Controller
#RequestMapping(value="/welcome")
public class IndexController {
#RequestMapping(method=RequestMethod.GET)
public String getCreateForm(Model model, HttpServletRequest request) {
if(request.getUserPrincipal() != null) {
String loginName = request.getUserPrincipal().getName();
System.out.println("loginName : " + loginName );
}
model.addAttribute("form", new Form());
return "welcome";
}
}
In Spring 3+ you have have following options.
Option 1 :
#RequestMapping(method = RequestMethod.GET)
public String currentUserNameByPrincipal(Principal principal) {
return principal.getName();
}
Option 2 :
#RequestMapping(method = RequestMethod.GET)
public String currentUserNameByAuthentication(Authentication authentication) {
return authentication.getName();
}
Option 3:
#RequestMapping(method = RequestMethod.GET)
public String currentUserByHTTPRequest(HttpServletRequest request) {
return request.getUserPrincipal().getName();
}
Option 4 : Fancy one : Check this out for more details
public ModelAndView someRequestHandler(#ActiveUser User activeUser) {
...
}
I would just do this:
request.getRemoteUser();
Yes, statics are generally bad - generally, but in this case, the static is the most secure code you can write. Since the security context associates a Principal with the currently running thread, the most secure code would access the static from the thread as directly as possible. Hiding the access behind a wrapper class that is injected provides an attacker with more points to attack. They wouldn't need access to the code (which they would have a hard time changing if the jar was signed), they just need a way to override the configuration, which can be done at runtime or slipping some XML onto the classpath. Even using annotation injection in the signed code would be overridable with external XML. Such XML could inject the running system with a rogue principal. This is probably why Spring is doing something so un-Spring-like in this case.
For the last Spring MVC app I wrote, I didn't inject the SecurityContext holder, but I did have a base controller that I had two utility methods related to this ... isAuthenticated() & getUsername(). Internally they do the static method call you described.
At least then it's only in once place if you need to later refactor.
You could use Spring AOP aproach.
For example if you have some service, that needs to know current principal. You could introduce custom annotation i.e. #Principal , which indicate that this Service should be principal dependent.
public class SomeService {
private String principal;
#Principal
public setPrincipal(String principal){
this.principal=principal;
}
}
Then in your advice, which I think needs to extend MethodBeforeAdvice, check that particular service has #Principal annotation and inject Principal name, or set it to 'ANONYMOUS' instead.
The only problem is that even after authenticating with Spring Security, the user/principal bean doesn't exist in the container, so dependency-injecting it will be difficult. Before we used Spring Security we would create a session-scoped bean that had the current Principal, inject that into an "AuthService" and then inject that Service into most of the other services in the Application. So those Services would simply call authService.getCurrentUser() to get the object. If you have a place in your code where you get a reference to the same Principal in the session, you can simply set it as a property on your session-scoped bean.
The best solution if you are using Spring 3 and need the authenticated principal in your controller is to do something like this:
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
#Controller
public class KnoteController {
#RequestMapping(method = RequestMethod.GET)
public java.lang.String list(Model uiModel, UsernamePasswordAuthenticationToken authToken) {
if (authToken instanceof UsernamePasswordAuthenticationToken) {
user = (User) authToken.getPrincipal();
}
...
}
Try this
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
String userName = authentication.getName();
I am using the #AuthenticationPrincipal annotation in #Controller classes as well as in #ControllerAdvicer annotated ones. Ex.:
#ControllerAdvice
public class ControllerAdvicer
{
private static final Logger LOGGER = LoggerFactory.getLogger(ControllerAdvicer.class);
#ModelAttribute("userActive")
public UserActive currentUser(#AuthenticationPrincipal UserActive currentUser)
{
return currentUser;
}
}
Where UserActive is the class i use for logged users services, and extends from org.springframework.security.core.userdetails.User. Something like:
public class UserActive extends org.springframework.security.core.userdetails.User
{
private final User user;
public UserActive(User user)
{
super(user.getUsername(), user.getPasswordHash(), user.getGrantedAuthorities());
this.user = user;
}
//More functions
}
Really easy.
Define Principal as a dependency in your controller method and spring will inject the current authenticated user in your method at invocation.
I like to share my way of supporting user details on freemarker page.
Everything is very simple and working perfectly!
You just have to place Authentication rerequest on default-target-url (page after form-login)
This is my Controler method for that page:
#RequestMapping(value = "/monitoring", method = RequestMethod.GET)
public ModelAndView getMonitoringPage(Model model, final HttpServletRequest request) {
showRequestLog("monitoring");
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String userName = authentication.getName();
//create a new session
HttpSession session = request.getSession(true);
session.setAttribute("username", userName);
return new ModelAndView(catalogPath + "monitoring");
}
And this is my ftl code:
<#security.authorize ifAnyGranted="ROLE_ADMIN, ROLE_USER">
<p style="padding-right: 20px;">Logged in as ${username!"Anonymous" }</p>
</#security.authorize>
And that's it, username will appear on every page after authorisation.

How to add model attributes to the default error page

What is the best way to handle default page not found error when a user requests a url that doesn't have any mapping in the application (e.g. a url like /aaa/bbb that there is no mapping for it in the application) while be able to add model attributes to the page?
There is some anserws in SO but those have caused me other problems and more importantly they don't state how to add model attributes to the error page.
The best solution I have found is this:
Create a controller that implements ErrorController and overrides
its getErrorPath() method.
In that controller create a handler method annotated with
#RequestMapping("/error")
It's in this method that you can add whatever model attributes you want and return whatever view name you want:
#Controller
public class ExceptionController implements ErrorController {
#Override
public String getErrorPath() {
return "/error";
}
#RequestMapping("/error")
public String handleError(Model model) {
model.addAttribute("message", "An exception occurred in the program");
return "myError";
}
}
Now if you want to handle other specific exceptions you can create #ExceptionHandler methods for them:
#ExceptionHandler(InvalidUsernameException.class)
public String handleUsernameError(Exception exception, Model model) {
model.addAttribute("message", "Invalid username");
return "usernameError";
}
Notes:
If you add specific exception handlers in the class, don't forget to annotate the controller with #ControllerAdvice (along with the #Controller)
The overridden getErrorPath() method can return any path you want as well as /error.

Combining POST and GET in SpringMvc

For a user registration form (registration.html) I created a view controller through:
#Configuration
#EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/user/registration").setViewName("registration");
}
This works fine, and if I go to /user/registration (i.e. GET), I can see the registration form.
However if I now want to create a controller for POST requests at the same uri through:
#Controller
public class RegistrationController {
#RequestMapping(value = "/user/registration", method = RequestMethod.POST)
#ResponseBody
public GenericResponse registerUserAccount(#Valid final UserDto accountDto, final HttpServletRequest request) {
// some code
}
}
I get an error message at the /user/registration uri saying:
Request method 'GET' not supported
So it seems that my post controller is somehow overriding the GET controller which was working before. Why is that? Is it possible to make the two work together or do I have to write my own GET controller in the same way as my post controller?

New implementation/method of existing request mapping in controller

I am trying to look for a way to extend a controller such that I can use the existing request mapping but with a different implementation/method tied to it.
Say for example, below is a code snippet from AdminBasicEntityController in BLC where viewAddEntityForm method is tied to /add request mapping. Now I want to have my own logic of showing entityForm(Say Product entity) using /add request mapping. Is it possible?
#Controller("blAdminBasicEntityController")
#RequestMapping("/{sectionKey:.+}")
public class AdminBasicEntityController extends AdminAbstractController {
#RequestMapping(value = "", method = RequestMethod.GET)
public String viewEntityList(HttpServletRequest request, HttpServletResponse response, Model model,
#PathVariable Map<String, String> pathVars,
#RequestParam MultiValueMap<String, String> requestParams) throws Exception {
// default implementation
}
#RequestMapping(value = "/add", method = RequestMethod.GET)
public String viewAddEntityForm(HttpServletRequest request, HttpServletResponse response, Model model,
#PathVariable Map<String, String> pathVars,
#RequestParam(defaultValue = "") String entityType) throws Exception {
// default implementation
}
}
Also I found below mentioned information in the documentation of AdminBasicEntityController, so does it mean I can have controller for specific entity. If yes, how?
The default implementation of the {#link #BroadleafAdminAbstractEntityController}. This delegates every call to super and does not provide any custom-tailored functionality. It is
responsible for rendering the admin for every entity that is not
explicitly customized by its own controller
#RequestMapping("/{sectionKey:.+}") uses the generic path variable sectionKey, making the controller handle any requests that are not explicitly mapped. For example,
/product
/product/add
/category
/category/add
/store
/store/add
may all be hitting this controller if these URLs have not been explicitly mapped to their own controllers.
To handle a specific URL yourself, you could do:
#Controller
#RequestMapping("/product")
public class ProductAdminController {
#RequestMapping("/add")
public String viewAddEntityForm(...) { ... }
}
Now, the URL /product/add will be routed to this custom controller while all others will continue to get routed to the generic controller.

Spring Web MVC: Pass an object from handler interceptor to controller?

Currently I am using request.setAttribute() and request.getAttribute() as a means to pass an object from a handler interceptor to a controller method. I don't view this as an ideal technique, because it requires that I take HttpServletRequest as an argument to my controller methods. Spring does a good job hiding the request object from controllers, so I would not need it except for this purpose.
I tried using the #RequestParam annotation with the name I set in setAttribute(), but of course that did not work because request attributes are not request params. To my knowledge, there is no #RequestAttribute annotation to use for attributes.
My question is, is there some better way to hand off objects from interceptors to controller methods without resorting to setting them as attributes on the request object?
Use the interceptor prehandle method and session like this:
Interceptor:
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!(handler instanceof HandlerMethod)) {
return true;
}
HttpSession session = request.getSession();
String attribute = "attribute";
session.setAttribute("attributeToPass", attribute);
return true;
}
Controller:
#RequestMapping(method = RequestMethod.GET)
public String get(HttpServletRequest request) {
String attribute = (String)request.getSession().getAttribute("attribteToPass");
return attribute;
}
Just to save time for those visiting this page: since Spring 4.3 #RequestAttribute annotation is a part of Spring MVC, so there is no need to create your own #RequestAttribute annotation.
An example using #RequestAttribute:
Interceptor
#Component
public class ExampleRequestInterceptor
implements HandlerInterceptor {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// Logic to verify handlers, you custom logic, etc.
// Just for illustration, I'm adding a `List<String>` here, but
// the variable type doesn't matter.
List<String> yourAttribute = // Define your attribute variable
request.setAttribute("yourAttribute", yourAttribute);
return true;
}
}
Controller
public ResponseEntity<?> myControllerMethod(#RequestParam Map<String, String> requestParams, #RequestAttribute List<String> yourAttribute) {
// `yourAttribute` will be defined here.
}

Resources