Play Framework controller with secure and non-secure methods. Possible? - security

I try to make a website with play with a member and a non member area. So i have controllers with member and non-member methods. But i can only make the whole controller secure [#With(Secure.class)].
Is it possibly to make only a few methods secure and access the others without a login?
Thanks

Yes, you can, although it will require some tweaking on the Secure class. If you check #Secure it has a method annotated with #Before. As per documentation you can indicate which methods the #Before is applied to and for which ones it is skipped.
#Before(unless="login")
So it would be a matter of not running #Before on the public methods. Be aware it may not work properly using #With and you may need to create your own #Before in the controller that manages the security (calling the proper methods in secure).
But it would be simpler to just have 2 controllers, one for secure users and one for public methods.

You can use the deadbolt module which is quite powerful: http://www.playframework.org/modules/deadbolt

Yes, you can to this. Remove #With annotation and use this method of Secure controller when you want restrict access to connected user :
Secure.checkAccess();
With this method, you can even use #Check annotation. Example :
#Check("member")
public static void restrictedAction() {
Secure.checkAccess();
...
}

No, there is no simple way to do this. You can check roles, but not connected user, visitor.
You would have to add #Before annotations and that is going to be a little complicated. Simply break up your controller into several controllers. It is by the way, functionnaly better to do it that way, rather than mix up public/private methods.

Related

MVC5 Authentication: Authorize attribute on every controller or base controller

I have been doing a lot of research on the best way to secure my MVC 5 application.
We have one Web.csproj with many WebAPI Controllers and also an MVC site with two areas - one for Admin and then the public facing website.
After reading this article which states that the Base Controller is best way, I decided to go with that approach.
However, I am personally not OK with the use of base controllers (see this stackoverflow answer for some of my reasoning).
So, given that I am using MVC 5 (ASP.Net Identity and OWIN Authentication) - can anyone shed some light on the pros and cons of each approach?
The current practice in MVC 5 is to apply the AuthorizeAttribute as a Global filter, and open up individual Actions/Controllers with the AllowAnonymousAttribute
So in App_Start\FilterConfig.cs add the following lines:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
... existing filters
// use the [AllowAnonymous] attribute to open up individual Actions/Controllers
filters.Add(new System.Web.Mvc.AuthorizeAttribute());
filters.Add(new RequireHttpsAttribute());
}
note: for good measure I have also added the RequireHttpsAttribute as every authenticated request with ASP.Net Identity carries the auth cookie, which is vulnerable to Man In The Middle attacks if carried over regular HTTP.
I would always use a base controller, for more reasons than just authentication and authorization...
To get to your question, what we ended up doing was rolling our own custom Authorisation Attributes with complex rules that all inherit from AuthorizeAttribute. Its pretty simple, all you do is inherit from the given attribute and then overwrite the OnAuthorization and AuthorizeCore methods.
Generally, all our controllers do not allow anon access, based on our baseController class. From there it gets as complicated as needed. But it always makes sense to use a base class for things like this and build on top of that. If you ever need to make a very wide system change quickly you tap it into the baseClass and thats it.

Best practice securing GWTP application

I am working on application using GWT platform, and now i want to add security part. What is the best practice to do this?
My requirements for security are:
having user authorities;
hide some places from users without required authorities;
hide some elements on page from users without required authorities;
secure server side from unauthorized requests;
comfortable managing all of this things (like in spring using annotations or something like this )
having user authorities;
Model your users with permission atribute, like
private int user_type;
hide some places from users without required authorities;
Use the concept of Gate Keeper
A Gate Keeper is Singleton that obligates you to inherit a method called
boolean canReveal()
Using this, you can call server and search for user permission, then reveal or not the presenter called.
If a Presenter need security, just add #UseGateKeeper on it Proxy interface, like:
SomePresenter extends Presenter<V,P>{
#UseGateKeeper(YourGateKeeper.class)
SomePresenterProxy extends ProxyPlace{}
}
This will block users without some permission to access a presenter.
hide some elements on page from users without required authorities;
A good question, I've never seen this type of security in GWTP Projects. But you can always use Widget.setVisible(false) ;D, but I don't know if gwtp has a good practice for this.
secure server side from unauthorized requests;
GWTP GWTP makes it possible to link each of your ActionHandlers with a server-side ActionValidator that determines whether or not the current client can execute the action
You can hide some server calls using ActionValidator's.
read this
comfortable managing all of this things (like in spring using annotations or something like this)
As you can see, many of this security concepts use Annotations and other's stuff to manage easily your Application.

In which layer should Specification Pattern objects be "new'ed up"?

So, I've looked at some posts about the Specification Pattern here, and haven't found an answer to this one yet.
My question is, in an n-layered architecture, where exactly should me Specifications get "newed" up?
I could put them in my Service Layer (aka, Application layer it's sometimes called... basically, something an .aspx code-behind would talk to), but I feel like by doing that, I'm letting business rules leak out of the Domain. If the Domain objects are accessed some other way (besides the Service Layer), the Domain objects cannot enforce their own business rules.
I could inject the Specification into my Model class via constructor injection. But again, this feels "wrong". I feel like the only thing that should be injected into Model classes are "services", like Caching, Logging, dirty-flag tracking, etc... And if you can avoid it, to use Aspects instead of littering the constructors of the Model classes with tons of service interfaces.
I could inject the Specification via method injection (sometimes referred to as "Double Dispatch"???), and explicitly have that method encapsulate the injected Specification to enforce its business rule.
Create a "Domain Services" class, which would take a Specification(s) via constructor injection, and then let the Service Layer use the Domain Service to coordinate the Domain object. This seems OK to me, as the rule enforced by the Specification is still in the "Domain", and the Domain Service class can be named very much like the Domain object it's coordinating. The thing here is I feel like I'm writing a LOT of classes and code, just to "properly" implement the Specification pattern.
Add to this, that the Specification in question requires a Repository in order to determine whether it's "satisfied" or not.
This could potentially cause performance problems, esp. if I use constructor injection b/c consuming code could call a property that perhaps wraps the Specification, and that, in turn is calling the database.
So any ideas/thoughts/links to articles?
Where is the best place to new up and use Specifications?
Short answer:
You use Specifications mainly in your Service Layer, so there.
Long answer:
First of all, there's two questions here:
Where should your specs live, and where should they be new'd up?
Just like your repository interfaces, your specs should live in the domain layer, as they are, after all, domain specific. There's a question on SO that discusses this on repository interfaces.
Where should they be new'd up though? Well, I use LinqSpecs on my repositories and mostly ever have three methods on my repository:
public interface ILinqSpecsRepository<T>
{
IEnumerable<T> FindAll(Specification<T> specification);
IEnumerable<T> FindAll<TRelated>(Specification<T> specification, Expression<Func<T, TRelated>> fetchExpression);
T FindOne(Specification<T> specification);
}
The rest of my queries are constructed in my service layer. That keeps the repositories from getting bloated with methods like GetUserByEmail, GetUserById, GetUserByStatus etc.
In my service, I new-up my specs and pass them to the FindAll or FindOne methods of my repository. For example:
public User GetUserByEmail(string email)
{
var withEmail = new UserByEmail(email); // the specification
return userRepository.FindOne(withEmail);
}
and here is the Specification:
public class UserByEmail : Specification<User>
{
private readonly string email;
public UserByEmail(string email)
{
this.email = email;
}
#region Overrides of Specification<User>
public override Expression<Func<User, bool>> IsSatisfiedBy()
{
return x => x.Email == email;
}
#endregion
}
So to answer your question, specs are new'd up in the service layer (in my book).
I feel like the only thing that should be injected into Model classes
are "services"
IMO you should not be injecting anything into domain entities.
Add to this, that the Specification in question requires a Repository
in order to determine whether it's "satisfied" or not.
That's a code smell. I would review your code there. A Specification should definitely not require a repository.
A specification is an implementation check of a business rule. It has to exist in the domain layer full stop.
Its hard to give specifics on how you do this as every codebase is different, but any business logic in my opinion needs to be in the domain layer and nowhere else. This business logic needs to be completely testable and coupled loosely from UI, database, external services and other non-domain dependencies. So I would definitely rule out 1, 2, and 3 above.
4 is an option, at least the specification will live in your domain layer. However the newing up of specifications depends really again on the implementation. We usually use depencency injection, hence the newing up of pretty much all of our objects is performed via an IOC container and corresponding bootstrapping code (i.e. we usually wire the application fluently). However we would never directly link business logic directly to e.g. UI model classes and the like. We usually have contours/boundaries between things such as UI and domain. We usually define domain service contracts, which can then be used by outside layers such as the UI etc.
Lastly, my answer is assuming that the system you are working on is at least some way complex. If it is a very simple system, domain driven design as a concept is probably too over the top. However some concepts such as testability, readibility, SoC etc should be respected regardless of the codebase in my opinion.

Transparent authorization reliability

I need a gear for custom authorization in business logic classes. It has to be permissions based system, but I can not decide how to apply authorization rules to methods.
My first thought was to apply custom attributes to method
[NeedPermission("Users", PermissionLevel.Read)]
public IList<User> GetAllUsers()
{
// some code goes here
}
My business logic class has interface, so I can use, for example, Unity Interception behavior and check in runtime if current user has required permissions. And throw an exception if he has not.
But now I'm concerned about reliability of this method.
Usually the reference to business logic class injected by unity container. So there is no problem because it is configured to apply interface interception mechanism.
But what if some developer will instantiate my business logic class directly? Then no interception will be applied and he will be able to call any method even if current user has not permissions to make some actions or even he is not authenticated.
Also somebody can change unity container configuration, turn off Interception extension completly. Again my authorization system will not work.
I saw ASP .NET MVC is using similar mechanism for authorization. Authorization rule is applied only when request came by standard way (IController.Execute). I think this is not a problem in this case because end user of controller (web user) has no way to access controller class directly.
In my case end user of business logic is a programmer who develops front end and he can intentionally or unintentionally screw things - create instance of business logic class and call any methods.
What can you suggest me? How do you deal with this kind of problems?
Thank you.
The .NET Framework supports a mechanism for declarative permission verifications that does not depend on Unity interception or other "external" AOP. In order to take advantage of this, your attribute must inherit from System.Security.Permissions.CodeAccessSecurityAttribute. The System.Security.Permissions.PrincipalPermissionAttribute that is included in the BCL is an example of using this mechanism to evaluate user permissions. If it does not suit your needs, there's nothing stopping you from creating your own attribute that does.
If your constructors are internal and your objects instantiated from a factory, a developper won't be able to bypass your security by error.
If someone really, really wants to create your objets without the security, he could still do it using reflection, but this would have be pretty intentional to do so.

How do you override the WCF AuthenticationService IsLoggedIn() method?

I have three current thoughts on how to do this:
re-implement AuthenticationService, which uses lots of internal constructors and internal helpers,
implement custom IIdentity and IPrincipal types and somehow hook these into FormsAuthentication.
give up and roll my own.
The problem is that we've got web apps and fat client apps using authentication and storing cookies. However, logging out of a web app does not log out of a fat client app, and we have now way of forcing a refreshed cookie, atm.
Found what I needed. Use number 2, implement my own IIdentity, and then implement the FormsAuthentication_OnAuthenticate on Global.asax [1].
[1] http://msdn.microsoft.com/en-us/library/system.web.security.formsauthenticationmodule.aspx

Resources