Print Page | Close Window

Accessing Principal from VM

Printed From: IdeaBlade
Category: Cocktail
Forum Name: Community Forum
Forum Discription: A professional application framework using Caliburn.Micro and DevForce
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=4209
Printed Date: 22-Nov-2019 at 6:39am


Topic: Accessing Principal from VM
Posted By: gregweb
Subject: Accessing Principal from VM
Date Posted: 04-Jul-2013 at 2:39pm
I am populating Principal.Roles on the server.

However, it is not clear how to access the Principal on the client. Since Cocktail doesn't allow direct access to the EntityManager, I can't use EntityManager.Principal directly.

The only way I have found so far is to import the AuthenticationService into the viewModel, and then check AuthenticationService.Principal.

Am I doing this correctly?

Greg



Replies:
Posted By: mgood
Date Posted: 05-Jul-2013 at 9:05pm
Yes, that is the correct way. The principal should always be retrieved from the AuthenticationService. Instead of injecting the AuthenticationService, though, a cleaner approach is to create a UserService from which you can obtain the principal and other authorization stuff. The UserService uses the AuthenticationService to get the principal and for example cast it to the proper type if you use a custom principal. You can see it in TempHire, although TempHire doesn't actually use the UserService anywhere yet, but it shows the idea. The idea of this approach is to cleanly separate authentication from authorization.

The interface looks like this:

    public interface IUserService
    {
        bool IsLoggedIn { get; }

        UserPrincipal CurrentUser { get; }
    }

And the implementation like this. The custom AuthenticationService acts in both capacities, but from the consumption perspective, the two concerns are separated. 

    [Export(typeof(IAuthenticationService))]
    [Export(typeof(IUserService))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class TempHireAuthenticationService : AuthenticationService, IUserService
    {
#if FAKESTORE
        public TempHireAuthenticationService()
        {
            Configure(config => config.WithConnectionOptions(ConnectionOptions.Fake.Name));
        }
#endif

        #region IUserService Members

        public UserPrincipal CurrentUser
        {
            get { return Principal as UserPrincipal; }
        }

        #endregion

        protected override void OnLoggedIn()
        {
            base.OnLoggedIn();
            EventFns.Publish(new LoggedInMessage(CurrentUser));
        }

        protected override void OnLoggedOut()
        {
            base.OnLoggedOut();
            EventFns.Publish(new LoggedOutMessage());
        }
    }



Posted By: gregweb
Date Posted: 06-Jul-2013 at 6:21am
Great, thanks Marcel.



Print Page | Close Window