I am creating third part login system for my web application using Oauth2 and have to support various third party Oauth2.0 service provider like
Gmail
Facebook
MSN
Yahoo
Twitter
I have already working code for these.Each service provider have a certain set of configuration which need to be created before starting Oauth process.I was thinking about using ServiceLocatorFactoryBean of Spring and create few services for each Oauth provider and based on what user has selected can fetch that specific service.
Is my approach is good enough or is it like a overuse / overcomplicated one
Edit
As per one answer, We can create a single bean with singleton scope and inject Map of required services to it so as we can fetch services from Map based on what user has selected, though approach is fine but won't that force us to load every services in Memory and no matter if we will use them or not, they will remain in Memory
Using ServiceLocatorFactoryBean is a way to do it and solves the problem of getting a bean (implementing an interface) based on a String key lookup.
The javadoc says that the class is meant mostly for injecting prototype scoped beans, but also works for other scopes altough they don't advise it.
The javadoc gives an indication that is not the use case for which the ServiceLocatorFactoryBean was created, another solution that gives the same work is to just create a singleton bean OAuthServiceProvider that returns the correct service depending on a string using just some if/elses or a map.
In the long run it would more readable, the use of the ServiceLocatorFactoryBean seems not to buy us much compared to that.
Related
I recently readed carefully about the spring mvc 3 beans scope, specifically the web ones(session, request and global session) and i have some doubdts:
If i have a controller, why should i annotate him with other scope aside of singleton? I mean, the controllers are supossed to handle the requests and instantiate the view resources of all the app, so why give them a, for instance, session scope? what is the advantage of do that?
Is advisable making the services layer session scoped?
And finally, is there any convention or good practices that dictates where and when is more convenient the use each one of the web scopes? If there is, can somebody provides me the link or information about it? Not necessary convention or good practices, also your experience about it.
Thanks very much.
I mean, the controllers are supossed to handle the requests and
instantiate the view resources of all the app, so why give them a, for
instance, session scope?
In an average web application, you have various objects that exist on a per-session basis. Example can be user profile, or some kind of cabinet, or wallet, etc.
To be able to use those objects in service, every time you should get from session, and pass through the service chain. Instead of doing this, of course it is better to have those available in your service, without a need to pass it explicitly.
Really good example (in practice) you can find here.
An ideal practical example of request scope bean is HttpServletRequest, which should be unique obviously for each request, therefore it is request scoped and created for each request.
From my experience, without any explicit need for a case, you don't need to bother yourself with changing scopes. It is not without reason that default scope is Singleton, it is by purpose - because in most of the applications and basic scenarios you need beans as singleton. However as your main concern was with Session and Request scopes, the above examples are cases which you need often in web application.
In MVC, a ModelValidatorProvider is instantiated and called to validate a model on each request. This means that in a DI environment, it can take dependencies on objects scoped within a single request, such as a Unit of Work or Database context. In Web API, this appears to have been significantly changed. Instead of being instantiated per-request, the ModelValidatorProvider appears to be long-lived and instantiated within the application startup. The WebAPI then caches the results from the ModelValidatorProvider per-type, meaning that the ModelValidator cannot take any dependencies from DI.
I am trying to implement my ModelValidator to use a factory using a Service Locator (please, no automatic 'anti-pattern' comments!). This would allow me to construct an internal validator object within each request, which would be able to take dependencies from the container. However, I cannot get hold of a Dependency Resolver or container scoped to the current request from within this ModelValidator which is essentially scoped as a Singleton. I've tried to use GlobalConfiguration.Configuration.DependencyResolver, but this only returns globally-scoped services (from the root scope, also mentioned here)
I'm working in Autofac, so an autofac-specific solution would be suitable (e.g. MVC has AutofacDependencyResolver.Current, which internally uses DependencyResolver.GetService). There is no equivalent available in the WebAPI integration, presumably because of the reason mentioned above where the global DependencyResolver only returns globally-scoped services.
The reason I'm trying to do this (as well as for my own use) is to implement the Web API integration for FluentValidation, which currently does not exist. There have been two attempts so far, but neither of these handle the Dependency Injection issue and instead result in a single static ModelValidator.
Things I've tried so far:
Using GlobalConfiguration.Configuration.DependencyResolver (returns objects from the root scope)
Taking a dependency on Func<IComponentContext> (always returns the root context)
In an answer which has since been removed, it was suggested to remove IModelValidatorProvider service from the Web API config. This had to be done using reflection since the interface and the implementing classes are all defined as internal, but it did make the validators work better (because the ModelValidator was constructed per request). However, there is a significant performance hit to doing it this way due to the use of reflection to check for validators on the model and every property it has, so I don't want to take this option.
Filip W's answer suggests using HttpRequestMessage to get the Dependency Scope, but I've not found anything such as HttpRequestMessage.Current which would provide access to this object from within a long-lived object - if that could be achieved I believe everything would fall into place.
To get current dependency scope, you have to use (surprise, surprise :) GetDependencyScope() of the current HttpRequestMessage (more about which you can read up on MSDN) instead of GlobalConfiguration.
I blogged about Web API per-request dependency scope a while ago - that should be helpful.
This seems like it's basic Spring 101 stuff, but I can't seem to find the correct way to do this. The situation is as follows; in my web app there is a single entry point which is a controller that handles users coming from an outside system. The transfer is just a POST request with a bunch of associated information pertaining to that user. Apon entry, I need to create a new User bean and load it with that users information. Additionally, when the user hits a view which triggers some service, I need for that service to be able to access the appropriate User bean instance.
The first way to do this that came to mind was to have a UserManager service which would create a new instance of User, fill it w/ data, and then register it in the Spring container with the username as the bean name. Then when a service is invoked, the service would do something like Factory.getBean(username) to find the appropriate User instance. The problem I see here is that I'm losing the link between the user & which User bean belongs to them. Additionally, I'd like to avoid having the user carry the bean around in the session if at all possible. Is this where I am supposed to be using Spring AOP & proxies?
What is the typical Spring pattern for solving this type of situation?
So it is now many weeks later (since asking this question), and consequently my knowledge level has been expanding exponentially, so I figured I might as well answer my question for anyone who might find it helpful (not to mention the question wasn't very clear to begin with).
The basic answer is: use proxies. Since a singleton is only instantiate 1 time, you cant inject another class which has a shorter lifespan, eg. session scope. For those requiring more information, checkout stateful vs stateless beans. More or less what I ended up doing is this... the services contain STATELESS code for manipulating data (think verbs; RegisterUserSvc, AddPartSvc, etc). The data which these services manipulate is stateful. For instance, each user has a own copy of their own data object, lets say TodoListBean, which is in a different state for each user.
So how does a service, AddTodoItemService for instance, manipulate this data? This is where the proxy comes into play. When instantiated, the AddTodoItemService gets injected with a proxy for the TodoListBean, instead of the actual object. That way when the service needs to access the TodoListBean the container will serve up the a TodoListBean out of the current users session, and therefore the service will be operating on the correct bean (based on which user invoked the service), instead of doing something silly like having numerous copies of the service included in each users session scope.
Search did not give me a hint, how can i behave with the following situation:
I'd love to have 2 OSGI implementations of the same interface: one is regular, the other should work (be active/present/whatever) on the given time period (f.e for Christmas weeks :))
The main goal is to call the same interface without specifying any flags/properties/without manual switching of ranking. Application should somehow switch implementation for this special period, doing another/regular job before and after :)
I'm a newbie, maybe i do not completely understand OSGI concept somewhere, sorry for that of give me a hint or link, sorry for my English.
Using Felix/Equinox with Apache Aries.
The publisher of a service can register and unregister that service whenever it likes using the normal API. If it chooses then it can do so according to some regular schedule.
If there is another service instance that is available continuously, then the consumer of the service will sometimes see two instances of the service and sometimes see one. When there is only one instance available then it is trivial to get only that instance. When there are two instances then you need a way to ensure you get your "preferred" instance. The SERVICE_RANKING property is a way to do this. The getService method of a normal ServiceTracker will always return the higher ranked service, so this would appear to satisfy your requirement.
I have yet to see an OSGI container that at a framework level supports date/time based availability of services.
If I were you I would simply drop a proxy service in front of the two interface implementations and put the service invocation based on date logic in there.
I don't believe there is any framework support for what you are asking for.
If you are intent on avoiding service filters, you might try this.
Implement a PolicyService. This service is in charge of deciding which instance of your service should be registered at a given point in time. When its time for the policy service to switch implementations, it just uses the register/unregister apis as usual. You policy service implementation can read in a config file that specifies the date range to service implementation mapping. This will allow you to add new behavior by modifying your config file and installing a new bundle with the new service.
I agree with Neil that a service should only publish itself if it can actually be invoked. My solution to this problem would be to have all service producers be dependent on a "time constraint dependency". Whilst such a dependency is not available in the standard dependency frameworks (like Declarative Services, Blueprint, iPOJO) it is easily implemented with the Apache Felix Dependency Manager, which allows you to create your own types of dependencies. Note that writing such a new dependency once is some work, but if this is a core piece of your application I think it's worth it. Service consumers would not require any special logic, they would simply invoke the service that was there.
Ok, what i have finally done...
Implemented a common dispatcher bundle - and call any of services only thru it (therefore cron is not needed, when call is on-demand)
When dispatcher obtains request - it searches for interface in its own cache and -
When there are >1 service with the same ranking and both are equal (registered) - then
Dispatcher resolves needed service via own written #TimigPolicy annotation with "from" and "to" fields
For the given server new datetime() - dispatcher returns proper service instance
Much work, i should say :) But works nearly perfect :)
Thanks everybody for giving me hints, it was really helpful!!!
What I am looking to accomplish is a filter (or similar) that would handle the authentication model for my Spring MVC application. My application is also hosted on Google App Engine.
The authentication on this application can tend to be very dynamic and the permissions are not something that would fit cleanly into a predefined Role structure. These permissions would be tied to the different action methods on my controllers. Ideally I would like to be able to annotate these permissions but I am open for other suggestions.
I am finding that there is not very much information around on how to accomplish this. Ideally I would like to be able to intercept the call to my controller actions and be able to read off the annotations and handle accordingly. What I am hoping is that someone here has a little bit more knowledge on Spring MVC and where I can inject some custom code, and would be able to point me in the right direction.
I would still use Spring Security to do this. It may not have a class that 100% fits your login scheme, but that's what inheritance is for. Write your own. You can easily get rid of the ROLE based DecisionManager and make it fit your paradigm.
Based on your comments have you checked out the MethodInterceptor in Spring? It creates a Proxy that will intercept calls to any method on the proxied class and allow you to run or disallow the method based on any code you want. In Spring Security there is an AbstractSecurityInterceptor, but I find it very hard to use and for most access decisions I think it's overkill.
So I would use Spring Security to authenticate the user (and populate the SecurityContext) and then use interceptors to wall off access to methods in your controllers that you want protected.