Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • manila 248 posts 550 karma points
    Mar 20, 2018 @ 09:58
    manila
    0

    Authenticating mobile app users via umbraco Rest API

    I'm trying to get my head around how to do a member login for front end users from a mobile app - to login to use protected content of my umbraco site.

    I have come across this documentation: https://our.umbraco.org/documentation/implementation/Rest-Api/ But I'm not sure - can I authenticate members or only users through Umbraco Rest API?

    Wil I get a request token back from umbraco to pass to the mobile app? What can be exactly the process here to request member login and get back to mobile app?

  • Mila Pandurska 43 posts 187 karma points
    Mar 23, 2018 @ 21:27
    Mila Pandurska
    0

    Hi manila, I have the same task. I am using UmbracoIdentity as MembershipProvider becuase in my case we need external login as well (with different social networks). In theory I am going tho achieve this by creating a WebAPI where I will have a method:

    string Login(username, password)
    {
    var user = await UserManager.FindAsync(model.Username, model.Password);
                    if (user != null)
                    {
                        //create bareer token and send return it to mobile app
                    }
    }
    

    The mobile app will store the token in the app and when the users tries to access the secured methods they will make the request with the barear token in the head of the request. Hope that this makes sense to you.

    Mila

  • Mila Pandurska 51 posts 258 karma points
    Mar 24, 2018 @ 21:33
    Mila Pandurska
    0

    Hi, manila, I achieved this functionality on project using UmbracoIdentity. If you need some guidelines or code samples just write to me.

    Mila

  • John Bergman 438 posts 1001 karma points
    Mar 26, 2018 @ 19:31
    John Bergman
    0

    We have this working using AuthU, which provides a way to use OAUTH to do the authentication and leverages the membership provider built into umbraco.

    It was a little trial and error to get the package working - but its working now, specifically the number of variations of the attributes for in play (ie, [oauth(realm)], etc... you just need to be sure you use the correct one(s).

  • manila 248 posts 550 karma points
    Apr 05, 2018 @ 08:29
    manila
    0

    Thanks for recommendations! I'll be checking them this week. Mila, it'll be very useful if you can share some code sample, your solution looks like it's what we're looking for. Thank you

  • Biagio Paruolo 1474 posts 1613 karma points c-trib
    Apr 05, 2018 @ 09:01
    Biagio Paruolo
    0

    I'm using AuthU without to "customize" Umbraco Identity where there is a lack of documentation.

  • Biagio Paruolo 1474 posts 1613 karma points c-trib
    Apr 05, 2018 @ 09:02
    Biagio Paruolo
    0

    Only backoffice user.

  • manila 248 posts 550 karma points
    Apr 05, 2018 @ 15:57
    manila
    0

    Thanks but I need it for Members, not Users

  • Biagio Paruolo 1474 posts 1613 karma points c-trib
    Apr 05, 2018 @ 16:14
    Biagio Paruolo
    0

    So, use https://github.com/mattbrailsford/umbraco-authu I already use it in 3 apps.

  • Mila Pandurska 43 posts 187 karma points
    Apr 05, 2018 @ 21:21
    Mila Pandurska
    1

    Hi, manila, First Step is to install the packaege Umbraco Identity from Nuget. In my case I installed only the .Core because I didn't need all the views. It is important to follow the steps described here.

    I created UmbracoIdentityStartup.cs in my App_Core folder and inside my ConfigureMiddleware method I have this:

     protected override void ConfigureMiddleware(IAppBuilder app)
        {
            //Configure the application for OAuth based flow
            var OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/token"),
                Provider = new SimpleAuthorizationServerProvider(),
              //  AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(30),
                AuthorizationCodeExpireTimeSpan = TimeSpan.FromHours(3),
                AllowInsecureHttp = true
            };
    
            //Enable the application to use bearer tokens to authenticate users
            //app.UseOAuthBearerTokens(OAuthOptions);
            app.UseOAuthAuthorizationServer(OAuthOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    app.UseUmbracoPreviewAuthentication(ApplicationContext, PipelineStage.Authorize);
    
           }
    

    The code inside SimpleAuthorizationServerProvider is:

    public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }
    
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            UmbracoMembersUserManager<UmbracoApplicationMember> UserManager = context.OwinContext
                    .GetUserManager<UmbracoMembersUserManager<UmbracoApplicationMember>>();
    
            var user = await UserManager.FindAsync(context.UserName, context.Password);
            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
    
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString(), ClaimValueTypes.String));
            identity.AddClaim(new Claim(ClaimTypes.Name, user.Name));
            identity.AddClaim(new Claim(ClaimTypes.Email, context.UserName));
    
            context.Validated(identity);
    
        }
    }
    

    This is the configuration for authenticating mobile users. The mobile app calls http://domain/token with username and password. In response they get token which is used in any further request. Of cource you need an Umbraco API Controller with [Authorize] attribute:

     [Authorize]
    public class MyAPIControllerController : UmbracoApiController
    {
        //my methods go here
    }
    

    Mila

  • Biagio Paruolo 1474 posts 1613 karma points c-trib
    Apr 06, 2018 @ 05:40
    Biagio Paruolo
    0

    Why Do you create SimpleAuthorizationServerProvider? If you install Identity package you already have the custom Umbraco startup into App_Start.

  • manila 248 posts 550 karma points
    Apr 06, 2018 @ 08:42
    manila
    0

    Mila, did you do it as a separate project or within one Umbraco project?

  • Mila Pandurska 43 posts 187 karma points
    Apr 06, 2018 @ 09:01
    Mila Pandurska
    0

    Hi, manila, Inside the Umbraco Project. @Biagio - I use the package to authenticate members to my website as well. So I have 2 configuration - one with the token for mobile and one with cookie for the standart login.

    Mila

  • manila 248 posts 550 karma points
    Apr 06, 2018 @ 14:06
    manila
    0

    Thanks Mila, Can you share some code from api controller too?

    I am not doing mobile app end, so I'm not totally sure how to link everything, You said the mobile app calls domain/token or it should rather call an umbracoapi controller action?

  • Mila Pandurska 43 posts 187 karma points
    Apr 08, 2018 @ 22:01
    Mila Pandurska
    0

    Hi, manila, The mobile app calls Http://domain/token only for authentication - the call returns token. The call has the following structure:

     grant_type=password&username=USERNAME&password=PASSWORD
    

    The response is:

    {"access_token":"TOKEN", "token_type":"bearer", "expires_in":2591999} 
    

    Once a mobile user gets the token he makes the requests to Umbraco API Controller with the token above in the header. Here is part of my AccountController:

    [Authorize]
    public class AccountController : UmbracoApiController
    {
        #region Properties and Constructors
    
        private UmbracoMembersUserManager<UmbracoApplicationMember> _userManager;
        private UmbracoMembersRoleManager<UmbracoApplicationRole> _roleManager;
    
        private IMessagingService _messagingService;
    
        public AccountController(UmbracoContext umbracoContext, UmbracoMembersUserManager<UmbracoApplicationMember> userManager, UmbracoMembersRoleManager<UmbracoApplicationRole> roleManager, IMessagingService messageingService) : base(umbracoContext)
        {
            _userManager = userManager;
            _roleManager = roleManager;
        }
    
        public AccountController(UmbracoContext umbracoContext, UmbracoHelper umbracoHelper, UmbracoMembersUserManager<UmbracoApplicationMember> userManager, UmbracoMembersRoleManager<UmbracoApplicationRole> roleManager, IMessagingService messageingService) : base(umbracoContext, umbracoHelper)
        {
            _userManager = userManager;
            _roleManager = roleManager;
        }
    
        public AccountController(UmbracoMembersUserManager<UmbracoApplicationMember> userManager, UmbracoMembersRoleManager<UmbracoApplicationRole> roleManager, IMessagingService messageingService)
        {
            _userManager = userManager;
            _roleManager = roleManager;
        }
    
        public AccountController(IMessagingService messageingService)
        {
            _messagingService = messageingService;
        }
    
        protected IOwinContext OwinContext
        {
            get { return Request.GetOwinContext(); }
        }
    
        public UmbracoMembersUserManager<UmbracoApplicationMember> UserManager
        {
            get
            {
                return _userManager ?? (_userManager = OwinContext
                    .GetUserManager<UmbracoMembersUserManager<UmbracoApplicationMember>>());
            }
        }
    
        public UmbracoMembersRoleManager<UmbracoApplicationRole> RoleManager
        {
            get
            {
                return _roleManager ?? (_roleManager = OwinContext
                    .Get<UmbracoMembersRoleManager<UmbracoApplicationRole>>());
            }
        }
        #endregion Properties and Constructors
    
        [HttpGet]
        public string Test()
        {
            return "Test";
        }
    
        [HttpGet]
        public HttpResponseMessage GetProfile()
        {
    
            var identity = (ClaimsIdentity)User.Identity;
            if (identity == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound, "User is not logged in");
            }
    
            //some logic here
    
                return Request.CreateResponse(HttpStatusCode.OK, user);
    
        }
    

    I don't have login method inside my API controller. This article helped me a lot to achieve what I wanted

    Regards Mila

  • Biagio Paruolo 1474 posts 1613 karma points c-trib
    Apr 09, 2018 @ 07:55
    Biagio Paruolo
    0

    @Manila: There is not the login method because "you made login" when call token function.

Please Sign in or register to post replies

Write your reply to:

Draft