Skip to content

Instantly share code, notes, and snippets.

@milannankov
Last active February 19, 2016 12:09
Show Gist options
  • Save milannankov/a3ddd96d161bf1b4a6f5 to your computer and use it in GitHub Desktop.
Save milannankov/a3ddd96d161bf1b4a6f5 to your computer and use it in GitHub Desktop.
Migrating custom authentication from Mobile Services to Mobile Apps
public class AuthController : ApiController
{
public HttpResponseMessage Post(LoginChallenge challenge)
{
// return error if password is not correct
if (!this.IsPasswordValid(challenge.Username, challenge.Password))
{
return this.Request.CreateUnauthorizedResponse();
}
// OLD CODE
// var claims = new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, challenge.Username) });
// var loginProvider = new CustomLoginProvider(this.handler);
// return this.Request.CreateResponse(HttpStatusCode.OK, loginResult);
var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, challenge.Username) };
JwtSecurityToken token = this.GetAuthenticationTokenForUser(claims);
return this.Request.CreateResponse(HttpStatusCode.OK, new { Token = token.RawData });
}
}
[Authorize]
public class ProtectedController : ApiController
{
public string Get()
{
string greeting = "Hello from protected resource";
return greeting;
}
}
// The Sign-In Endpoint
public class AuthController : ApiController
{
public HttpResponseMessage Post(LoginChallenge challenge)
{
// return error if password is not correct
if (!this.IsPasswordValid(challenge.Username, challenge.Password))
{
return this.Request.CreateUnauthorizedResponse();
}
var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, challenge.Username) };
JwtSecurityToken token = this.GetAuthenticationTokenForUser(claims);
return this.Request.CreateResponse(HttpStatusCode.OK, new
{
Token = token.RawData,
Username = challenge.Username
});
}
}
// Create The Authentication Token
private JwtSecurityToken GetAuthenticationTokenForUser(IEnumerable<Claim> claims)
{
var signingKey = this.GetSigningKey();
var audience = this.GetSiteUrl(); // audience must match the url of the site
var issuer = this.GetSiteUrl(); // audience must match the url of the site
JwtSecurityToken token = AppServiceLoginHandler.CreateToken(
claims,
signingKey,
audience,
issuer,
TimeSpan.FromHours(24)
);
return token;
}
private string GetSiteUrl()
{
var settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
if (string.IsNullOrEmpty(settings.HostName))
{
return "http://localhost";
}
else
{
return "https://" + settings.HostName + "/";
}
}
private string GetSigningKey()
{
var settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
if (string.IsNullOrEmpty(settings.HostName))
{
// this key is for debuggint and testing purposes only
// this key should match the one supplied in Startup.MobileApp.cs
return "GfYVqdtZUJQfghRiaonAeRQRDjytRi47";
}
else
{
return Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY");
}
}
// The Protected Endpoint
[Authorize]
public class ProtectedController : ApiController
{
public string Get()
{
string greeting = "Hello from protected resource";
return greeting;
}
}
private JwtSecurityToken GetAuthenticationTokenForUser(IEnumerable<Claim> claims)
{
var signingKey = this.GetSigningKey();
var audience = this.GetSiteUrl(); // audience must match the url of the site
var issuer = this.GetSiteUrl(); // audience must match the url of the site
JwtSecurityToken token = AppServiceLoginHandler.CreateToken(
claims,
signingKey,
audience,
issuer,
TimeSpan.FromHours(24)
);
return token;
}
private string GetSiteUrl()
{
var settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
if (string.IsNullOrEmpty(settings.HostName))
{
return "http://localhost";
}
else
{
return "https://" + settings.HostName + "/";
}
}
private string GetSigningKey()
{
var settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
if (string.IsNullOrEmpty(settings.HostName))
{
// this key is for debuggint and testing purposes only
// this key should match the one supplied in Startup.MobileApp.cs
return "GfYVqdtZUJQfghRiaonAeRQRDjytRi47";
}
else
{
return Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY");
}
}
// The Custom LoginProvider
public class CustomLoginProvider : LoginProvider
{
public const string ProviderName = "custom";
public override string Name
{
get
{
return ProviderName;
}
}
public CustomLoginProvider(IServiceTokenHandler tokenHandler)
: base(tokenHandler)
{
this.TokenLifetime = new TimeSpan(30, 0, 0, 0);
}
public override void ConfigureMiddleware(Owin.IAppBuilder appBuilder, ServiceSettingsDictionary settings)
{
return;
}
public override ProviderCredentials CreateCredentials(ClaimsIdentity claimsIdentity)
{
if (claimsIdentity == null)
{
throw new ArgumentNullException("claimsIdentity");
}
var providerKey = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier).Value;
var credentials = new CustomLoginProviderCredentials
{
UserId = this.TokenHandler.CreateUserId(this.Name, providerKey)
};
return credentials;
}
public override ProviderCredentials ParseCredentials(JObject serialized)
{
if (serialized == null)
{
throw new ArgumentNullException("serialized");
}
return serialized.ToObject<CustomLoginProviderCredentials>();
}
}
// The Custom LoginCredentials
public class CustomLoginProviderCredentials : ProviderCredentials
{
public CustomLoginProviderCredentials()
: base(CustomLoginProvider.ProviderName)
{
}
}
// The Sign-In Endpoint
public class AuthController : ApiController
{
public HttpResponseMessage Post(LoginChallenge challenge)
{
// return error if password is not correct
if (!this.IsPasswordValid(challenge.Username, challenge.Password))
{
return this.Request.CreateUnauthorizedResponse();
}
var claims = new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, challenge.Username) });
var loginProvider = new CustomLoginProvider(this.handler);
return this.Request.CreateResponse(HttpStatusCode.OK, loginResult);
}
}
// The Protected Endpoint
[AuthorizeLevel(AuthorizationLevel.User)]
public class ProtectedController : ApiController
{
public string Get()
{
string greeting = "Hello from protected resource";
return greeting;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment