Custom auth token caching (SessionSecurityTokenCache override vs ITokenCacheRepository implementation) - session

When implementing a custom SessionSecurityTokenCache, is it better to extend/override SessionSecurityTokenCache or to implement ITokenCacheRepository? And why?
I have working examples of both and though there are a few minor differences (different method signatures, Get() on an ITokenCacheRepository implementation is requested less frequently than when overriding Get() on SessionSecurityTokenCache), they seem to do roughly the same thing. There is quite a lot of conflicting documentation out there, so am not sure which route to take with this.
Thanks

After a bit more reading on this, I found more info here which hints at when to derive from SessionSecurityTokenCache.
For web based scenarios (as opposed to the WCF-based scenarios) we can derive from PassiveRepositorySessionSecurityTokenCache. It allows for a simpler custom implementation because there are some methods of the WIF SessionSecurityTokenCache base class that aren't needed in web-based scenarios.

Related

Why does not exist the AspectJBeforeAdvice class?

In Spring about AOP/AspectJ exists the MethodInterceptor interface. It is used internally to decide if an #Aspect class must be called or not - really an advice method - according with a pointcut.
About its implementations exists (see the former link):
AspectJAfterAdvice
AspectJAfterThrowingAdvice
AspectJAroundAdvice
Question
What is the reason or Why does not exist the AspectJBeforeAdvice class?
This is not meant to be a conclusive answer, because I cannot speak for the Spring AOP team or speculate more than just a little bit about their design goals and motives. Insofar, this question is not a good fit for Stack Overflow, because it does not present a programming problem to be solved by a correct answer.
Anyway, actually it seems that the AOP Alliance's MethodInterceptor interface is not implemented for before advice types. Either it is not necessary or was an oversight. I think, however, that Spring AOP mostly revolves around the Advice interface and, where necessary, its subinterfaces BeforeAdvice and AfterAdvice. Moreover, all concrete advice types extend AbstractAspectJAdvice. This is a screenshot from my IDE:
Please note on the bottom of the picture, that MethodInterceptor itself extends Interceptor, which again intercepts Advice. So, Advice is the common denominator for all advice types, no matter if they are also MethodInterceptors or not.

Swift: Do protocols even have a real purpose?

I'm wondering why protocols are used in swift. In every case I've had to use one so far (UICollectionViewDelegate, UICollectionViewDataSource) I've noted that they don't even have to be added to the class declaration for my code to work. All they do is make it such that your class needs to have certain methods in it so that it can compile. Beats me why this is useful other then as a little post it note to help you keep track of what your classes do.
I'm assuming I'm wrong though. Would anyone care to point out why to me please?
A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol doesn’t actually provide an implementation for any of these requirements—it only describes what an implementation will look like.
So it's basically an interface, right?
You use an interface when you want to define a "contract" for your code. In most cases, the purpose of this is to enable multiple implementations of that contract. For example, you can provide a real implementation, and a fake one for testing.
Further Reading
Protocols
What is the point of an Interface?
It allows flexible linkage between parts of code. Once the protocol is defined it can be used by code that doesn't need to know what will be done when the methods are called or exactly what object (or struct or enum) is actually being used. An alternative approach could be setting callbacks or blocks but by using a protocol as complete set of behaviours can be grouped and documented.
Some other code will typically create the concrete instance and pass it to the code expecting the protocol (sometimes the concrete instance will pass itself). In some cases neither the implementation of the code using it need to be aware of each other and it can all be set up by some other code to keep it reusable and testable.
It might be possible to do this in some languages by duck typing which is to say that a runtime inspection could allow a object to act in such a context without particular declaration but this is probably not possible to do at compile time in all cases and it could also be error prone if worked out implicitly.

When should AcceptableViewModelSelector and Rendering / Response Strategies be used in Zend Framework 2?

If one needs JSON, XML, etc. als output format, one can use the AcceptableViewModelSelector Controller Plugin or / and (?) alternate rendering / response strategies.
When should the one and when the other (and when a combination) be applied?
Can/should they be combined?
Well, the Strategies are basically listeners. Listeners that give action depending on what kind of Model will be returned from your Controllers actions. If you return a ViewModel the PhpRendererStrategy will take place. If you return a JsonModel, the JsonStrategy will do it's stuff and if you return a FeedModel it's the FeedStrategy doing it's thing.
However the Strategies only apply if they are registered. So if you return a JsonModel without having the JsonStrategy registered, then nothing will happen.
The AcceptableViewModelSelector exists to provide an easier access and handling of different ModelFormats depending on the accept header. It helps to make things easier, no more, no less.
Strategies, you can also register your own one. There's modules out there that have a PdfStrategy which will render out a PDF-Document if you tell it to.
To tune this down a little to your question:
Strategies have been there from the start of ZF 2.0
The controller plugin AVMS only got in sometime within ZF 2.1 to just make things easier - that's why it's nothing more than a "plugin" ;)
If that doesn't really cover your question, i'm quite insecure on how to answer you ^^

When to use custom AccessDecisionManager (need a real use case)

