ServiceStack authentication with MVC Controllers

2019-07-04 01:25发布

问题:

I've followed the samples in SocialBootstrapAPi for ServiceStack but I don't get it how the redirects are wired up. When I go to the Secured controller being unauthenticated I get redirected back to the index page. I was unable to replicate the behaviour in my own application. Did not find where this wirings are done - can't find them in SocialBootstrapApi's web.config?

I've inherited from the ServiceStackController<AuthUserSession> and put [Authenticate] on my base controller. This is the error I get:

[NullReferenceException: Object reference not set to an instance of an object.]
   ServiceStack.ServiceInterface.SessionExtensions.SessionAs(ICacheClient cache, IHttpRequest httpReq, IHttpResponse httpRes) +90
   ServiceStack.Mvc.ServiceStackController.SessionAs() +64
   ServiceStack.Mvc.ServiceStackController`1.get_UserSession() +36
   ServiceStack.Mvc.ServiceStackController`1.get_AuthSession() +5
   ServiceStack.Mvc.ExecuteServiceStackFiltersAttribute.OnActionExecuting(ActionExecutingContext filterContext) +97

This is what I have in the AppHost.cs file:

        //Enable Authentication
        ConfigureAuth(container);

        //Register In-Memory Cache provider. 
        //For Distributed Cache Providers Use: PooledRedisClientManager, BasicRedisClientManager or see: https://github.com/ServiceStack/ServiceStack/wiki/Caching
        container.Register<ICacheClient>(new MemoryCacheClient());
        container.Register<ISessionFactory>(c => 
            new SessionFactory(c.Resolve<ICacheClient>()));

ConfigureAuth() is similar to the SocialBootstrapApi sample (not exactly the same but close) - I don't think there's something missing here.

So how does this work?

回答1:

Promoting comment to an answer, per OPs request:

Did you set your IoC for your MVC controller? ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));



回答2:

Look at this question to see how to change the HtmlRedirect used by ServiceStack's Authentication.

You may also find the CustomAuthenticationMvc project in ServiceStack UseCases more useful since it only focuses on Authentication in MVC.