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.
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?
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.
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).
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
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
}
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.
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?
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
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?
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:
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
Hi, manila, I achieved this functionality on project using UmbracoIdentity. If you need some guidelines or code samples just write to me.
Mila
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).
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
I'm using AuthU without to "customize" Umbraco Identity where there is a lack of documentation.
Only backoffice user.
Thanks but I need it for Members, not Users
So, use https://github.com/mattbrailsford/umbraco-authu I already use it in 3 apps.
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:
The code inside SimpleAuthorizationServerProvider is:
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:
Mila
Why Do you create SimpleAuthorizationServerProvider? If you install Identity package you already have the custom Umbraco startup into App_Start.
Mila, did you do it as a separate project or within one Umbraco project?
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
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?
Hi, manila, The mobile app calls Http://domain/token only for authentication - the call returns token. The call has the following structure:
The response is:
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:
I don't have login method inside my API controller. This article helped me a lot to achieve what I wanted
Regards Mila
@Manila: There is not the login method because "you made login" when call token function.
is working on a reply...