i have written a small grails webapp. I am using milton.io to access some content via webdav.
So webdav is still working and i am able to put, get, delete files - and so on.
But now i want to add authentication and authorization. And here is the problem:
The Resource Interface gives me 2 methods:
Object authenticate(String user, String password);
boolean authorise(Request request, Request.Method method, Auth auth);
So my Resource classes implements the Resource Interface, but the method authenticate is never called by the framework. Do i have to implement Auth Basic by my self?
My knowledge about milton is very poor. May be i forgot something, cause my webdav client (e.g. cadaver) never asks for a username / password.
Thanks for any help
Peter Waver
Signature of my Resource Classes:
class SResource implements GetableResource, PropFindableResource, Resource, DeletableResource, MoveableResource, ReportableResource, CopyableResource
class SFileResource extends SResource implements ReplaceableResource
class SFolderResource extends SResource implements PutableResource, MakeCollectionableResource, CollectionResource
And here is the builder to get the HttpManager
class SMiltonConfig implements MiltonConfigurator {
protected HttpManagerBuilder builder;
protected List<Initable> initables;
protected HttpManager httpManager;
public SMiltonConfig(){
try {
// Attempt to use Enterprise edition build if available
Class builderClass = Class.forName("io.milton.ent.config.HttpManagerBuilderEnt");
builder = (HttpManagerBuilder) builderClass.newInstance();
println ("load Ent. HTTP Manager")
} catch (InstantiationException ex) {
builder = new HttpManagerBuilder();
println ("load Std. HTTP Manager")
} catch (IllegalAccessException ex) {
println ("load Std. HTTP Manager")
builder = new HttpManagerBuilder();
} catch (ClassNotFoundException ex) {
println ("load Std. HTTP Manager")
builder = new HttpManagerBuilder();
}
}
#Override
public HttpManager configure(Config arg0) throws ServletException {
ResourceFactory rf = new SResourceFactory();
builder.setMainResourceFactory(rf);
checkAddInitable(initables, builder.getMainResourceFactory());
httpManager = builder.buildHttpManager();
for( Initable i : initables ) {
i.init(config, httpManager);
}
return httpManager;
}
#Override
public void shutdown() {
httpManager.shutdown()
for( Initable i : initables ) {
i.destroy(httpManager);
}
}
private void checkAddInitable(List<Initable> initables, Object o) {
if( o instanceof Initable) {
initables.add((Initable)o);
} else if( o instanceof List ) {
for( Object o2 : (List)o) {
checkAddInitable(initables, o2);
}
}
}
}
And here the ResourceFactory
class SResourceFactory implements ResourceFactory {
def fileSystemService
public SResourceFactory(){
println "loading resource Factory"
def ctx = ServletContextHolder.servletContext.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
fileSystemService = ctx.fileSystemService
}
#Override
public Resource getResource(String host, String strPath)
throws NotAuthorizedException, BadRequestException {
SResource sfr
sfr = fileSystemService.getFolderByPath(strPath)
return sfr
}
}
If you need Basic Auth - you have to enable it. So add the following line to the config method of the SMiltonConfig Class.
builder.setEnableOptionsAuth(true); // enables auth
builder.setEnableBasicAuth(true); // optional
Here'S an example of the Resource authorise Method
#Override
public boolean authorise(Request r, Method m, Auth a) {
return a != null;
}
Hope it helps
Florian Pfann
Related
I have to do some extra logic layer on existing classes. I'm using autofac.
The project is Windows service having also Kestrel server. Program.cs e.g.
void Main(string[] args) {
var customQueue = new CustomQueue();
var someClass = new SomeClass(customQueue);
var randomClass = new RandomClass();
// do some logic here with using declared instances
var server = new Server(someClass, randomClass);
server.Start();
}
And here is the Server.cs
class Server {
private IWebHost _host;
public Server(SomeClass cls, RandomClass cls1) {
// set to fields
}
void Start() {
_host = new WebHostBuilder()
.UseKestrel()
.ConfigureServices(services =>
{
services.AddAutoFac(); // first as per doc in order to scaffold 'ConfigureContainer'?
services.AddSingleton(someClass); // fields
services.AddSingleton(randomClass); // fields
})
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration(...)
.ConfigureLogging(...);
.UseStartup<Startuo>()
.Build();
_host.StartAsync();
}
}
Startup.cs
public class Startup
{
public ILifetimeScope AutofacContainer { get; private set; }
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// create a container-builder and register dependencies
var builder = new ContainerBuilder();
// populate the service-descriptors added to `IServiceCollection`
// BEFORE you add things to Autofac so that the Autofac
// registrations can override stuff in the `IServiceCollection`
// as needed
builder.Populate(services);
builder.RegisterType<SomeClass>()
.As<ISomeClass>()
.EnableInterfaceInterceptors()
.InterceptedBy(typeof(SomeClassInterceptor));
builder.Register(_ => new SomeClassInterceptor());
AutofacContainer = builder.Build();
return new AutofacServiceProvider(AutofacContainer);
}
}
And last SomeClassInterceptor.cs
public class SomeClassInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
try
{
invocation.Proceed();
if (invocation.ReturnValue is Task taskResult)
{
taskResult.ContinueWith(
t =>
{
Console.WriteLine("OOHH YEAHH");
}, TaskContinuationOptions.None);
}
else
{
Console.WriteLine("WOW");
}
}
catch (Exception ex)
{
Console.WriteLine("EXCEPTIOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNN");
}
}
}
I've tried with Named and Typed registration with having Intercept(...) attribute but still no success. Nothing gets triggered.
Also ISomeClass is inheriting other interfaces, I've tried setting .As<>() also with those but no.
What am I missing?
In order to let the interceptor works. The class should be build by Autofac.
services.AddAutofac();
services.AddSingleton(someClass);
services.AddSingleton(randomClass);
In your case you configure Autofac using the AddAutofac method then add SomeClass as a singleton using the AddSingleton which will override the Autofac configuration. There is no way that Autofac can inject the interceptor in it.
If you want to register SomeClass as singleton you should register it using the SingleInstance() method
builder.RegisterType<SomeClass>()
.As<ISomeClass>()
.SingleInstance()
.EnableInterfaceInterceptors()
.InterceptedBy(typeof(SomeClassInterceptor));
I am constructing my own AuthorizingRealm subclass, and am having a tough time wiring it up to my SecurityManager.
The essence of my realm:
public class MyRealm extends AuthorizingRealm {
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
try {
// My custom logic here
} catch(Throwable t) {
System.out.println(t.getMessage());
}
SimpleAuthenticationInfo authn = new SimpleAuthenticationInfo(new MyUser(), "somePassword");
return authn;
}
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
try {
// My custom logic here
} catch(Throwable t) {
System.out.println(t.getMessage());
}
return new SimpleAuthorizationInfo();
}
}
Then in my 'shiro.ini':
# =======================
# Shiro INI configuration
# =======================
[main]
myRealm = com.me.myapp.security.MyRealm
Then in my Driver class/main method (that I'm using for testing):
public class Driver {
public static void main(String[] args) {
Driver d = new Driver();
d.test();
}
public void test() {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
UsernamePasswordToken token = new UsernamePasswordToken("", "");
token.setRememberMe(true);
System.out.println("Shiro props:");
System.out.println(securityManager.getProperties());
Subject currentUser = SecurityUtils.getSubject()
try {
currentUser.login(token)
println "I think this worked!"
} catch (UnknownAccountException uae) {
println "Exception: ${uae}"
} catch (IncorrectCredentialsException ice) {
println "Exception: ${ice}"
} catch (LockedAccountException lae) {
println "Exception: ${lae}"
} catch (ExcessiveAttemptsException eae) {
println "Exception: ${eae}"
} catch (AuthenticationException ae) {
println "Exception: ${ae}"
}
}
}
When I run this I get:
Shiro props:
[class:class org.apache.shiro.mgt.DefaultSecurityManager, cacheManager:null, subjectFactory:org.apache.shiro.mgt.DefaultSubjectFactory#6a2b8b42, authorizer:org.apache.shiro.authz.ModularRealmAuthorizer#50c3d082, realms:[com.me.myapp.security.MyRealm#67ae303a], subjectDAO:org.apache.shiro.mgt.DefaultSubjectDAO#5ce06503, rememberMeManager:null, authenticator:org.apache.shiro.authc.pam.ModularRealmAuthenticator#1007d798, sessionManager:org.apache.shiro.session.mgt.DefaultSessionManager#72db4460]
Exception: org.apache.shiro.authc.AuthenticationException: Authentication failed for token submission [org.apache.shiro.authc.UsernamePasswordToken - , rememberMe=true]. Possible unexpected error? (Typical or expected login exceptions should extend from AuthenticationException).
So it looks like its reading my shiro.ini because its picking up the correct realm, but MyRealm doesn't do anything except stub out dummy users that should authenticated regardless of the username/password supplied. Any ideas as to where I'm going awry?
add this to your shiro.ini: securityManager.realms = $myRealm then in your Driver class
UsernamePasswordToken token = new UsernamePasswordToken("", "somePassword");
instead of an empty passowrd.
I think this worked!
I have not done this myself, but here are a couple of things you can try:
If you don't need authorization logic, consider subclassing AuthenticatingRealm instead of AuthorizingRealm
In method doGetAuthenticationInfo, consider using this code:
SimpleAuthenticationInfo authn = new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), "myRealm");
You seem to have created a Realm properly but have not told the SecurityManager that it is one the realms to be used. In that way, it is just another object created in the main section of shiro.ini.
To tell Shiro's SecurityManager that it needs to use myRealm as a Realm, you need to add this to your shiro.ini:
securityManager.realms = $myRealm
I am receiving an error when using NServiceBus 4.0.3 with NHibernate 3.3.1 when it's trying to process a message
INFO NServiceBus.Unicast.Transport.TransportReceiver [(null)] <(null)> - Failed to process message
Autofac.Core.Registration.ComponentNotRegisteredException: The requested service 'NServiceBus.Impersonation.ExtractIncomingPrincipal' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.
at NServiceBus.Unicast.Transport.TransportReceiver.ProcessMessage(TransportMessage message) in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Unicast\Transport\TransportReceiver.cs:line 353
at NServiceBus.Unicast.Transport.TransportReceiver.TryProcess(TransportMessage message) in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Unicast\Transport\TransportReceiver.cs:line 233
at NServiceBus.Transports.Msmq.MsmqDequeueStrategy.ProcessMessage(TransportMessage message) in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Transports\Msmq\MsmqDequeueStrategy.cs:line 262
at NServiceBus.Transports.Msmq.MsmqDequeueStrategy.Action() in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Transports\Msmq\MsmqDequeueStrategy.cs:line 197
2013-08-30 09:35:02,508 [9] WARN NServiceBus.Faults.Forwarder.FaultManager [(null)] <(null)> - Message has failed FLR and will be handed over to SLR for retry attempt: 1, MessageID=8aaed043-b744-49c2-965d-a22a009deb32.
I think it's fairly obvious what that I need to implement or register an "ExtractIncomingPrincipal", but I can't seem to find any documentation on how or whether there is a default one that I can use. I wouldn't have figured that I would have had to register any of the NServiceBus-related services as many of them are already being registered in my IoC implementation.
As requested, here is the EndpointConfig and supporting code I have currently:
[EndpointSLA("00:00:30")]
public class EndpointConfig : IConfigureThisEndpoint, AsA_Server, IWantCustomInitialization {
public void Init() {
Configure.With().ObjectBuilderAdapter().UseInMemoryTimeoutPersister().UseInMemoryGatewayPersister().InMemorySagaPersister().InMemorySubscriptionStorage();
}
}
//public class PrincipalExtractor : ExtractIncomingPrincipal {
// public IPrincipal GetPrincipal(TransportMessage message) {
// return Thread.CurrentPrincipal;
// }
//}
public class ObjectBuilderAdapter : IContainer {
readonly IDependencyInjector injector;
public ObjectBuilderAdapter(IDependencyInjectionBuilder dependencyInjectionBuilder) {
injector = dependencyInjectionBuilder.Create(); //This method does all the common service registrations that I am trying to re-use
//injector.RegisterType<ExtractIncomingPrincipal, PrincipalExtractor>();
}
public void Dispose() {
injector.Dispose();
}
public object Build(Type typeToBuild) {
return injector.Resolve(typeToBuild);
}
public IContainer BuildChildContainer() {
return new ObjectBuilderAdapter(new DependencyInjectorBuilder());
}
public IEnumerable<object> BuildAll(Type typeToBuild) {
return injector.ResolveAll(typeToBuild);
}
public void Configure(Type component, DependencyLifecycle dependencyLifecycle) {
injector.RegisterType(component);
}
public void Configure<T>(Func<T> component, DependencyLifecycle dependencyLifecycle) {
injector.RegisterType(component);
}
public void ConfigureProperty(Type component, string property, object value) {
if (injector is AutofacDependencyInjector) {
((AutofacDependencyInjector)injector).ConfigureProperty(component, property, value);
} else {
Debug.WriteLine("Configuring {0} for property {1} but we don't handle this scenario.", component.Name, property);
}
}
public void RegisterSingleton(Type lookupType, object instance) {
injector.RegisterInstance(lookupType, instance);
}
public bool HasComponent(Type componentType) {
return injector.IsRegistered(componentType);
}
public void Release(object instance) { }
}
public static class Extensions {
public static Configure ObjectBuilderAdapter(this Configure config) {
ConfigureCommon.With(config, new ObjectBuilderAdapter(new DependencyInjectorBuilder()));
return config;
}
}
I removed the IWantCustomInitialization (left over from something else I had tried earlier) interface implementation on the class and my service now processes the message. There are errors still (relating to trying to connect to Raven [even though I thought I am using everything in-memory), but it's processing the message.
In my MVC 2 project, I originally used Ninject 2 and wrote this version of the NinjectControllerFactory:
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel kernel = new StandardKernel(new HandiGamerServices());
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
try
{
if (controllerType == null)
{
return base.GetControllerInstance(requestContext, controllerType);
// return null;
}
}
catch (HttpException ex)
{
if (ex.GetHttpCode() == 404)
{
IController errorController = kernel.Get<ErrorController>();
((ErrorController)errorController).InvokeHttp404(requestContext.HttpContext);
return errorController;
}
else
{
throw ex;
}
}
return (IController)kernel.Get(controllerType);
}
Of most importance is the retrieval of my ErrorController, which allows me to gracefully handle a multitude of HTTP errors.
The problem is that I upgraded to the MVC 2 extension via Nuget, so a NinjectControllerFactory is already provided. Would it be possible to use my own override of GetControllerInstance? If so, how?
I do exactly this, and for precisely the same reason. In Global.asax.cs, I add this to my OnApplicationStarted override (declared virtual in NinjectHttpApplication):
ControllerBuilder.Current.SetControllerFactory(
new MyControllerFactory(ControllerBuilder.Current.GetControllerFactory()));
This means you're creating your own controller factory, but providing it with the default implementation to do the heavy lifting.
Then define your controller factory like so:
public class MyControllerFactory : IControllerFactory
{
private IControllerFactory defaultFactory;
public MyControllerFactory(IControllerFactory defaultFactory)
{
this.defaultFactory = defaultFactory;
}
public IController CreateController(RequestContext requestContext, string controllerName)
{
try
{
var controller = defaultFactory.CreateController(requestContext, controllerName);
return controller;
}
catch (HttpException e)
{
// Pasted in your exception handling code here:
if (ex.GetHttpCode() == 404)
{
IController errorController = kernel.Get<ErrorController>();
((ErrorController)errorController).InvokeHttp404(requestContext.HttpContext);
return errorController;
}
else
{
throw ex;
}
}
}
public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)
{
return defaultFactory.GetControllerSessionBehavior(requestContext, controllerName);
}
public void ReleaseController(IController controller)
{
defaultFactory.ReleaseController(controller);
}
}
As you can see, we're just using the default (Ninject) controller factory for most purposes unless it can't find the page. For obtaining the error controller, you can either pass in the kernel as you were already doing, or just call defaultFactory.CreateController using the error controller name.
I'm trying to get windows workflows working, and I've become a little stumped.
I've gotten a single workflow working, but now I am trying to do something a little more complex: start a workflow, where each activity itself contains a workflow. (Picture something like the main program starts the activities "Input, logic, and output", and then each of those have additional activities like "prompt user, get input, etc.")
I've had it working fine, with the example from here (http://msdn.microsoft.com/en-us/magazine/gg535667.aspx), when I am not passing any parameters from the main program to the activites. My question is, how exactly does the 'Variables' and 'metadata.SetVariablesCollection' work in the NativeActivity, and how to I get the parameters to the low level activities?
This is what I am currently trying:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Collections.ObjectModel;
using System.Activities.Statements;
namespace Project1
{
internal class MainProgram
{
internal static void Main(string[] args)
{
try
{
var act = new SimpleSequence();
act.Activities.Add((Activity)(new WriteSomeText()));
act.Activities.Add((Activity)(new WriteSomeText()));
act.Activities.Add((Activity)(new WriteSomeText()));
act.Variables.Add(new Variable<string> ("stringArg", "TEXT"));
WorkflowInvoker.Invoke(act);
}
catch (Exception ex)
{
System.Console.WriteLine("EXCEPTION: {0}", ex);
}
}
public class WriteSomeText : CodeActivity
{
[RequiredArgument]
public InArgument<string> stringArg { get; set; }
protected override void Execute(CodeActivityContext context)
{
string output = context.GetValue(stringArg);
System.Console.WriteLine(output);
}
}
public class SimpleSequence : NativeActivity
{
Collection<Activity> activities;
Collection<Variable> variables;
Variable<int> current = new Variable<int> { Default = 0 };
public Collection<Activity> Activities
{
get
{
if (this.activities == null)
this.activities = new Collection<Activity>();
return this.activities;
}
set
{
this.activities = value;
}
}
public Collection<Variable> Variables
{
get
{
if (this.variables == null)
this.variables = new Collection<Variable>();
return this.variables;
}
set
{
this.variables = value;
}
}
protected override void CacheMetadata(NativeActivityMetadata metadata)
{
metadata.SetChildrenCollection(this.activities);
metadata.SetVariablesCollection(this.variables);
metadata.AddImplementationVariable(this.current);
}
protected override void Execute(NativeActivityContext context)
{
if (this.Activities.Count > 0)
context.ScheduleActivity(this.Activities[0], onChildComplete);
}
void onChildComplete(NativeActivityContext context, ActivityInstance completed)
{
int currentExecutingActivity = this.current.Get(context);
int next = currentExecutingActivity + 1;
if (next < this.Activities.Count)
{
context.ScheduleActivity(this.Activities[next], this.onChildComplete);
this.current.Set(context, next);
}
}
}
}
}
This ends up throwing the following exception:
EXCEPTION: System.Activities.InvalidWorkflowException: The following errors were encountered while processing the workflow tree:
'WriteSomeText': Value for a required activity argument 'stringArg' was not supplied.
'WriteSomeText': Value for a required activity argument 'stringArg' was not supplied.
'WriteSomeText': Value for a required activity argument 'stringArg' was not supplied.
at System.Activities.Validation.ActivityValidationServices.ThrowIfViolationsExist(IList`1 validationErrors)
at System.Activities.Hosting.WorkflowInstance.ValidateWorkflow(WorkflowInstanceExtensionManager extensionManager)
at System.Activities.Hosting.WorkflowInstance.RegisterExtensionManager(WorkflowInstanceExtensionManager extensionManager)
at System.Activities.WorkflowApplication.EnsureInitialized()
at System.Activities.WorkflowApplication.RunInstance(WorkflowApplication instance)
at System.Activities.WorkflowApplication.Invoke(Activity activity, IDictionary`2 inputs, WorkflowInstanceExtensionManager extensions, TimeSpan timeout)
at System.Activities.WorkflowInvoker.Invoke(Activity workflow, TimeSpan timeout, WorkflowInstanceExtensionManager extensions)
at System.Activities.WorkflowInvoker.Invoke(Activity workflow)
at Project1.MainProgram.Main(String[] args) in c:\users\user\documents\visual studio 2010\Projects\ModelingProject1\Project1\MainProgram.cs:line 25
I know, I only pass 1 parameter, but the exception still says that I am missing 3 parameters. I am missing something as to how to do this properly.
You're correctly declaring stringArg as an InArgument but you're not passing any value to it when calling it inside SimpleSequence.
You can pass something using the constructor, while constructing the all activity itself, like this:
public class WriteSomeText : CodeActivity
{
[RequiredArgument]
public InArgument<string> stringArg { get; set; }
public WriteSomeText(string stringArg)
{
this.stringArg = stringArg;
}
protected override void Execute(CodeActivityContext context
{
string output = context.GetValue(stringArg);
System.Console.WriteLine(output);
}
}
// Calling the activity like this:
internal static void Main(string[] args)
{
var act = new SimpleSequence()
{
Activities =
{
new WriteSomeText("hello"),
new WriteSomeText("world"),
new WriteSomeText("!")
}
};
WorkflowInvoker.Invoke(act);
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
Also notice that is a best practice to use the constructor to initialize collections:
public SimpleSequence()
{
activities = new Collection<Activity>();
variables = new Collection<Variable>();
}
This way is even more intuitive to initialize the activity:
var act = new SimpleSequence()
{
Activities =
{
new WriteSomeText("hello"),
new WriteSomeText("world"),
new WriteSomeText("!")
},
Variables =
{
new Variable<int>("myNewIntVar", 10),
// ....
}
};
EDIT:
There are a couple of other ways to approach the problem. This is your best friend while starting in the WF4 world.
Check WF\Basic\CustomActivities\Code-Bodied for a little push with this particular case.