When validating domainclasses in Grails, it uses the DefaultMessageCodesResolver from Spring to "extend" the set of i18n-keys to try and lookup. I would like to simplify this, and have therefore implemented my own SimpleMessageCodesResolver by extending the MessageCodesResolver interface.
However, I can't seem to make Grails pick up on this. I've declared it as a custom dependency injection, trying to override, what Spring normally does:
messageCodesResolver(SimpleMessageCodesResolver)
I still see the DefaultMessageCodesResolver when looking at the domain object... Any ideas how to make this work?
I belive your custom dependency injection should be:
defaultMessageCodesResolver(SimpleMessageCodesResolver)
MessageCodesResolver is an interface, but not spring bean as DefaultMessageCodesResolver instance is.
Related
Please note: Although my specific question at hand involves the Grails Shiro plugin, I believe this to be a core Grails question at heart. And so any battle weary Grails veteran should be able to answer this, regardless of their experience with Grails Shiro.
Using the Grails Shiro plugin (via grails shiro-quick-start) produces a Shiro realm class under grails-app/realms. For instance, running:
grails shiro-quick-start --prefix=com.example.me.myapp.Mongo
...will produce:
myapp/
grails-app/
realms/
com/
me/
myapp/
MongoDbRealm.groovy
Where MongoDbRealm is the Shiro realm.
package com.example.me.myapp
class MongoDbRealm {
FizzClient fizzClient // How to inject?
BuzzClient buzzClient // How to inject?
FooFactory fooFactory // How to inject?
// lots of auth-centric, generated code here...
}
Let's pretend that MongoDbRealm is very complicated and needs to be injected with lots of complicated objects such as service clients and factories, etc. How do I properly inject MongoDbRealm?
Will #PostConstruct work here? Can I inject Grails services into it like I do with controllers? Something else?
Again, I would imagine that dependency injection works the same here (with Grails Shiro and my MongoDbRealm) as in any other class defined under grails-app. I just don't understand how grails-app/* dependency injection works.
Plugins that support defining classes under grails-app typically do so by defining a new type of artifact, and specify an ArtefactHandler implementation to manage that. The Grails ArtefactHandlerAdapter class implements that interface and provides a lot of common functionality, so that's often used, and is used in the plugin's RealmArtefactHandler class.
Dependency injection would be configured in the newInstance method. You can see where I did this for one of my plugins here. Since the Shiro plugin doesn't override that method from the base class, it looks like dependency injection isn't supported.
Note that using #PostConstruct (or implementing InitializingBean) would work if the realm classes were registered as Spring beans, but it doesn't look like that's the case in this plugin.
I try to avoid using the Holders class since in most cases it's straightforward to use DI instead of pulling in dependencies explicitly, but it looks like you will need to use that approach here, e.g. fizzClient = Holders.applicationContext.fizzClient (assuming that is registered as the "fizzClient" bean).
We're using the Grails spring security plugin:
http://grails.org/plugin/spring-security-core
I simply want to change the default access decision manager from the default AffirmativeBased to UnanimousBased. I do not see it documented anywhere in the plugin manual:
http://grails-plugins.github.io/grails-spring-security-core/docs/manual/
Does anyone know if it's possible to change this?
I added one additional voter, "myVoter" which is detected and working fine.
grails.plugins.springsecurity.voterNames = [
'myVoter', 'authenticatedVoter', 'roleVoter',
]
Based on Burt Beckwith's "Hacking the Grails Spring Security Plugin" [http://www.slideshare.net/gr8conf/hacking-the-grails-spring-security-plugins], it should be possible to simply provide a different implementation of the accessDecisionManager bean. Something like this:
accessDecisionManager(org.springframework.security.access.vote.UnanimousBased)
in resources.groovy
When I tried this, I had trouble with the constructor syntax in the bean definition. The access decision manager wants a list of voters in the constructor and I couldn't quote figure out how to get my voters defined in config.groovy as parameters to the constructor. I was about to derive my own decision manager (with parameterless constructor) from UnanimousBased when I stumbled upon the source code for AuthenticatedVetoableDecisionManager in the Grails Spring Security Plugin. This class splits the voters in half... anything deriving from AuthenticatedVoter will immediately fail if any are denied (e.g. AUTHENTICATED_FULLY family), but all other voters will pass if any are granted (e.g. RoleVoter). I wanted the AuthenticatedVoter functionality for my custom voter so I simply derived from AuthenticatedVoter (making sure to override all of the interface methods so I didn't accidentally get any base class functionality) and stuck with the default decision manager.
I am using spring security annotations in my project. There are scenarios when i want to invoke security-less version of the annotated object. Spring by default creates a security-enabled proxy of the annotated object and uses it for autowiring in the code, is there any way that i can achieve this using spring ?
An obvious way to do this would be to manually create proxy classes corresponding to each class for which i want this feature have those methods annotated and the implementation of these methods just delegate it to the actual object.
As an option in a case of JDK proxies you can get actual bean at runtime:
MyBean proxy;
if(AopUtils.isJdkDynamicProxy(proxy)) {
MyBean actualInstance = (MyBean) ((Advised)proxy).getTargetSource().getTarget()
}
actualInstance.doSomethingSecured(); // no advice related to this method will be called
// so your security annotation will be ignored (transactions, cache, and everething that requires AOP too...)
But from architectural point of view approach with manual proxies looks less error phrone (except if you absolutely sure that you do not need security and all another possible aspects too).
You can improve readability using generics:
MyBean actualInstance = extractProxyTarget(proxy, proxy.getClass());
actualInstance.doSomethingSecured();
I'm using the resources.groovy to declare a service e.g.
aService(com.foo.OrganizationService)
so that I can tie aService to my controllers instead of using organizationService which could change in the future.
I've noticed that the OrganizationService doesn't get treated special like other services "not" declared in the resources.groovy. For example it doesn't get injected with grailsApplication, and likely a hibernateSession etc and other things I've not hit yet....
Now, I know I can manually wire in stuff to my service but I'd rather not have to maintain that...
Is there a special way to declare a service in the resources.groovy so that gets treated like another service that grails loads up?
TIA
The short answer to your question is "no".
Under the covers, Grails services are driven by some intelligent code that is referencing a specific location and expecting certain properties.
Viewing the source code (especially around the ServicesGrailsPlugin.groovy) is a good way to see the "magic" in how these are wired together.
Is there a reason you wouldn't want to use a bonafide Grails service to solve your problem? If you are expecting things like a grailsApplication, it seems like that use is pretty specific to Grails and would be a good candidate for porting over to a "true" Grails service.
Good luck!
So I've come full circle on this. This is a timing problem. Where services haven't been grails initialized yet.
Basically when you use the resources.groovy to do service wiring you run the risk of using a Service that might initialize itself e.g. afterPropertiesSet method or static initializers that use grails services (log, hibernate session, ..) that haven't been injected yet.
So... What I've turned to instead is to create my own BeanBuilder in a BootStrap.groovy file.
BeanBuilder builder = new BeanBuilder(grailsApplication.parentContext)
def bb = builder.beans {
LoginListener(com.foo.LoginListener) {
springSecurityService = ref("springSecurityService")
userService = ref("userService")
}
}
bb.registerBeans(grailsApplication.mainContext)
I have a custom attribute class derived from AuthorizationAttribute, which performs custom security on controller actions. The OnAuthorizationCore method depends on various other components (e.g. DAL) in order to ajudicate whether a user can invoke an action.
I'm using Autofac for dependency injection. The ExtensibleActionInvoker claims to be able to perform property injection on action filters. Setting an attribute's properties at runtime (which seems like a bad idea) will work in a simple unit test, but in a busy, multi-threaded web server it's bound to go wrong, and so this idea seems like an anti-pattern. Hence this question:
If my AuthorizationAttribute depends on other components in order to work correctly, what it the right [architecture] pattern in order to achieve this?
i.e. AuthorizationAttribute depends on IUserRepository... how should this relationship be resolved?
The ExtensibleActionInvoker claims to be able to perform property injection on action filters.
Correct - but don't confuse action filters with the attributes that might not implement them. The cleanest way to approach this in ASP.NET MVC is to split responsibilities, even though the MVC framework allows you to combine them.
E.g., use a pair of classes - an attribute class that holds data only:
// Just a regular old attribute with data values
class SomeAttribute : Attribute { ... }
And a filter that has dependencies injected:
// Gets dependencies injected
class SomeFilter : IActionFilter { ... }
SomeFilter just uses the typical approach of getting the SomeAttribute attribute from the controller or action method via GetCustomAttributes() to do whatever work is needed.
You can then use ExtensibleActionInvoker to wire up the filter:
builder.RegisterControllers(...).InjectActionInvoker();
builder.RegisterType<ExtensibleActionInvoker>().As<IActionInvoker>();
builder.RegisterType<SomeFilter>().As<IActionFilter>();
It might be a little more code than you'd write using the attribute-as-filter approach, but the quality of the code will be better in the long run (e.g. by avoiding the limitations of attributes and the awkwardness of the Service Locator solutions.)
I would seem that the easiest way to achieve this is to bite the bullet and accept a dependency on autofac itself. While a dependency on the IoC is in itself an anti-pattern, it's somewhat more pallatable. You can implement a property as follows:
public class UserAuthorizeAttribute : AuthorizeAttribute
{
public IUserRepository CurrentUserService
{
get
{
var cpa = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance;
var cp = cpa.ContainerProvider;
return cp.RequestLifetime.Resolve<IUserRepository>();
}
}
}
...
There's no straight-forward way to do this prior to MVC2. There is an interesting technique detailed here: http://www.mattlong.com.au/?p=154. I'd suggest using the Common Service Locator to abstract over this and locate your DI container.
If you're using MVC 3 then you can use MVC Service Location
Constructor injection seems to be impossible w/o changing way of filter registration.
Even in Asp.Net Mvc3:
One place where dependency injection has been difficult in the past is inside the filter attributes themselves. Because the .NET framework runtime is actually responsible for creating these attribute instances, we cannot use a traditional dependency injection strategy.
So - next best thing is property injection (Mvc3 provides some support for that out of the box).
Here's a how to for doing that manually.
I personally use MvcExtensions. I'm fine with registering them in different way. Here's usage.
Another thing You might want to investigate is MvcTurbine project. In contrast to MvcExtensions project which is more general - MvcTurbine is primarily for providing dependency injection support.