Open Authentication is pretty standard by now, and for us, a requirement. We don’t maintain our clients’ passwords, allowing their administration to handle that. Instead, we use oAuth to access sites. While getting the token from a Javascript page is pretty straight forward, what we really need is a way to then access our own API servers with that token and ensure this user is legit. To do so, we have an api that receives a posted token object like this {token:”blah blah blah”}, we then call the Auth0 website where they keep our matching credentials and see if the token is ok. Then, we give them a session ID on our server and in our database.
Now, this is stripped down from our normal session controller, but basically, this is called after the promise call to Auth0 has been fulfilled. We simply relay that call right back to our server, get the reply and then our user is officially “logged in”.
public class SessionController : ApiController { const string auth0Domain = "https://[your account].auth0.com/"; /* This is the clientID of your Auth0 application, not the url of the "Audience", like most examples I found on the web */ const string auth0ClientID = "hYbChvXUxxxxxxxxxxxxxxxxxxRuOSWHvH"; [ResponseType(typeof(JObject ))] public async Task<IHttpActionResult> Post([FromBody]JObject obj, [FromUri]string sid = "") { string token = (string)obj["token"]; var openidConfiguration = await OpenIdConnectConfigurationRetriever.GetAsync( $"{auth0Domain}.well-known/openid-configuration", CancellationToken.None).ConfigureAwait(false); TokenValidationParameters validationParameters = new TokenValidationParameters { ValidIssuer = auth0Domain, ValidAudiences = new[] { auth0ClientID }, IssuerSigningKeys = openidConfiguration.SigningKeys }; SecurityToken validatedToken; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); var user = handler.ValidateToken(token, validationParameters, out validatedToken); if (user.Identity.IsAuthenticated) { /* in here, I send the token off to get some further information from our database, cache the token, etc.. You can do whatever you need to do. */ SecurityModule sec = new SecurityModule(); dynamic responseObject = sec.getSessionId(obj ); return Ok(responseObject); } else { return Unauthorized(); } } }