用户身份验证,角色和权限

时间:2016-03-02 14:24:44

标签: servicestack

在AppHost模块中,我打开/创建一个基于NHibernate的身份验证存储库(使用“ServiceStack.Authentication.NHibernate”模块),然后创建一个默认用户:

HibernateFactory = RepoDatabaseFactory(typeof(ServiceStack.Authentication.NHibernate.UserAuthMap).Assembly);       NHSession = HibernateFactory.OpenSession();       container.Register(NHSession);       NHibernateUserAuthRepository UserRepository = new NHibernateUserAuthRepository(HibernateFactory);       container.Register(UserRepository);       CurrentSessionContext.Bind(NHSession);

  var Authorization = UserRepository.GetUserAuthByUserName("miga");

  if (Authorization == null)
    {
    UserRepository.CreateUserAuth(
      new UserAuth
        {
        UserName = "miga",
        FirstName = "xxxxxx",
        LastName = "xxxxxx",
        Address = "xxxxxxxxxxxx",
        PostalCode = "xxxxxx",
        City = "xxxxxx",
        Country = "xxxxx",
        Gender = "xxxxx",
        PhoneNumber = "xxxxxx",
        Email = "xxxxxxx",
        Roles = new List<string> { RoleNames.Admin },
        Culture = "xxxxx"
        },
      "xxxxxx");
    }

  container.Register<ICacheClient>(new MemoryCacheClient());

  UserRepository.InitSchema();

RepoDatabaseFactory是:

public NHibernate.ISessionFactory RepoDatabaseFactory(Assembly AuthAssembly)
  {
  var Configuration = Fluently.Configure()
   .Database(MsSqlConfiguration.MsSql2012.ConnectionString(ConnString).UseReflectionOptimizer()).Mappings(m =>
     {
       m.FluentMappings.AddFromAssembly(AuthAssembly);
     })
   .CurrentSessionContext("web")
   .BuildConfiguration();

  var Exporter = new SchemaExport(Configuration);
  Exporter.Execute(false, false, false);

  var SessionFactory = Configuration.BuildSessionFactory();

  return (SessionFactory);
  }

在某种程度上这是有效的;即创建相关表(“UserAuth”,“UserAuth_Permissions”,“UserAuth_Roles”,“UserOAuthProvider”和“UserOAuthProvider_Items”)。如上所述创建用户“miga”时,您会注意到“new UserAuth”语句中的“Roles = new List {RoleNames.Admin}”行。随后,上面的用户数据实际上被添加到“UserAuth”表中,但“Admin”角色被添加到“UserAuth_Roles”表中,正如我所期望的那样。手动在“UserAuth_Roles”表中插入新记录(包含“miga”用户的用户ID和admin角色名称 - 例如1,“Admin”)仍然 - 它出现 - 不向“miga”用户提供“管理员“角色:

使用以下片段:

  var Client = new RestClient("http://localhost:42147/");
  Client.Authenticator = new HttpBasicAuthenticator("miga", "xxxxxxxx");
  var Request = new RestRequest("assignroles", Method.POST);
  Request.RequestFormat = DataFormat.Json;
  Request.AddBody(new { UserName = "Sally", Roles = "Write" });
  var Response = Client.Post<AssignRoleResponse>(Request);

我收到“无效角色”消息的授权错误。所以我的问题基本上是如何让它在NHibernate上下文中工作?

0 个答案:

没有答案