I'm working on a Xamarin Forms mobile app with .NET backend. I followed this guide and successfully set up custom authentications with one change in Startup.cs:
app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions
{
SigningKey = Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY"),
ValidAudiences = new[] { Identifiers.Environment.ApiUrl },
ValidIssuers = new[] { Identifiers.Environment.ApiUrl },
TokenHandler = config.GetAppServiceTokenHandler()
});
Without "if (string.IsNullOrEmpty(settings.HostName))". Otherwise I am always getting unauthorized for all requests after login.
Server project:
Auth controller
public class ClubrAuthController : ApiController { private readonly ClubrContext dbContext; private readonly ILoggerService loggerService;
public ClubrAuthController(ILoggerService loggerService) { this.loggerService = loggerService; dbContext = new ClubrContext(); } public async Task<IHttpActionResult> Post(LoginRequest loginRequest) { var user = await dbContext.Users.FirstOrDefaultAsync(x => x.Email == loginRequest.username); if (user == null) { user = await CreateUser(loginRequest); } var token = GetAuthenticationTokenForUser(user.Email); return Ok(new { authenticationToken = token.RawData, user = new { userId = loginRequest.username } }); } private JwtSecurityToken GetAuthenticationTokenForUser(string userEmail) { var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, userEmail) }; var secretKey = Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY"); var audience = Identifiers.Environment.ApiUrl; var issuer = Identifiers.Environment.ApiUrl; var token = AppServiceLoginHandler.CreateToken( claims, secretKey, audience, issuer, TimeSpan.FromHours(24) ); return token; }
}
Startup.cs
ConfigureMobileAppAuth(app, config, container); app.UseWebApi(config); } private void ConfigureMobileAppAuth(IAppBuilder app, HttpConfiguration config, IContainer container) { config.Routes.MapHttpRoute("ClubrAuth", ".auth/login/ClubrAuth", new { controller = "ClubrAuth" }); app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions { SigningKey = Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY"), ValidAudiences = new[] { Identifiers.Environment.ApiUrl }, ValidIssuers = new[] { Identifiers.Environment.ApiUrl }, TokenHandler = config.GetAppServiceTokenHandler() }); }
Client project:
MobileServiceUser user = await MobileClient.LoginAsync(loginProvider, jtoken);
Additionally I configured Facebook provider in azure portal like described here. But it works only when I comment out app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions(){...}); in Startup.cs. What I am missing to make both types of authentication works at the same time?