security util using SecurityContextHolder in spring application - java

in my spring application I have some aspects for controller methods where I do some security checks. beacause of I need several checks more often I wrapped them into static helper methods of a "sercurityUtil" class.:
public abstract class SecurityUtils {
public static Authentication getCurrentAuthentication(){
return SecurityContextHolder.getContext().getAuthentication();
}
public static ChroniosUser getAuthenticatedUser(){
return (ChroniosUser) getCurrentAuthentication().getPrincipal();
}
public static boolean authenticationHasRole(Authentication authentication, Role role){
SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role.getRoleIdentifier());
return authentication.getAuthorities().contains(grantedAuthority);
}
public static boolean authenticatedUserIsAdmin(){
Authentication authentication = getCurrentAuthentication();
return authenticationHasRole(authentication, ADMIN);
}
...
}
is this a valid and good approach?
or shut I wrap these helper functions into a spring service?
thank you.
PS: I know that I can use #PreAuthorize ... but my aspects are more complex.

The short answer is :
Yes it seems to be a valid and good approach.
The long answer is :
It's up to you.
Spring Security documentation states that its infrastructure is based entirely on standard servlet filters and has no strong links to any particuler web technology, including Spring MVC
Spring Security’s web infrastructure is based entirely on standard
servlet filters. It doesn’t use servlets or any other servlet-based
frameworks (such as Spring MVC) internally, so it has no strong links
to any particular web technology. It deals in HttpServletRequest s and
HttpServletResponse s and doesn’t care whether the requests come from
a browser, a web service client, an HttpInvoker or an AJAX application
[Spring Security Reference - 1. The Security Filter Chain]
Its use is based nearly entirely on the SecurityContextHolder. The examples provided are through static methods :
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
As you can see, it's not a Spring Bean/Service/Component. SecurityContextHolder itself looks like a utility class.
Now you can create a Spring Service to expose it or you can use it through a classic Util class depending on what is more practical to you and for your application.

Related

intercept spring mvc controller call based on annotations

