There are different kinds of authentication. One of the most used ones is basic authentication that doesn’t expire like a bearer token and you need to send a username and password per each request. In order to handle such an authentication you can middleware:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | public class AuthenticationMiddleware { private readonly RequestDelegate _next; public AuthenticationMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { string authHeader = context.Request.Headers[ "Authorization" ]; if (authHeader != null && authHeader.StartsWith( "Basic" )) { //Extract credentials string encodedUsernamePassword = authHeader.Substring( "Basic " .Length).Trim(); Encoding encoding = Encoding.GetEncoding( "iso-8859-1" ); string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword)); int seperatorIndex = usernamePassword.IndexOf( ':' ); var username = usernamePassword.Substring(0, seperatorIndex); var password = usernamePassword.Substring(seperatorIndex + 1); //fetch user/pass from Db if ( username == "MyUser" && password == "MyPass" ) { await _next.Invoke(context); } else { context.Response.StatusCode = 401; //Unauthorized return ; } } } } |
A simple middleware that handles every incoming request and verifies the username and password. Notice that, fetching usernames and passwords for every request could be really cost-effective, and based on the usage you should create it wisely. By registering the above middleware in Configure() of Startup class:
1 2 | app.UseMiddleware<AuthenticationMiddleware>(); app.UseMvc(); |
You can use the middle. By doing this you don’t even need to use Authorize attribute in your controllers.