Skip to content

Instantly share code, notes, and snippets.

@milannankov
Last active November 25, 2015 15:30
Show Gist options
  • Save milannankov/c55f0d05726fb2242401 to your computer and use it in GitHub Desktop.
Save milannankov/c55f0d05726fb2242401 to your computer and use it in GitHub Desktop.
custom-auth-mobile-apps
[MobileAppController]
public class AuthController : ApiController
{
public HttpResponseMessage Post(string username, string password)
{
// return error if password is not correct
if (!this.IsPasswordValid(username, password))
{
return this.Request.CreateUnauthorizedResponse();
}
JwtSecurityToken token = this.GetAuthenticationTokenForUser(username);
return this.Request.CreateResponse(HttpStatusCode.OK, new
{
Token = token.RawData,
Username = username
});
}
private bool IsPasswordValid(string username, string password)
{
// this is where we would do checks agains a database
return true;
}
}
[MobileAppController]
public class AuthController : ApiController
{
public HttpResponseMessage Post(string username, string password)
{
// return error if password is not correct
if (!this.IsPasswordValid(username, password))
{
return this.Request.CreateUnauthorizedResponse();
}
JwtSecurityToken token = this.GetAuthenticationTokenForUser(username);
return this.Request.CreateResponse(HttpStatusCode.OK, new
{
Token = token.RawData,
Username = username
});
}
private JwtSecurityToken GetAuthenticationTokenForUser(string username)
{
var claims = new Claim[]
{
new Claim(JwtRegisteredClaimNames.Sub, username)
};
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 = MobileAppLoginHandler.CreateToken(
claims,
signingKey,
audience,
issuer,
TimeSpan.FromHours(24)
);
return token;
}
private bool IsPasswordValid(string username, string password)
{
// this is where we would do checks agains a database
return true;
}
}
private JwtSecurityToken GetAuthenticationTokenForUser(string username)
{
var claims = new Claim[]
{
new Claim(JwtRegisteredClaimNames.Sub, username)
};
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 = MobileAppLoginHandler.CreateToken(
claims,
signingKey,
audience,
issuer,
TimeSpan.FromHours(24)
);
return token;
}
[MobileAppController]
public class ProtectedController : ApiController
{
[Authorize]
public string MyProtectedMethod()
{
return "this is a protected method";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment