Skip to content

Instantly share code, notes, and snippets.

View changhuixu's full-sized avatar
💭
Everyone has a happy ending. If you're not happy, it's not the end.

Changhui Xu changhuixu

💭
Everyone has a happy ending. If you're not happy, it's not the end.
View GitHub Profile
[HttpPost("logout")]
[Authorize]
public ActionResult Logout()
{
var userName = User.Identity.Name;
_jwtAuthManager.RemoveRefreshTokenByUserName(userName); // can be more specific to ip, user agent, device name, etc.
_logger.LogInformation($"User [{userName}] logged out the system.");
return Ok();
}
[ApiController]
[Authorize]
[Route("api/[controller]")]
public class AccountController : ControllerBase
{
private readonly ILogger<AccountController> _logger;
private readonly IUserService _userService;
private readonly IJwtAuthManager _jwtAuthManager;
public AccountController(ILogger<AccountController> logger, IUserService userService, IJwtAuthManager jwtAuthManager)
public class JwtAuthManager : IJwtAuthManager
{
public IImmutableDictionary<string, RefreshToken> UsersRefreshTokensReadOnlyDictionary => _usersRefreshTokens.ToImmutableDictionary();
private readonly ConcurrentDictionary<string, RefreshToken> _usersRefreshTokens; // can store in a database or a distributed cache
private readonly JwtTokenConfig _jwtTokenConfig;
private readonly byte[] _secret;
public JwtAuthManager(JwtTokenConfig jwtTokenConfig)
{
_jwtTokenConfig = jwtTokenConfig;
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
public void ConfigureServices(IServiceCollection services)
{
var jwtTokenConfig = Configuration.GetSection("jwtTokenConfig").Get<JwtTokenConfig>();
services.AddSingleton(jwtTokenConfig);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
public class JwtTokenConfig
{
public string Secret { get; set; }
public string Issuer { get; set; }
public string Audience { get; set; }
public int AccessTokenExpiration { get; set; }
public int RefreshTokenExpiration { get; set; }
}
services.AddSwaggerGen(c =>
{
// configure SwaggerDoc and others
// add JWT Authentication
var securityScheme = new OpenApiSecurityScheme
{
Name = "JWT Authentication",
Description = "Enter JWT Bearer token **_only_**",
In = ParameterLocation.Header,
FROM scratch
COPY hello /
CMD ["/hello"]
curl http://timelessname.com/elfbin/helloworld.tar.gz --output helloworld.tar.gz
mkdir helloworld
tar -xvf helloworld.tar.gz -C ./helloworld
$ docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
busybox latest 1c35c4412082 3 weeks ago 1.22MB
alpine latest a24bb4013296 4 weeks ago 5.57MB
nginx alpine 89ec9da68213 2 months ago 19.9MB