@@ -42,3 +42,101 @@ namespace jwtauthcore.Controllers
4242
4343```
4444
45+ Final Look of the Authenticate Mehtod
46+
47+ ``` cs
48+ [AllowAnonymous ] // everybody can call this mehtod but rest of the method is authorized.
49+ [HttpPost (" authenticate" )]
50+ public IActionResult Authenticate ([FromBody ] UserCred userCred )
51+ {
52+ var token = jwtAuthenticationManager .Authenticate (userCred .Username , userCred .Password );
53+ if (token == null )
54+ {
55+ return Unauthorized ();
56+ }
57+ return Ok (token );
58+ }
59+
60+ ```
61+
62+ here is the authenticate method code from ` JwtAuthenticationManager ` file
63+
64+ ``` cs
65+ public string Authenticate (string username , string password )
66+ {
67+
68+ if (! users .Any (u => u .Key == username && u .Value == password ))
69+ {
70+ return null ;
71+ }
72+
73+
74+ var tokenHandler = new JwtSecurityTokenHandler ();
75+ var tokenKey = Encoding .ASCII .GetBytes (key );
76+
77+ var tokenDescriptor = new SecurityTokenDescriptor
78+ {
79+ Subject = new ClaimsIdentity (new Claim []
80+ {
81+ new Claim (ClaimTypes .Name , username )
82+ }),
83+ Expires = DateTime .UtcNow .AddHours (1 ),
84+ SigningCredentials =
85+ new SigningCredentials (
86+ new SymmetricSecurityKey (tokenKey ),
87+ SecurityAlgorithms .HmacSha256Signature )
88+ };
89+ var token = tokenHandler .CreateToken (tokenDescriptor );
90+ return tokenHandler .WriteToken (token );
91+ }
92+
93+ ```
94+
95+ And the Interface ` IJwtAuthenticationManager ` where I mentioned our authenticate mehtod.
96+
97+ ``` cs
98+ namespace jwtauthcore .Interface
99+ {
100+ public interface IJwtAuthenticationManager
101+ {
102+ string Authenticate (string username , string password );
103+ }
104+ }
105+
106+ ```
107+
108+ Finally the dependency Injection to ` Startup.cs ` file
109+
110+ ``` cs
111+ public void ConfigureServices (IServiceCollection services )
112+ {
113+ services .AddControllers ();
114+
115+
116+ var key = " this is test key" ;
117+
118+ services .AddAuthentication (x =>
119+ {
120+ x .DefaultAuthenticateScheme = JwtBearerDefaults .AuthenticationScheme ;
121+ x .DefaultChallengeScheme = JwtBearerDefaults .AuthenticationScheme ;
122+ }).AddJwtBearer (x =>
123+ {
124+ x .RequireHttpsMetadata = false ;
125+ x .SaveToken = true ;
126+ x .TokenValidationParameters = new TokenValidationParameters
127+ {
128+ ValidateIssuerSigningKey = true ,
129+ IssuerSigningKey = new SymmetricSecurityKey (Encoding .ASCII .GetBytes (key )),
130+ ValidateIssuer = false ,
131+ ValidateAudience = false
132+ };
133+ });
134+ services .AddSingleton <IJwtAuthenticationManager >(new JwtAuthenticationManager (key ));
135+ }
136+
137+ ```
138+
139+ ### Testing with PostMan
140+
141+
142+
0 commit comments