I have the following controller in spring MVC
#GetMapping("/id/kw")
public ModelAndView industryWater(HttpServletRequest request) {
return someMAV
}
I want to cut into the execution of the controller based on customized annotation
#GetMapping("/id/kw")
#WaterBefore
#WaterAfter
public ModelAndView industryWater(HttpServletRequest request) {
return someMAV
}
I can probably inject some thing using BEAN postProcessor, but I don't know how to hook my injected part with the controller execution. Also I need to access the context request mav when implementing my water aspect.
I researched a bit BeanPostProcessor, Interceptor, but didn't manage to connect all pieces.
I think you need to use AOP in Spring. that is very useful. it`s using transaction management and using logging etc.
Spring AOP (Aspect-oriented programming) framework is used to modularize cross-cutting concerns in aspects. If you want a more simple definition you can think of them as a Interceptor but with more options configurations possible. In Spring there are two different constructs that get called “interceptors”. First, there are Handler Interceptors, which are part of the Spring MVC framework and give you the ability to add interceptor logic to requests. But you also have Method Interceptors, which are part of the Spring AOP framework. These are much more general mechanism than Handler Interceptors, but also potentially more complex. In AOP terminology, such interceptors provide a means of coding the “aspects” you’re talking about.
Like this :
#Pointcut(" execution (* com.your.controller.industryWater(..))")
public void pointcutDemo() {}
#Before("pointcutDemo())")
public void logBefore(){ }
#After("pointcutDemo())")
public void logAfter(){ }
link : https://www.mkyong.com/spring3/spring-aop-aspectj-annotation-example/
https://www.journaldev.com/2583/spring-aop-example-tutorial-aspect-advice-pointcut-joinpoint-annotations
http://www.baeldung.com/spring-mvc-handlerinterceptor

How to create, manage, associate a session in REST Jersey Web Application

A HTML5 UI is connected to the backend (REST Jersey to business logic to Hibernate and DB).
I need to create and maintain a session for each user login until the user logs out.
Can you please guide me on what technologies/ APIs can be used.
Does something need to be handled at the REST Client end also..
Using JAX-RS for RESTful web services is fairly straightforward. Here are the basics. You usually define one or more service classes/interfaces that define your REST operations via JAX-RS annotations, like this one:
#Path("/user")
public class UserService {
// ...
}
You can have your objects automagically injected in your methods via these annotations:
// Note: you could even inject this as a method parameter
#Context private HttpServletRequest request;
#POST
#Path("/authenticate")
public String authenticate(#FormParam("username") String username,
#FormParam("password") String password) {
// Implementation of your authentication logic
if (authenticate(username, password)) {
request.getSession(true);
// Set the session attributes as you wish
}
}
HTTP Sessions are accessible from the HTTP Request object via getSession() and getSession(boolean) as usual. Other useful annotations are #RequestParam, #CookieParam or even #MatrixParam among many others.
For further info you may want to read the RESTEasy User Guide or the Jersey User Guide since both are excellent resources.

use HttpServletRequest in my Spring MVC application? Any benefits?

I came across authentication code in my company's java code. The application is a set of several REST services built on Spring MVC. There is a method that gets called in one of the authentication services on the HttpServletRequest object called getHeader(). And the method retrieves an AuthId. Why would they use HttpServletRequest in a spring MVC application? What are the benefits of using this servlet type code in the spring app? What would this method do? Any alternatives?
Spring MVC provides a lot of fabulous abstractions on top of HttpServletRequest, so you can avoid its low-level implementation details. You rarely need to access it directly.
For example, you could get a header value like Content-Type like this:
#GET
#Path("/myService")
public Response doSomething(#HeaderParam("Content-Type") String contentType) {
...
}
But there are times when you do need to access the HttpServletRequest directly--usually when you are using another API that demands it. If you are using some other library with a method you need that takes HttpServletRequest, then you got to grab it from Spring MVC directly.
For example, check out this method in this random UrlUtil class:
public static String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
//Get a path segment
}
You have no choice but to grab HttpServletRequest from Spring MVC.
Spring MVC is built on the Servlet API. Anything you could do with a Servlet, you can therefore do with Spring MVC. What the Spring MVC framework provides is a wrapper to code a web application in a specific architectural style. This wrapper adds behavior and some times simplifies tasks.
Why would they use HttpServletRequest in a spring MVC application?
In this case, because it is the most direct way to get the header.
What are the benefits of using this servlet type code in the spring
app?
Spring doesn't have to wrap anything. You get it directly from the source.
What would this method do?
Read the javadoc.
Any alternatives?
In a #Controller class' handler method, you can declare a parameter annotated with #RequestHeader and have Spring pass an argument that it retrieves from the HttpServletRequest headers.
This is, by default, restricted to #Controller methods annotated with #RequestMapping. If your service class is a HandlerInterceptor, Filter, or other type of class and simply has a reference to the HttpServletRequest object, there is nothing more you can do than retrieve it directly with getHeader(String).
Here is an alternative : Spring MVC define the parameter annotation #RequestHeader to read httpServletRequest headers :
#RequestMapping(...)
public #ResponseBody String myMethod(#RequestHeader String AuthId){
//the value of the parameter AuthId is the value of request header named AuthId
...
}

Securing Methods with Spring Security

For our current project, we are integrating JSF and the Spring Framework. I'd like to use Spring Security to handle authentication and authorization. So far, I have implemented a custom PasswordEncoder and AccessDecisionVoter which are working fine. Now I'm trying to secure methods using the #Secured annotation (among others) but I can't get that to work as I would expect it to do.
It seems that the #Secured annotation works for bean methods called directly from the JSF layer, only. Here's a simplified example:
#Named("foobarBean")
#Scope("access")
public class FoobarBean
{
#Secured("PERMISSION_TWO")
public void dummy()
{
}
#Secured("PERMISSION_ONE")
public String save()
{
dummy();
}
}
The method save() is called from the JSF layer like this:
<h:commandButton id="save" action="#{foobarBean.save}" />
Our AccessDecisionVoter is then asked to vote on PERMISSION_ONE but not on PERMISSION_TWO. Is this working as designed (I hope not) or am I doing something wrong (what could that be?).
I'd post more code or config but I'm not sure which part is relevant, and I don't want to clutter this post.
It is a simple problem of Proxy AOP! If you use Proxy AOP for Security, then the Proxy can only intercept calles that go through the proxy. If one method invoke an other method of the same bean directly, then there is no proxy that can intercept this call. -- And this is the reason why only the the Security Annotation of save() is taken in account.
One solution would be using AspectJ AOP instead of Proxy AOP. (It is supported by Spring (Security) too.)
Yes, That is how the AccessDecisionVoter works. It takes all roles allowed on a resource(method in your case) and vote for those roles form the current authenticated user's role. If the Role is matched, then only the permission is granted.
In your case also, the only Role defined for the save method is PERMISSION_ONE so the security system will check against this role only. If logged in user has that role, this method will be executed.

How can I secure Spring controller methods for user roles?

I have USER, ROLE and USER_ROLE tables and a bunch Spring controllers ... is there an Spring annotation I can add to the controller methods that will specify the role(s) a user should have to be able to access it?
I guess it's going to be Spring security? Is that straighforward to wire up to an existing user/role schema?
I'm using Spring 2.5.4.
Spring Security is going to be your easiest way to do it. What you're asking for specifically is Method Security Expressions. You can achieve this by using the following:
#PreAuthorize("hasRole('ROLE_ADMIN')")
public void deleteUser(User user) {
...
}
It's pretty straightforward to set up Spring Security with a database backend. I'd take a look at the DAOAuthenticationProvider as a starting point.
Spring Security annotations, as follows:
#Secured({"ROLE_1", "ROLE_2"})
public String mySecuredHander() {
return "foo";
}

Categories