Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ServiceStack authentication correctly in ASP.Net MVC controller

I'm having problem with getting ServiceStack [Authentication] attribute to work in ASP.Net MVC4 controller, pages / action methods with the attribute keep redirecting Users to the login page even after the login details are submitted correctly.

I've followed the SocialBootstrapApi example, with the difference being that all the authentication web service calls are made from the controllers:

this.CreateRestClient().Post<RegistrationResponse>("/register", model);

Other things that I've done so far:

  • Use my own user session implementation subclassing AuthUserSession (not too different from the example, but using my own implementation of User table)
  • Inherit ServiceStackController on my BaseController, overriding the default login URL
  • Enable Auth feature in AppHost with my user session implementation

Registration does work, user auth logic works (even though the session does not persist), and I can see the ss-id and ss-pid cookies in the request.

So my complete list of questions:

  1. How do I make the [Authenticate] attribute work (or, what did I do wrong)?
  2. How do I save and reuse the user session in an MVC controller? At the moment this.UserSession is always null.
  3. How do I logout a user? this.CreateRestClient().Get<AuthResponse>("/auth/logout"); does not seem to work.

Update 1:
The session cookies (ss-id and ss-pid) gets created when I attempt to load the secured page (ones with [Authenticate] attribute), before any credentials get submitted. Is this the expected behaviour?

Update 2:
I can see that the session is saved in MemoryCacheClient, however trying to retrieve it in the base controller via this.Cache.Get<CustomUserSession>(SessionKey) returns null (where SessionKey is like: urn:iauthsession:1)

like image 525
hhandoko Avatar asked Aug 21 '12 22:08

hhandoko


People also ask

How authentication and authorization works in ASP.NET MVC?

Windows Authentication is used in conjunction with IIS authentication. The Authentication is performed by IIS in one of three ways such as basic, digest, or Integrated Windows Authentication. When IIS authentication is completed, then ASP.NET uses the authenticated identity to authorize access.

How authorization attribute works in MVC?

If a user is not authenticated, or doesn't have the required user name and role, then the Authorize attribute prevents access to the method and redirects the user to the login URL. When both Roles and Users are set, the effect is combined and only users with that name and in that role are authorized.


2 Answers

After much fiddling around, apparently the way to hook ServiceStack authentication is to call the AuthService via:

try {
    authResponse = AuthService.Authenticate(new Auth{ UserName = model.UserName, Continue = returnUrl, Password = model.Password });
} catch (Exception ex) {
    // Cut for brevity...
}

and NOT authResponse = this.CreateRestClient().Post<AuthResponse>("/auth/credentials", model);!

Where AuthService is defined in the base controller as:

public AuthService AuthService
{
    get
    {
        var authService = ServiceStack.WebHost.Endpoints.AppHostBase.Instance.Container.Resolve<AuthService>();
        authService.RequestContext = new HttpRequestContext(
            System.Web.HttpContext.Current.Request.ToRequest(),
            System.Web.HttpContext.Current.Response.ToResponse(),
            null);

        return authService;
    }
}

Everything else (incl. session) works correctly now.

like image 99
hhandoko Avatar answered Sep 20 '22 10:09

hhandoko


You can find how it could be done in the ServiceStack Use Cases repository. The following example is based on MVC4 but works perfectly for MVC3 either: CustomAuthenticationMvc.

like image 40
desunit Avatar answered Sep 19 '22 10:09

desunit