1+ using System ;
2+ using System . Text ;
3+ using System . Threading . Tasks ;
4+ using Microsoft . AspNetCore . Http ;
5+ using Microsoft . Net . Http . Headers ;
6+ using System . Linq ;
7+ using Microsoft . EntityFrameworkCore ;
8+
9+
10+ namespace SimpleToDoService
11+ {
12+ public class BasicAuthMiddleware
13+ {
14+ private readonly RequestDelegate next ;
15+ private ToDoContext dbContext ;
16+
17+ public BasicAuthMiddleware ( RequestDelegate next , ToDoContext databaseContext )
18+ {
19+ this . next = next ;
20+ dbContext = databaseContext ;
21+ }
22+
23+ public async Task Invoke ( HttpContext context )
24+ {
25+ var authHeader = ( string ) context . Request . Headers [ "Authorization" ] ;
26+ if ( authHeader != null && authHeader . StartsWith ( "basic" , StringComparison . OrdinalIgnoreCase ) )
27+ {
28+ var token = authHeader . Substring ( "Basic " . Length ) . Trim ( ) ;
29+ var credentialstring = Encoding . UTF8 . GetString ( Convert . FromBase64String ( token ) ) ;
30+ var credentials = credentialstring . Split ( ':' ) ;
31+ var user = credentials . FirstOrDefault ( ) ;
32+ var password = credentials . Skip ( 1 ) . FirstOrDefault ( ) ;
33+
34+ var currentUser = dbContext . Users . Where ( o => o . Email == user && o . Password == password ) . FirstOrDefault ( ) ;
35+ if ( currentUser != null )
36+ {
37+ context . Items . Add ( "UserId" , currentUser . Id ) ;
38+ }
39+ else
40+ {
41+ context . Response . StatusCode = 401 ; //Unauthorized
42+ var jsonString = "{ \" Error\" : \" Incorrect user name or password\" }" ;
43+ context . Response . ContentType = new MediaTypeHeaderValue ( "application/json" ) . ToString ( ) ;
44+ await context . Response . WriteAsync ( jsonString , Encoding . UTF8 ) ;
45+ return ;
46+ }
47+ }
48+ else
49+ {
50+ context . Response . StatusCode = 401 ; //Unauthorized
51+ var jsonString = "{ \" Error\" : \" Authorization header missed\" }" ;
52+ context . Response . ContentType = new MediaTypeHeaderValue ( "application/json" ) . ToString ( ) ;
53+ await context . Response . WriteAsync ( jsonString , Encoding . UTF8 ) ;
54+ return ;
55+ }
56+
57+ await next . Invoke ( context ) ;
58+ }
59+ }
60+
61+ }
0 commit comments