Skip to content

Commit 24758a4

Browse files
committed
Custom JWT Auth Extention
1 parent aeebdec commit 24758a4

File tree

3 files changed

+37
-1
lines changed

3 files changed

+37
-1
lines changed

MoviesApi/Controllers/GenresController.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
1-
using Microsoft.AspNetCore.Http;
1+
using Microsoft.AspNetCore.Authorization;
2+
using Microsoft.AspNetCore.Http;
23
using Microsoft.AspNetCore.Mvc;
34
using MoviesApi.Services;
45

56
namespace MoviesApi.Controllers
67
{
78
[Route("api/[controller]")]
89
[ApiController]
10+
[Authorize]
911
public class GenresController : ControllerBase
1012
{
1113
private readonly IGenresService _genresService;
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
using Microsoft.AspNetCore.Authentication.JwtBearer;
2+
using Microsoft.IdentityModel.Tokens;
3+
using System.Text;
4+
5+
namespace MoviesApi.Extentions
6+
{
7+
public static class CustomJwtAuthExtention
8+
{
9+
public static void AddCustomJwtAuth(this IServiceCollection services, ConfigurationManager configuration)
10+
{
11+
services.AddAuthentication(o =>
12+
{
13+
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
14+
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
15+
o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
16+
}).AddJwtBearer(o =>
17+
{
18+
o.RequireHttpsMetadata = false;
19+
o.SaveToken = true;
20+
o.TokenValidationParameters = new TokenValidationParameters()
21+
{
22+
ValidateIssuer = true,
23+
ValidIssuer = configuration["JWT:Issuer"],
24+
ValidateAudience = false,
25+
ValidateIssuerSigningKey = true,
26+
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:SecretKey"]))
27+
};
28+
});
29+
}
30+
}
31+
}

MoviesApi/Program.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using Microsoft.AspNetCore.Identity;
22
using Microsoft.EntityFrameworkCore;
33
using Microsoft.OpenApi.Models;
4+
using MoviesApi.Extentions;
45
using MoviesApi.Models;
56
using MoviesApi.Services;
67
using System;
@@ -16,6 +17,8 @@
1617

1718
// for jwt
1819
builder.Services.AddIdentity<AppUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
20+
21+
builder.Services.AddCustomJwtAuth(builder.Configuration);
1922
// Add services to the container.
2023

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

0 commit comments

Comments
 (0)