4
votes

In the latest update of Azure Mobile Apps, support for custom authentication was finally added, ref: https://azure.microsoft.com/en-us/blog/azure-mobile-apps-november-2015-update.

They have included a snippet for issuing a JWT-token, but my question is how would I use this in my app for authenticating requests?

I guess I need to add a custom token handler in my WebApiConfig, but I can't find any docs on the subject.

3

3 Answers

2
votes
  1. Turn on App Service Authentication
  2. Add Microsoft.Azure.Mobile.Server.Login NuGet package
  3. Create custom authentication endpoint
  4. Configure service to require authentication
  5. Use token on client

Please check this out for more details. This article explains it steps by step.

http://www.newventuresoftware.com/blog/custom-authentication-with-azure-mobile-apps/

0
votes

I eventually figured this out myself.

If anyone is wondering, this actually "just works". I looked into the source code and the only validation being done is based on the JWT-token encryption key, the "Audience"-setting and the "Issuer"-setting. You can just add the [Authorize] attribute to the controller or method and the pipeline takes care of the rest.

If custom claims are needed, they can be added to the MobileAppLoginHandler.CreateToken call and extracted from the User-object. I made my own extension method on IPrincipal to get a custom object with the properties I needed in the same manner as the built-in providers.

0
votes

Generates an Azure token and return it to the app. You need Microsoft.Azure.Mobile.Server.Login NuGet package.

 var claims = new Claim[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, "YOUR_UNIQUE_EMAIL_OR_USERNAME_OR_PHONENUMBER")
    };

    var signingKey = Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY");
    var audience = "https://myservice.azurewebsites.net/"; // audience must match the url of the site
    var issuer = "https://myservice.azurewebsites.net/"; // audience must match the url of the site

    JwtSecurityToken token = AppServiceLoginHandler.CreateToken(
        claims,
        signingKey,
        audience,
        issuer,
        TimeSpan.FromDays(30)
        );

string tokenString = token.RawData;