Last active
July 12, 2019 19:26
-
-
Save baughmann/38d5fc47b98fce6953e334c07b53f76d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.DirectoryServices.AccountManagement; | |
using System.IdentityModel.Tokens.Jwt; | |
using System.Linq; | |
using System.Security.Claims; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Authorization; | |
using Microsoft.AspNetCore.Cors; | |
using Microsoft.AspNetCore.Http.Features; | |
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.IdentityModel.Tokens; | |
using Newtonsoft.Json; | |
namespace MyApp | |
{ | |
[Route("api/users")] | |
public class UsersController : Controller | |
{ | |
private IConfiguration configuration { get; } | |
private MyAuthService authService { get; } | |
public AuthController(IConfiguration _configuration, MyAuthService _authService) | |
{ | |
configuration = _configuration; | |
authService = _authService; | |
} | |
[AllowAnonymous] | |
[HttpPost("login")] | |
public async Task<IActionResult> Login([FromBody] AuthRequest authRequest) | |
{ | |
var username = authRequest.username; | |
var password = authRequest.password; | |
// call to a custom service that verifies the password and | |
// retrieves the user if authentication was successful | |
var user = authService.getUser(username, password); | |
if (!user.Equals(null)) | |
{ | |
// add your custom claims from the user object pulled from your database | |
var claims = new[] { new Claim(ClaimTypes.Name, user.name) }; | |
// pull a signing key from your appsettings.json (ideally, this should be rotated out fairly regularly for security) | |
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetSection("App:JWTSigningKey").Value)); | |
// create some credentials to sign the token with | |
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); | |
var token = new JwtSecurityToken( | |
// set the domain your token will cover | |
issuer: "mydomain.com", | |
audience: "mydomain.com", | |
// add your custom claims to the token (such as "isAdmin" or perhaps a permissions array) | |
claims: claims, | |
// decide how long your JWT will be valid for | |
expires: DateTime.Now.AddMinutes(60), | |
// add the signing credentials to prevent tokens from other sources | |
signingCredentials: creds); | |
// return a 200, and the JWT that your client side can store (in cookies for example) | |
// and then resend in HTTP headers as "Authorization": "Bearer <JWT_TOKEN_STRING>" | |
return Ok(new | |
{ | |
token = new JwtSecurityTokenHandler().WriteToken(token) | |
}); | |
} | |
// return a 401 if authentication failed for some reason. | |
// probably best to add some more details (i.e. "Incorrect Username or Password" or "User does not exist", etc.) | |
return Unauthorized(); | |
} | |
[Authorize] | |
[HttpGet("so-something")] | |
public async Task<IActionResult> DoSomething() { | |
// does something that requires authentication | |
} | |
// a custom model for handling login requests | |
public class AuthRequest | |
{ | |
public string username { get; set; } | |
public string password { get; set; } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment