Single entry/exit point design in JSF 2.0 - jsf-2

I want to design my application in JSF 2.0 with single entry/exit point for all the requests and responses so that they can be routed through a single managedBean/controller.
The purpose of having this design is to catch my all business exceptions at common place and also it would be easy for me to check for the validation of session for each new request.
One of the option I see is ServletFilter but I am not sure if this would be the best approach with JSF 2.0.

The purpose of having this design is to catch my all business exceptions at common place
Just implement a custom JSF ExceptionHandler.
and also it would be easy for me to check for the validation of session for each new request.
This makes no sense. The container does it already by itself. I believe that you're concretely asking to check a session attribute representing the logged-in user. For that a servlet Filter is indeed the most sensible approach. Some may opt to use a JSF PhaseListener for that, but this is tight coupled to JSF requests and does not kick in on other requests.

Related

Downside of using my own Autofac LifetimeScope in MVC application

I am writing MVC UI wrapper reusing legacy core libraries that were written down for desktop edition using Autofac for DI. The problem I am facing is, core libraries are working with Lifetime scope that I can't change while MVC requires InstancePerRequest.
So what happens is, in MVC, if I register my services for InstancePerRequest scope, they get disposed by core libraries before request completes. It makes MVC application unhappy.
I tried using LifeTimeScope for all services in MVC app too. Since Lifetime scope is shorter than Request life, it appears to work in MVC.
Is there any downside in this approach?
Note: In legacy code all the time services are being resolved manually, instead of being injected through constructor. Like:
using (var scope = IocContainer.BeginLifetimeScope())
{
var service = scope.Resolve<IMyService>();
return service.FindAll();
}
MVC will work with InstancePerLifetimeScope for services as noted in the documentation about sharing registrations across apps that have and apps that don't have request scopes.
I think there are going to be potentially two gotchas in your approach to creating your own lifetime scope. Whether you can live with them is very much app specific so you'll have to judge for yourself.
Problem 1: Early Disposal
In your example you show a factory or service IMyService being resolved, doing some work, and returning that work. At the end of the using statement the owning lifetime scope is getting disposed. That means IMyService will be disposed (if it's IDisposable) and any dependencies that IMyService requires will also be disposed. In the case of things like database contexts or connections, that well could mean the return value becomes invalid because you won't be able to update the values or read additional data against a disposed connection.
Problem 2: Singleton/Sharing Issues
Lifetime scopes are sometimes used to isolate units of work or sets of components that need shared context. For example, in MVC you only have one instance of the controller for the whole request - no matter how many times you resolve the controller object, for that request it'll be the same instance. You might see a similar thing with database connections - one connection from the pool allocated for an entire request lifetime.
By creating your own lifetime scope you are also creating a sort of logical unit of work. Any dependencies for IMyService will not be shared with the rest of the MVC request. In fact, it's more like that tiny lifetime scope is its own request or its own unit of work. No overlap.
General Resolution
As noted in the doc I linked to earlier, register things as InstancePerLifetimeScope if they need to be used in both MVC and non-MVC contexts and just let the MVC request semantics handle spinning up and disposal of scopes if possible.
If that won't work, it'll be up to you and your app code to figure out if you can live with the issues here or if you need to address them. If you need to address them, that, too, will be app specific so there isn't "guidance" to provide - you're on your own for that.

Should spring security method level annotations be applied at the controller layer or the service layer?

I have been using spring security with #PreAuthorize on my controller methods. My reasoning was that I wanted the authorization check to happen predictably in one layer, and as early as possible in the request. However, I just read the spring security 3 documentation, and saw that they recommend applying method level security on the service layer (but they don't say why).
My question is: should spring security method level annotations be applied at the controller layer or the service layer? (Or "both", or "it depends"?) More importantly: why?
"It depends" :). If your application has a service layer through which all your business logic is applied then that is usually a clean place to apply your security constraints and be certain that you haven't missed out any corner cases.
Web code is generally messier, there's more of it, it changes more rapidly and you may end up calling the same service methods from multiple places. Someone might add a new controller and forget to secure it properly. Alternatively you might have different types of clients calling the same services.
But it depends on how your application is structured and what your use cases are. You may have a good argument for why you want to secure a controller.
Think in terms of code reuse. Are you going to use your service elsewhere? Not just to feed your web tier?
We also reuse our services with jms bridges so we secure our service layer.
I think the Service is the better place to use it.
Despites some problems that #PreAuthorize could create on Controller and the Spring Security FAQ recommendation to put this kind of annotation on Service, I understand that the authorization for some action is more a business rule than a responsibility for the web tier.

Upshot/Knockout Architectural Best Practices - What is the preferred of method of limiting user access to functions exposed through the WebAPI?

A fundamental idea in implementing a single page application with Knockout and Upshot is that most of the data will received from and sent to the server in JSON format using AJAX.
On the server, we will expose a number of endpoints (using perhaps WebAPI and the DbDataController) to respond to requests from Upshot. These endpoints may provide general queries for data such as lists of clients, previous orders, account information, etc.
Obviously, it is not desirable for one client to be able view another clients account information, previous orders, or other private data.
What strategies or approaches be used to secure queries (and data) which are being requested from upshot (or other mechanism) to the server? (In other words, how do we make sure a user only has access to his own data?)
Are the strategies the same or different than those used in a normal ASP.NET MVC application--namely use of the Authorize attribute?
This is probably a very simple question, but I am still not clear on all the differences between WebAPI controllers and normally ASP.NET MVC controllers.
Thank for your help!
A custom authorize attribute is one possible way to implement this requirement. The only difference with standard ASP.NET MVC controllers is that you derive from System.Web.Http.AuthorizeAttribute instead of System.Web.Mvc.AuthorizeAttribute.

Fighting WIF for my own IPrincipal in an MVC app

I want to add Azure ACS to one of my sites, but having issues with all of the magic. I have an MVC app that uses a global filter to set a custom IPrincipal for the life of the request. The problem with the "add STS reference" methodology of WIF is that it short circuits this via an HttpModule.
This much I know: ACS bounces back to my Web app to the URL I configured it for, and that bounce is a POST with the normalized SAML token. I'm not interested in WIF setting cookies or any of that nonsense... I just want to get the claims I'm interested in from the POST and deal with setting auth stuff up myself from there. What's the workflow? The documentation is lousy, and focuses on the magic "right click" solution.
I think there is a really easy solution to your problem:
Register on the SecurityTokenValidated event of the WSFederationAuthenticationModule, set e.Cancel to true and start your sign in logic with the information provided in the ClaimsPrincipal property of the event args.
Setting Cancel to true on the event args prevents WIF from creating any IPrincipal or session, so you can handle this stuff by your self.
There are many examples of using WIF + MVC, with different levels of control. I would suggest these ones: http://claimsid.codeplex.com or the ones in the Identity Training Kit.
WIF pretty much takes care of everything for you. For deeper extensibility, you should check Vittorio's book.
Regarding: I just want to get the claims I'm interested in from the POST and deal with setting auth stuff up myself from there.
What would you want to do yourself that WIF doesn't? What functionality would you include in your IPrincipal that IClaimsPrincipal doesn't provide?
There are many knobs and levers in WIF with all kind of fine grain control. It would probably help if you share what is it you want to do.

Help with 2-part question on ASP.NET MVC and Custom Security Design

I'm using ASP.NET MVC and I am trying to separate a lot of my logic. Eventually, this application will be pretty big. It's basically a SaaS app that I need to allow for different kinds of clients to access. I have a two part question; the first deals with my general design and the second deals with how to utilize in ASP.NET MVC
Primarily, there will initially be an ASP.NET MVC "client" front-end and there will be a set of web-services for third parties to interact with (perhaps mobile, etc).
I realize I could have the ASP.NET MVC app interact just through the Web Service but I think that is unnecessary overhead.
So, I am creating an API that will essentially be a DLL that the Web App and the Web Services will utilize. The API consists of the main set of business logic and Data Transfer Objects, etc. (So, this includes methods like CreateCustomer, EditProduct, etc for example)
Also, my permissions requirements are a little complicated. I can't really use a straight Roles system as I need to have some fine-grained permissions (but all permissions are positive rights). So, I don't think I can really use the ASP.NET Roles/Membership system or if I can it seems like I'd be doing more work than rolling my own. I've used Membership before and for this one I think I'd rather roll my own.
Both the Web App and Web Services will need to keep security as a concern. So, my design is kind of like this:
Each method in the API will need to verify the security of the caller
In the Web App, each "page" ("action" in MVC speak) will also check the user's permissions (So, don't present the user with the "Add Customer" button if the user does not have that right but also whenever the API receives AddCustomer(), check the security too)
I think the Web Service really needs the checking in the DLL because it may not always be used in some kind of pre-authenticated context (like using Session/Cookies in a Web App); also having the security checks in the API means I don't really HAVE TO check it in other places if I'm on a mobile (say iPhone) and don't want to do all kinds of checking on the client
However, in the Web App I think there will be some duplication of work since the Web App checks the user's security before presenting the user with options, which is ok, but I was thinking of a way to avoid this duplication by allowing the Web App to tell the API not check the security; while the Web Service would always want security to be verified
Is this a good method? If not, what's better? If so, what's a good way of implementing this. I was thinking of doing this:
In the API, I would have two functions for each action:
// Here, "Credential" objects are just something I made up
public void AddCustomer(string customerName, Credential credential
, bool checkSecurity)
{
if(checkSecurity)
{
if(Has_Rights_To_Add_Customer(credential)) // made up for clarity
{
AddCustomer(customerName);
}
else
// throw an exception or somehow present an error
}
else
AddCustomer(customerName);
}
public void AddCustomer(string customerName)
{
// actual logic to add the customer into the DB or whatever
// Would it be good for this method to verify that the caller is the Web App
// through some method?
}
So, is this a good design or should I do something differently?
My next question is that clearly it doesn't seem like I can really use [Authorize ...] for determining if a user has the permissions to do something. In fact, one action might depend on a variety of permissions and the View might hide or show certain options depending on the permission.
What's the best way to do this? Should I have some kind of PermissionSet object that the user carries around throughout the Web App in Session or whatever and the MVC Action method would check if that user can use that Action and then the View will have some ViewData or whatever where it checks the various permissions to do Hide/Show?
What you propose will not work. Actions can be cached, and when they are, the action (and hence your home-rolled security) does not run. ASP.NET membership, however, still works, since the MVC caching is aware of it.
You need to work with ASP.NET membership instead of trying to reinvent it. You can, among other things:
Implement a custom membership provider or role provider.
Subtype AuthorizeAttribute and reimplement AuthorizeCore.
Use Microsoft Geneva/Windows Identity Foundation for claims-based access.
Also, I completely disagree with ChaosPandion, who suggests making structural changes in your code before profiling. Avoiding exceptions for "performance" reasons is absurd -- especially the idea that the mere potential to throw an exception for invalid users will somehow tank the performance for valid users. The slowest part of your code is likely elsewhere. Use a profiler to find the real performance issues instead of jumping on the latest micro-"optimization" fad.
The correct reason to avoid exceptions for authorizations is that the correct way to indicate an attempt at unauthorized access in a web app is to change the HTTP status code to 401 Unauthorized, not throwing an exception (which would return 500).
Define your authorisation requirements as a domain service so they are available to both the web and web service implementations.
Use an authorisation filter to perform your authorisation checks within the web application, this should be as simple as creating an auth request object and then passing it to your auth domain service.
If the authorisation fails, return the correct error - a 401 as indicated by Craig Stuntz.
ALWAYS authorise the action. If you can hide the link to unauthorised users - thats nice.
Simplify your views / view logic by writing a HtmlHelper extension method that can show / hide things based on a call to the auth domain service.
To use your authorisation service from the web service is simply a matter of constructing the auth request object from something passed in via the service message instead of from a cookie passed by the users browser.

Resources