ServiceStack OAuth - registration instead login

蹲街弑〆低调 提交于 2019-11-30 16:11:49

The SocialBootstrap API project shows an example of handling the callback after a successful Authentication by overriding the OnAuthenticated() hook of its custom user session:

I've pulled out, rewrote some and highlighted some of the important bits:

public class CustomUserSession : AuthUserSession
{
    public override void OnAuthenticated(IServiceBase authService, 
                    IAuthSession session, 
                    IOAuthTokens tokens, 
                    Dictionary<string, string> authInfo)
    {
        base.OnAuthenticated(authService, session, tokens, authInfo);

        //Populate matching fields from this session into your own MyUserTable
        var user = session.TranslateTo<MyUserTable>();
        user.Id = int.Parse(session.UserAuthId);
        user.GravatarImageUrl64 = CreateGravatarUrl(session.Email, 64);

        foreach (var authToken in session.ProviderOAuthAccess)
        {
            if (authToken.Provider == FacebookAuthProvider.Name)
            {
                user.FacebookName = authToken.DisplayName;
                user.FacebookFirstName = authToken.FirstName;
                user.FacebookLastName = authToken.LastName;
                user.FacebookEmail = authToken.Email;
            }
            else if (authToken.Provider == TwitterAuthProvider.Name)
            {
                user.TwitterName = authToken.DisplayName;
            }
        }

        //Resolve the DbFactory from the IOC and persist the user info
        using (var db = authService.TryResolve<IDbConnectionFactory>().Open())
        {
            //Update (if exists) or insert populated data into 'MyUserTable'
            db.Save(user);
        }

    }

    //Change `IsAuthorized` to only verify users authenticated with Credentials
    public override bool IsAuthorized(string provider)
    {
        if (provider != AuthService.CredentialsProvider) return false;
        return base.IsAuthorized(provider);
    }
}

Basically this user-defined custom logic (which gets fired after every successful authentication) extracts data from the UserSession and stores it in a custom 'MyUserTable'.

We've also overridden the meaning of IsAuthorized to only accept users that have authenticated with CredentialsAuth.

You can use this data to complete the rest of the registration.

Other possible customizations

ServiceStack's built-in Auth persists the AuthData and populates the Session automatically for you. If you want to add extra validation assertions you can simply use your own custom [Authentication] attribute instead containing additional custom logic. Look at the implementation of the built-in AuthenticateAttribute as a guide.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!