Skip to content

Commit

Permalink
Custom JWT Auth Extention
Browse files Browse the repository at this point in the history
  • Loading branch information
YaraGh22-engs committed Jun 10, 2024
1 parent aeebdec commit 24758a4
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
4 changes: 3 additions & 1 deletion MoviesApi/Controllers/GenresController.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MoviesApi.Services;

namespace MoviesApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class GenresController : ControllerBase
{
private readonly IGenresService _genresService;
Expand Down
31 changes: 31 additions & 0 deletions MoviesApi/Extentions/CustomJwtAuthExtention.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace MoviesApi.Extentions
{
public static class CustomJwtAuthExtention
{
public static void AddCustomJwtAuth(this IServiceCollection services, ConfigurationManager configuration)
{
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.RequireHttpsMetadata = false;
o.SaveToken = true;
o.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidIssuer = configuration["JWT:Issuer"],
ValidateAudience = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:SecretKey"]))
};
});
}
}
}
3 changes: 3 additions & 0 deletions MoviesApi/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using MoviesApi.Extentions;
using MoviesApi.Models;
using MoviesApi.Services;
using System;
Expand All @@ -16,6 +17,8 @@

// for jwt
builder.Services.AddIdentity<AppUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();

builder.Services.AddCustomJwtAuth(builder.Configuration);
// Add services to the container.

builder.Services.AddTransient<IGenresService, GenresService>();
Expand Down

0 comments on commit 24758a4

Please sign in to comment.