i am just curious
when i will need to use a custom AccessDecisionManager
i need some use cases from your experience guys, if anyone have used it before, thanks.
The canonical example given in the Spring Security docs is for customizing voter tallies, like if a particular voter should be weighted more heavily than others.
You could also customize behavior based on, say, properties of the secured object passed in to the decide method, for example, based on existing business logic. (That could also be handled by a custom voter, or other means, but if it's generic it might be easier to put it in a decision manager.)
IMO it's relatively unusual to need extensive customization at this level, but others may have additional insight.
You also need a custom AcceessDecisionManager if you have complex object for a granted authority, spring default only supports string for that.

What are your best practices when using an MVC-based web framework?

A few general questions to those who are well-versed in developing web-based applications.
Question 1:
How do you avoid the problem of "dependency carrying"? From what I understand, the first point of object retrieval should happen in your controller's action method. From there, you can use a variety of models, classes, services, and components that can require certain objects.
How do you avoid the need to pass an object to another just because an object it uses requires it? I'd like to avoid going to the database/cache to get the data again, but I also don't want to create functions that require a ton of parameters. Should the controller action be the place where you create every object that you'll eventually need for the request?
Question 2:
What data do you store in the session? My understanding is that you should generally only store things like user id, email address, name, and access permissions.
What if you have data that needs to be analyzed for every request when a user is logged in? Should you store the entire user object in the cache versus the session?
Question 3:
Do you place your data-retrieval methods in the model itself or in a separate object that gets the data and returns a model? What are the advantages to this approach?
Question 4:
If your site is driven by a user id, how do you unit test your code base? Is this why you should have all of your data-retrieval methods in a centralized place so you can override it in your unit tests?
Question 5:
Generally speaking, do you unit test your controllers? I have heard many say that it's a difficult and even a bad practice. What is your opinion of it? What exactly do you test within your controllers?
Any other tidbits of information that you'd like to share regarding best practices are welcome! I'm always willing to learn more.
How do you avoid the problem of "dependency carrying"?
Good object oriented design of a BaseController SuperClass can handle a lot of the heavy lifting of instantiating commonly used objects etc. Usage of Composite types to share data across calls is a not so uncommon practice. E.g. creating some Context Object unique to your application within the Controller to share information among processes isn't a terrible idea.
What data do you store in the session?
As few things as is humanly possible.
If there is some data intensive operation which requires a lot of overhead to process AND it's required quite often by the application, it is a suitable candidate for session storage. And yes, storage of information such as User Id and other personalization information is not a bad practice for session state. Generally though the usage of cookies is the preferred method for personalization. Always remember though to never, ever, trust the content of cookies e.g. properly validate what's read before trusting it.
Do you place your data-retrieval methods in the model itself or in a separate object that gets the data and returns a model?
I prefer to use the Repository pattern for my models. The model itself usually contains simple business rule validations etc while the Repository hits a Business Object for results and transformations/manipulations. There are a lot of Patterns and ORM tools out in the market and this is a heavily debated topic so it sometimes just comes down to familiarity with tools etc...
What are the advantages to this approach?
The advantage I see with the Repository Pattern is the dumber your models are, the easier they are to modify. If they are representatives of a Business Object (such as a web service or data table), changes to those underlying objects is sufficiently abstracted from the presentation logic that is my MVC application. If I implement all the logic to load the model within the model itself, I am kind of violating a separation of concerns pattern. Again though, this is all very subjective.
If your site is driven by a user id, how do you unit test your code base?
It is highly advised to use Dependency Injection whenever possible in code. Some IoC Containers take care of this rather efficiently and once understood greatly improve your overall architecture and design. That being said, the user context itself should be implemented via some form of known interface that can then be "mocked" in your application. You can then, in your test harness, mock any user you wish and all dependent objects won't know the difference because they will be simply looking at an interface.
Generally speaking, do you unit test your controllers?
Absolutely. Since controllers are expected to return known content-types, with the proper testing tools we can use practices to mock the HttpContext information, call the Action Method and view the results to see they match our expectations. Sometimes this results in looking only for HTTP status codes when the result is some massive HTML document, but in the cases of a JSON response we can readily see that the action method is returning all scenario's information as expected
What exactly do you test within your controllers?
Any and all publicly declared members of your controller should be tested thoroughly.
Long question, longer answer. Hope this helps anyone and please just take this all as my own opinion. A lot of these questions are religious debates and you're always safe just practicing proper Object Oriented Design, SOLID, Interface Programming, DRY etc...
Regarding dependency explosion, the book Dependency Injection in .NET (which is excellent) explains that too many dependencies reveals that your controller is taking on too much responsibility, i.e. is violating the single responsibility principle. Some of that responsibility should be abstracted behind aggregates that perform multiple operations.
Basically, your controller should be dumb. If it needs that many dependencies to do its job, it's doing too much! It should just take user input (e.g. URLs, query strings, or POST data) and pass along that data, in the appropriate format, to your service layer.
Example, drawn from the book
We start with an OrderService with dependencies on OrderRepository, IMessageService, IBillingSystem, IInventoryManagement, and ILocationService. It's not a controller, but the same principle applies.
We notice that ILocationService and IInventoryManagement are both really implementation details of an order fulfillment algorithm (use the location service to find the closest warehouse, then manage its inventory). So we abstract them into IOrderFulfillment, and a concrete implementation LocationOrderFulfillment that uses IInventoryManagement and ILocationService. This is cool, because we have hidden some details away from our OrderService and furthermore brought to light an important domain concept: order fulfillment. We could implement this domain concept in a non-location-based way now, without having to change OrderService, since it only depends on the interface.
Next we notice that IMessageService, IBillingSystem, and our new IOrderFulfillment abstractions are all really used in the same way: they are notified about the order. So we create an INotificationService, and make MessageNotification a concrete implementation of both INotificationService and IMessageService. Similarly for BillingNotification and OrderFulfillmentNotification.
Now here's the trick: we create a new CompositeNotificationService, which derives from INotificationService and delegates to various "child" INotificationService instances. The concrete instance we use to solve our original problem will delegate in particular to MessageNotification, BillingNotification, and OrderFulfillmentNotification. But if we wish to notify more systems, we don' have to go edit our controller: we just have to implement our particular CompositeNotificationService differently.
Our OrderService now depends only on OrderRepository and INotificationService, which is much more reasonable! It has two constructor parameters instead of 5, and most importantly, it takes on almost no responsibility for figuring out what to do.

Resources