How to use annotations (Actions) to authenticate/authorize user? - java

In play framework 2, the zentasks sample shows how to do basic authentication. They subclassed Security.Authenticator and added additional methods for authorization. I find it a bit messy, since each method needs to be wrapped with an if-statement.
How can I convert the methods isOwnerOf and isMemberOf into Actions? This would allow me to simply annotate the methods. Currently, I am struggling in create an annotation that would accept the param of the method. Even if I annotate the parameter, then I do not know how to fetch it when the Action is called.
If there's a better way, I would be glad to hear so.

Take a ready to use full stack for authentication/authorization - Play Authenticate
it includes Deadbolt
it offers common providers like Facebook, Twitter, Goolge, etc
it offers common password + own providers
it supports multilanguage (also in informational mails)
it includes ready-to-use Java sample

Related

Osgi annotation processing

I have a component declared using the #Component annotation, in which there is a set of methods that implement communication with another api, in my product there are operations that are prohibited for a user with an anonymous id. I want to create an annotation, for example #ProhibitedForAnonym, which, every time the method is called, will check the ID of the anonymous customer, with the ID in the method parameter and throw an error if the IDs match. But I don't understand how to do annotation processing in OSGI, maybe some kind of interceptor?
There is no general interception framework in OSGi. However, you could do interception in the following ways:
Don't. Personally, I feel that since we've lambdas a code-based solution has won hands on over a 'magic' annotation check. It is about the same number of characters but a lambda based call allows me to single step, provide context to the security check, does not suffer from the THIS problem, is testable, and requires no complex framework with lots of bug opportunities.
Use the byte code weaving support in OSGi. You need to register a weaver early and then weave any class that has these annotations. You can take a look at https://github.com/aQute-os/biz.aQute.osgi.util/tree/master/biz.aQute.trace for an example of how to use the byte code weaver. Make sure your weaver is there first. If you use bndtools you can add it to the -runpath to run before anybody else. Or use start levels.
Use proxying. You can 'hide' and original service with the Service Hooks and then register a proxy. In the proxy you can then do the annotation check. This also requires that this code runs first and cannot be updated. I think the spec has an example of this
You might want to read: https://www.aqute.biz/appnotes/interceptors.html

Different ways to implement security using spring security framework

I am new to spring security framework.I was just compiling the various ways to add security features using spring security annotations or spring security framework.
Found the below so far.
Full Page Authorization
example: <intercept-url pattern="/user/**" access="hasRole('ROLE_USER')" />
In-Page Authorization
example : <security:authorize access="hasRole('ROLE_ADMIN')">
Method Level Authorization - #PreAuthorize,#PostAuthorize,#PreFilter,#PostFilter
I am not sure if this is an exhaustive list to secure the application. Need some help for the same. Thanks.
Also,I am looking for security features which can easily be implemented and configurable- where developers are less likely to make mistakes and at the same time achieve the required security goals.It looks like annotations are easy to use and less ambiguous. Are annotations used only for method level authorization? Does spring security provide annotations which can be used for securing other parts of the application and can these annotations be passed parameters to configure the permissions or privileges?
I hope my question is not too broad. Any edits or helpful comments would be appreciated.
Perhaps you need to start by identifying the requirements of your domain model, what is deemed sensitive data and what not and how this data is being accessed (HTML/JSP vs REST/JSON vs direct Java calls). Then use the authorization features as needed. Your list contains pretty much what most applications will ever need, but for finer and more advanced authorization mechanisms have a look at Spring's ACL:
http://docs.spring.io/spring-security/site/docs/3.0.x/reference/domain-acls.html
Another important question you may want to answer to yourself is which application layer will be responsible for enforcing your security: MVC/REST vs Services (scattering this concern across multiple layers is usually bad idea). This will directly dictate the choices of SS features you are going to make.
You may wish to build your own annotations on top of SS annotations which reflect closely your particular domain. This way all complexity will be concentrated in a single place, leaving less room for error.
For example, you can create a custom annotation such as #AuthorizedFor where you can add various domain-specific parameters. You then annotate this annotation with one of SS annotations, say #Pre/PostAuthorize("hasAnyRole()") (here you can also play with the Spring's native EL to further customise the behaviour) and use custom implementation of Pre/PostInvocationAuthorizationAdvice where you make the authorization decisions based on your custom annotation parameters. The added advantage here is that you will be able to secure complete classes with your custom annotation instead of having to annotate all methods in that class. In your implementation you get the MethodInvocation instance from where you can interrogate the class containing the method and see if its annotated, then proceed as-if the method itself was annotated.
See this article for more in-depth discussion: http://blog.novoj.net/2012/03/27/combining-custom-annotations-for-securing-methods-with-spring-security/
There are basically 2 ways to implement spring security. through bean configuration in .xml files and other by using Annotations. Annotation based method is easy to use in long term as it is less ambiguous.
here is the reference to spring.io . Both ways are explained nicely.
http://spring.io/blog/2013/07/03/spring-security-java-config-preview-web-security/
Annotation is pure java based configuration and will most probably overtake xml configuration.
The three items in your list serve different purposes:
intercept-url : Adds security at the servlet layer. In other words, you control who can/cannot access any url in your application. For example you may add permission only to administrators to access the url /admin/some_critical_operation, but allow all authenticated users to access /some_informational_page. It is possible to secure your application with this type of authorisation only but it is very fragile design. Adding or changing urls can easily break security without notice.
In-Page Authorization: It is not real authorisation, just a convenience tag for hiding html content not intended for the current user. For example a non-admin user should not see the button create new user. As I said it is not real security measure since the user can type the url in the browser and gain access if none of the other authorisation types have been applied.
Method Level Authorization: Adds security to the service layer. This means you can apply restrictions on who can/cannot call a method of some service class. It is considered more secure and harder to compromise since it is applied deeper in the application layer stack. It can be applied both with annotations and with the security namespace.
Usually you start by securing your application in the service layer and then add some url control as well. Adding authorisation tags in pages is optional.
I can't comment yet, but regarding your question:
Are there annotations which are configurable? For example, I provided the method level security annotations where you provide the parameters - like the roles of users who have the privileges to access the method or to access the elements returned by the method
You are free to write your own annotations, which are in turn annotated with the native Spring Security annotations. This makes them essentially a domain-specific extension. That said, the standard SS annotations allow the use of SpEL which is rather flexible even tough is not bound to your particular domain. You can easily assert if user has certain roles (GrantedAuthority), etc ...
If you want to implement your own annotations, see the link in my other answer for a thorough discussion.
I can give you a concrete example from a recent project I worked on. We had authorization groups managed by external system and also built-in logic which defines access to certain resources. So, essentially we had 2 places to look for authorization parameters. We've created the concept of Authorization Groups (retrieved externally via LDAP) and Authorization Roles (built-in, business logic). The groups were simple - if user is a member of the group, they are granted access, else denied. With the roles, we had business rules which determine whether the user has a particular role or not (for example - signed T&C, accepted EULA, etc ...). All of these are determined at the authentication stage.
To make it easier to reason about our access control, we created two annotations #AuthorisedForGroups({group1, group2, ...}) and #AuthorisedForRoles({role1, role2,...}). Each of these was in turn annotated with Spring's native #PreAuthorize("hasAnyRole()"). Note the use of "hasAnyRole()" - this is simply to tell Spring "let everybody who is authenticated in" and that "we are going to make the authorization decisions ourselves". The authorization decisions are then made in a custom implementation of PreInvocationAuthorizationAdvice (in fact we just extended Spring's own implementation ExpressionBasedPreInvocationAdvice) and put the decision-making logic in #before() method:
#Override
public boolean before(Authentication authentication, MethodInvocation mi, PreInvocationAttribute attr) {
// 1) get AuthorisedForGroups & AuthorisedForRoles for the method
// 2) if either is missing from the method, check the enclosing class
// 3) if no annotations found - simply return super.before(...)
// 4) else, introspect the 'authentication' and see if it has the required groups/roles
// - here you may want to use 'ExpressionBasedAnnotationAttributeFactory' to
// create your own expressions which you then pass to super.before(...).
// This especially makes sense when your groups/roles
// are mapped to GrantedAuthority instances - as it was the case with our code.
}
Hope this helps.

Custom annotations for authorization in play framework

Hello first things first: Im using play framework 2.2.3 for java.
Basic tutorial about authentication in play shows how to use Annotation Security.Authenticated. The problem is that whole my application (besides login and registry forms) needs to be secured.
Now I thought of overloading GlobalSettings onRequest method and include my authentication inside, so every single call of an action would perform authentication check.
But I was told its not elegant way and was told to create another annotation similar to Security.Authenticated, but working on a whole class instead of method, and put it into my custom abstract controller class, so all my controllers that extends it will inherit this annotation.
Now I'm wondering how to make this annotation. Any tips ? Where should I start ? I know basics, how to code annotation itself, but i dont know where is right place to get annotations of controllers class to check if it contains my custom annotation, and perform authentication if so.
If you're looking for an authorization + authentication plugin for Play that can secure the whole class, and hence all the action methods within it, try SecureSocial. It has its own set of annotations, and securing every action method in a class is as easy as doing:
#SecureSocial.SecuredAction
public class MyController extends Controller {
Yes it's a little bit more work than intercepting the request and doing your check there, but its a more flexible method in case you'd like to "unsecure" some of the actions later on.

Dynamic custom validation with Play framework 2.2.x

This post makes it easy to set up a custom validation tag using Play 2.1(or 2).x "How to create a custom validator in Play Framework 2.0?". My use case, however, is a little different and I am hoping for a UI Play Framework Jedi Master that can provide some sort of direction. We have the normal MVC pattern to create reports, and for most scenarios, having validation in the play model using custom tags works fine. One of our use cases, however, is for custom "dynamic" validation. If we use the "Required" case, as an example, its easy to say that when form ABC loads, then fields X, Y and Z are required - But what if you dont know the list of required fields until just before the form is rendered and the list of required fields is provided to you in a json file from a db read in the controller. How, then, would you cater for this with the Play framework?
I may have a solution but without annotation. Create a validate method on your form (see http://www.playframework.com/documentation/2.2.x/JavaForms)
You'll be able to do all the checks you want there.

How to dynamically generate Validations for the Front end depending upon the Logic

Consider the page below. As in the image I have attached.
Now my problem is that I have multiple clients accessing the same page as given below. Now consider that each client has their own requirement such as:-
Name is mandatory for some clients not for others.
Age is mandatory for some clients but not for others along with some specific validations like age<20 or age>30 etc.
Search is also optional depending upon the clients.
Now I am searching for any such tools or technologies or methods that could help me to sort out the issue of dynamically validating the fields as well as hiding and showing the fields depending upon my clients. Please let me know any tools or technologies that can help in order to solve the above problem. I also heard about rule engine and templating .... Is it possible to work together with it to achieve the same. Please suggest.
I have no idea why hibernate-validator would not work here. You implement the validation as you want, by implementing an interface and creating your own validation annotations if needed. This is a server-side validation btw.
Showing or not some content in case of JSP is done with conditional :
c:when/c:choose
for example, assuming it's JSP you are using.

Categories