本文介绍了ServiceStack验证与现有数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找ServiceStack,我试图了解如何在服务中使用与BasicAuthentication现有的数据库。我想生成公钥(用户名)和密钥(密码),并提出,在现有的用户记录。然后,用户将它传递给他们的要求沿ServiceStack终点。

I've been looking at ServiceStack and I'm trying to understand how to use BasicAuthentication on a service with an existing database. I would like to generate a public key (username) and secret key (password) and put that in an existing user record. The user would then pass that to the ServiceStack endpoint along with their request.

什么我需要在ServiceStack栈来实现得到这个工作?

我已经看过两个IUserAuthRepository和CredentialsAuthProvider基类,它看起来像我应该落实在我现有的数据库表的顶部IUserAuthRepository。

I have looked at both IUserAuthRepository and CredentialsAuthProvider base class and it looks like I should just implement IUserAuthRepository on top of my existing database tables.

我也想弄清楚什么是最低限度我应该实现得到验证工作。我不会使用该服务来添加或更新用户访问服务,而是使用单独的Web应用程序。

I am also trying to figure out what is the bare minimum I should implement to get authentication working. I will not be using the service to Add or Update user access to the Service, but instead using a separate web application.

任何帮助和过去的经验是极大的赞赏。

Any help and past experiences are greatly appreciated.

推荐答案

进行身份验证现有的数据库(在通过一把umbraco / ASP.NET会员制这种情况下)的例子。 1)创建AuthProvider(原谅冗长的代码,并注意你不必重写TryAuthenticate过,这是在这里做检查,如果用户是特定的应用一把umbraco别名的成员):

Example of authenticating against an existing database (in this case via Umbraco/ASP.NET membership system). 1) Create your AuthProvider (forgive the verbose code, and note you don't have to override TryAuthenticate too, this is done here to check if the user is a member of specific Umbraco application aliases):

using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Security;

using ServiceStack.Configuration;
using ServiceStack.Logging;
using ServiceStack.ServiceInterface;
using ServiceStack.ServiceInterface.Auth;
using ServiceStack.WebHost.Endpoints;

using umbraco.BusinessLogic;
using umbraco.providers;

public class UmbracoAuthProvider : CredentialsAuthProvider
{

    public UmbracoAuthProvider(IResourceManager appSettings)
    {
        this.Provider = "umbraco";
    }

    private UmbracoAuthConfig AuthConfig
    {
        get
        {
            return EndpointHost.AppHost.TryResolve<UmbracoAuthConfig>();
        }
    }

    public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
    {
        ILog log = LogManager.GetLogger(this.GetType());
        var membershipProvider = (UsersMembershipProvider)Membership.Providers["UsersMembershipProvider"];

        if (membershipProvider == null)
        {
            log.Error("UmbracoAuthProvider.OnAuthenticated - NullReferenceException - UsersMembershipProvider");
            session.IsAuthenticated = false;
            return;
        }

        MembershipUser user = membershipProvider.GetUser(session.UserAuthName, false);

        if (user == null)
        {
            log.ErrorFormat(
                "UmbracoAuthProvider.OnAuthenticated - GetMembershipUser failed - {0}", session.UserAuthName);
            session.IsAuthenticated = false;
            return;
        }

        if (user.ProviderUserKey == null)
        {
            log.ErrorFormat(
                "UmbracoAuthProvider.OnAuthenticated - ProviderUserKey failed - {0}", session.UserAuthName);
            session.IsAuthenticated = false;
            return;
        }

        User umbracoUser = User.GetUser((int)user.ProviderUserKey);

        if (umbracoUser == null || umbracoUser.Disabled)
        {
            log.WarnFormat(
                "UmbracoAuthProvider.OnAuthenticated - GetUmbracoUser failed - {0}", session.UserAuthName);
            session.IsAuthenticated = false;
            return;
        }

        session.UserAuthId = umbracoUser.Id.ToString(CultureInfo.InvariantCulture);
        session.Email = umbracoUser.Email;
        session.DisplayName = umbracoUser.Name;
        session.IsAuthenticated = true;
        session.Roles = new List<string>();
        if (umbracoUser.UserType.Name == "Administrators")
        {
            session.Roles.Add(RoleNames.Admin);
        }

        authService.SaveSession(session);
        base.OnAuthenticated(authService, session, tokens, authInfo);
    }

    public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
    {
        ILog log = LogManager.GetLogger(this.GetType());
        var membershipProvider = (UsersMembershipProvider)Membership.Providers["UsersMembershipProvider"];

        if (membershipProvider == null)
        {
            log.Error("UmbracoAuthProvider.TryAuthenticate - NullReferenceException - UsersMembershipProvider");
            return false;
        }

        if (!membershipProvider.ValidateUser(userName, password))
        {
            log.WarnFormat("UmbracoAuthProvider.TryAuthenticate - ValidateUser failed - {0}", userName);
            return false;
        }

        MembershipUser user = membershipProvider.GetUser(userName, false);

        if (user == null)
        {
            log.ErrorFormat("UmbracoAuthProvider.TryAuthenticate - GetMembershipUser failed - {0}", userName);
            return false;
        }

        if (user.ProviderUserKey == null)
        {
            log.ErrorFormat("UmbracoAuthProvider.TryAuthenticate - ProviderUserKey failed - {0}", userName);
            return false;
        }

        User umbracoUser = User.GetUser((int)user.ProviderUserKey);

        if (umbracoUser == null || umbracoUser.Disabled)
        {
            log.WarnFormat("UmbracoAuthProvider.TryAuthenticate - GetUmbracoUser failed - {0}", userName);
            return false;
        }

        if (umbracoUser.UserType.Name == "Administrators"
            || umbracoUser.GetApplications()
                          .Any(app => this.AuthConfig.AllowedApplicationAliases.Any(s => s == app.alias)))
        {
            return true;
        }

        log.WarnFormat("UmbracoAuthProvider.TryAuthenticate - AllowedApplicationAliases failed - {0}", userName);

        return false;
    }
}

public class UmbracoAuthConfig
{

    public UmbracoAuthConfig(IResourceManager appSettings)
    {
        this.AllowedApplicationAliases = appSettings.GetList("UmbracoAuthConfig.AllowedApplicationAliases").ToList();
    }

    public List<string> AllowedApplicationAliases { get; private set; }

}



2)注册通过平时APPHOST配置法提供商:

2) Register provider via usual AppHost Configure method:

    public override void Configure(Container container)
    {
        // .... some config code omitted....

        var appSettings = new AppSettings();
        AppConfig = new AppConfig(appSettings);
        container.Register(AppConfig);

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

        container.Register<ISessionFactory>(c => new SessionFactory(c.Resolve<ICacheClient>()));

        this.Plugins.Add(
            new AuthFeature(
                // using a custom AuthUserSession here as other checks performed here, e.g. validating Google Apps domain if oAuth enabled/plugged in.
                () => new CustomAuthSession(),
                new IAuthProvider[] { new UmbracoAuthProvider(appSettings)
                                    }) {
                                          HtmlRedirect = "/api/login"
                                       });

}



3)现在可以对现有的一把umbraco数据库@ yourapidomain认证/认证/一把umbraco,用一把umbraco管理用户/访问API。无需额外的实现用户密钥/秘密或BasicAuthentication,除非你真的想....

3) Can now authenticate against existing Umbraco database @ yourapidomain/auth/umbraco, using Umbraco to manage users/access to API. No need to implement extra user keys/secrets or BasicAuthentication, unless you really want to....

这篇关于ServiceStack验证与现有数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 00:07