Custom OWIN CookieAuthenticationProvider fails on 1st/cold boot - c#

We have a custom cookie auth provider that puts sets the auth cookie to bear a hostname like .domain.com instead of domain.com or my.domain.com. We do it so the cookies work across all subdomains and the domains. It's as simple as shown below.
Issue
On the very FIRST attempt after app cold start, the cookie STILL bears the domain my.domain.com (our logins are on my.domain.com) DESPITE setting it to .domain.com after executing the SubdomainCookieAuthentication code below (checked with breakpoints). On subsequent login attempts, the cookie hostname is fine.
Question
How can I fix this so it works even on the first attempt?
Code
Custom cookie auth
public class SubdomainCookieAuthentication : CookieAuthenticationProvider
{
public override void ResponseSignIn(CookieResponseSignInContext context)
{
// We need to add a "." in front of the domain name to
// allow the cookie to be used on all sub-domains too
var hostname = context.Request.Uri.Host;
// works for www.google.com => google.com
// will FAIL for www.google.co.uk (gives co.uk) but doesn't apply to us
var dotTrimmedHostname = Regex.Replace(hostname, #"^.*(\.\S+\.\S+)", "$1");
context.Options.CookieDomain = dotTrimmedHostname;
base.ResponseSignIn(context);
}
}
This is initialized inside the Owin startup class as follows
Class: Startup
File: App_start\Startup.Auth.cs
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new SubdomainCookieAuthentication()
});
}

I was having the same problem with the Cookie Domain not getting set on the first attempt using the ResponseSignIn method. I was able to resolve this by updating the Owin libraries to 3.x and using the new CookieManager to set the Domain. Found this solution from this post:
How is Owin able to set the Asp.Net Identity authentication cookies after the Application_EndRequest stage?
public class ChunkingCookieManagerWithSubdomains : ICookieManager
{
private readonly ChunkingCookieManager _chunkingCookieManager;
public ChunkingCookieManagerWithSubdomains()
{
_chunkingCookieManager = new ChunkingCookieManager();
}
public string GetRequestCookie(IOwinContext context, string key)
{
return _chunkingCookieManager.GetRequestCookie(context, key);
}
public void AppendResponseCookie(IOwinContext context, string key, string value, CookieOptions options)
{
options.Domain = context.Request.Uri.GetHostWithoutSubDomain();
_chunkingCookieManager.AppendResponseCookie(context, key, value, options);
}
public void DeleteCookie(IOwinContext context, string key, CookieOptions options)
{
options.Domain = context.Request.Uri.GetHostWithoutSubDomain();
_chunkingCookieManager.DeleteCookie(context, key, options);
}
}
public static class UriExtensions
{
public static string GetHostWithoutSubDomain(this Uri url)
{
if (url.HostNameType == UriHostNameType.Dns)
{
string host = url.Host;
if (host.Split('.').Length > 2)
{
int lastIndex = host.LastIndexOf(".");
int index = host.LastIndexOf(".", lastIndex - 1);
return host.Substring(index + 1);
}
else
{
return host;
}
}
return null;
}
}
Then, register it in Startup.Auth.cs
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
...
CookieManager = new ChunkingCookieManagerWithSubdomains(),
...
}
);

Related

IOwinContext.Authentication.AuthenticateAsync("ExternalCookie") with Steam auth is randomly null after a couple of succuessful authentications

I've been trying to implement Steam authentication in my ASP.Net web app (ASP.Net Framework 4.8, MVC 5) using Owin and its Steam auth provider (Owin.Security.Providers.Steam).
Followed a couple of tutorials for a similar authentication system but using GitHub and re-adapted that code to be used for login with Steam.
Everything is working fine with a couple of logins but after some time it just breaks and wouldn't authenticate properly.
I'm new to Owin and authenticating users with it so any tips on what I should do to debug it or anything related to Owin that I misinterpreted would be helpful.
I don't know how to explain much of the problem, I was trying to debug it but instead of fixing it I just got more confused, here is my code (only relevant parts):
HomeController.cs
public async Task<ActionResult> Login()
{
// This is always null after a couple of succuessful authentications
var authenticateResult = await HttpContext.GetOwinContext().Authentication.AuthenticateAsync("ExternalCookie");
if(authenticateResult != null)
{
var firstOrDefault = authenticateResult.Identity.Claims.FirstOrDefault(claim => claim.Issuer == "Steam" && claim.Type.Contains("nameidentifier"));
var idString = firstOrDefault?.Value;
var match = _accountIdRegex.Match(idString ?? "");
if (match.Success)
{
var accountID = match.Groups[1].Value;
var steamID = ulong.Parse(accountID);
// User Management Code
return RedirectToAction("Index");
}
}
return RedirectToAction("LoginSteam");
}
public ActionResult LoginSteam()
{
return new ChallengeResult("Steam", Url.Action("Login"));
}
ChallengeResult.cs
internal class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri)
{
LoginProvider = provider;
RedirectUri = redirectUri;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}
And Startup.cs
[assembly: OwinStartup(typeof(ApplicationNamespace.Startup))]
namespace ApplicationNamespace
{
public class Startup
{
public static string steamKey = "";
public void Configuration(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType("ExternalCookie");
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "ExternalCookie",
AuthenticationMode = AuthenticationMode.Passive,
CookieName = ".AspNet.ExternalCookie",
ExpireTimeSpan = TimeSpan.FromMinutes(5)
});
var webconfig = WebConfigurationManager.OpenWebConfiguration("~/");
#if DEBUG
steamKey = webconfig.AppSettings.Settings["steamApiKey"].Value;
#else
steamKey = webconfig.AppSettings.Settings["steamApiKeyRelease"].Value;
#endif
var options = new SteamAuthenticationOptions
{
ApplicationKey = steamKey,
};
app.UseSteamAuthentication(options);
}
}
}
From what I found online, this should be universal and work with any provider, be it Google, Steam, GitHub etc. and it does... for a while... then AuthenticateAsync starts returning null each time and that is where I get confused.
I couldn't find anyone having a similar problem to this online, so I would guess that something is wrong with my code instead of Owin or IIS configuration, what are relevant IIS configs that I should check before testing this again?
I had the same problem. It worked for almost two years and then it started to fail.
Mine was solved by this solution: https://coding.abel.nu/2014/11/catching-the-system-webowin-cookie-monster/
I added
public void ConfigureAuth(IAppBuilder app)
{
app.UseKentorOwinCookieSaver();
as first statement in the StartupAuth.cs and the authorization worked again.

How to setup the Azure Active Directory autentication to a single page

I'm using OWIN combined with Azure Active Directory App Registration as my authentication method on my MVC Web App as below to restrict the login user within a single domain. This part is functioning well.
public partial class Startup
{
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.Redirect("/Home/ErrorPage?message=" + context.Exception.Message);
return Task.FromResult(0);
}
}
});
}
}
Now I want to use another Azure Active Directory App Registration to restrict few users to only one admin configuration page. I don`t know if it doable and how to do it.
This is current controller attribute code to redirect user to a username/password login page before accessing admin configuration page. How can I change it to be redirected to an AAD login. In this way, I can configure the qualified user in AAD without maintain any username and password.
public class ConfigLoginAttribute : AuthorizeAttribute
{
public bool Ignore = true;
public ConfigLoginAttribute(bool ignore = true)
{
Ignore = ignore;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (Ignore == false)
{
return;
}
if (CookieHelper.GetCookie("username") == "")
{
filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary { { "Action", "AdminLogin" }, { "Controller", "Config" } });
return;
}
}
}
I`m new to this area and even English. Hopefully I explained it clear.
Thank you guys so much in advance.

How do I configure Owin to use a custom AuthenticationHandler?

I have read that it's possible to create a custom Owin authentication handler, but I can't figure out how to configure Owin to use my handler instead of the default one.
How do I tell Owin to use this class instead of the default?
public class XDOpenIdAuthHandler: OpenIdConnectAuthenticationHandler
{
public XDOpenIdAuthHandler(ILogger logger)
: base(logger)
{
}
protected override void RememberNonce(OpenIdConnectMessage message, string nonce)
{
//Clean up after itself, otherwise cookies keep building up until we've got over 100 and
// the browser starts throwing errors. Bad OpenId provider.
var oldNonces = Request.Cookies.Where(kvp => kvp.Key.StartsWith(OpenIdConnectAuthenticationDefaults.CookiePrefix + "nonce")).ToArray();
if (oldNonces.Any())
{
CookieOptions cookieOptions = new CookieOptions
{
HttpOnly = true,
Secure = Request.IsSecure
};
foreach (KeyValuePair<string, string> oldNonce in oldNonces)
{
Response.Cookies.Delete(oldNonce.Key, cookieOptions);
}
}
base.RememberNonce(message, nonce);
}
}
You must add it as a part of a custom AuthenticationMiddleware.
public class CustomAuthMiddleware : AuthenticationMiddleware<OpenIdConnectAuthenticationOptions>
{
public CustomAuthMiddleware(OwinMiddleware nextMiddleware, OpenIdConnectAuthenticationOptions authOptions)
: base(nextMiddleware, authOptions)
{ }
protected override AuthenticationHandler<OpenIdConnectAuthenticationOptions> CreateHandler()
{
return new XDOpenIdAuthHandler(yourLogger);
}
}
Then using it in the Startup.Auth for example:
public partial class Startup
{
// For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
app.Use<CustomAuthMiddleware>(new OpenIdConnectAuthenticationOptions());
}
}
Be aware however that the Owin pipeline must not contain the default OpenIdConnectAuthenticationMiddleware, otherwise it will still get called as part of the request pipe.

ASP.NET MVC owin oauth login won't work from different machine

I'm having a weird problem with logging using owin oauth in my test environment.
I create an account from my PC at the office using Google and I'm not able to use the same Google account to login from home or my mobile phone.
That happens with Facebook as well.
Setup:
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
/* Local login implementation */
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/login"),
ExpireTimeSpan = TimeSpan.FromDays(3),
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
/* Login with Google */
var googleOptions = new GoogleOAuth2AuthenticationOptions
{
ClientId = "",
ClientSecret = "",
};
googleOptions.Scope.Add("https://www.googleapis.com/auth/userinfo.profile");
googleOptions.Scope.Add("https://www.googleapis.com/auth/userinfo.email");
app.UseGoogleAuthentication(googleOptions);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
}
}
Oauth Controller
public class oauthcontroller : basecontroller
{
private readonly IUserService _userService;
// Google login button click
public ActionResult google()
{
return new ChallengeResult(LoginProviderEnum.Google.DisplayName, "/oauth/callback");
}
public ActionResult callback()
{
// context is not null
var context = HttpContext.GetOwinContext();
// auth is null
var auth = context.Authentication;
var loginInfo = auth.GetExternalLoginInfo();
//...
}
}
When using my PC at work this works fine and when logging from different machine HttpContext.GetOwinContext().Authentication is null.
UPDATE: I managed to reproduce it in localhost by removing cookie ASP.Net_SessionId
The problem is very well described here:
ASP.NET_SessionId + OWIN Cookies do not send to browser
Quick and dirty fix:
// Google login button click
public ActionResult google()
{
Session["RunSession"] = "1"; // Quick FIX
return new ChallengeResult(LoginProviderEnum.Google.DisplayName, "/oauth/callback");
}

ASP.NET Core Web API Authentication

I'm struggling with how to set up authentication in my web service.
The service is build with the ASP.NET Core web api.
All my clients (WPF applications) should use the same credentials to call the web service operations.
After some research, I came up with basic authentication - sending a username and password in the header of the HTTP request.
But after hours of research, it seems to me that basic authentication is not the way to go in ASP.NET Core.
Most of the resources I found are implementing authentication using OAuth or some other middleware. But that seems to be oversized for my scenario, as well as using the Identity part of ASP.NET Core.
So what is the right way to achieve my goal - simple authentication with username and password in a ASP.NET Core web service?
Now, after I was pointed in the right direction, here's my complete solution:
This is the middleware class which is executed on every incoming request and checks if the request has the correct credentials. If no credentials are present or if they are wrong, the service responds with a 401 Unauthorized error immediately.
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);
if(username == "test" && password == "test" )
{
await _next.Invoke(context);
}
else
{
context.Response.StatusCode = 401; //Unauthorized
return;
}
}
else
{
// no authorization header
context.Response.StatusCode = 401; //Unauthorized
return;
}
}
}
The middleware extension needs to be called in the Configure method of the service Startup class
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMiddleware<AuthenticationMiddleware>();
app.UseMvc();
}
And that's all! :)
A very good resource for middleware in .Net Core and authentication can be found here:
https://www.exceptionnotfound.net/writing-custom-middleware-in-asp-net-core-1-0/
You can implement a middleware which handles Basic authentication.
public async Task Invoke(HttpContext context)
{
var authHeader = context.Request.Headers.Get("Authorization");
if (authHeader != null && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
{
var token = authHeader.Substring("Basic ".Length).Trim();
System.Console.WriteLine(token);
var credentialstring = Encoding.UTF8.GetString(Convert.FromBase64String(token));
var credentials = credentialstring.Split(':');
if(credentials[0] == "admin" && credentials[1] == "admin")
{
var claims = new[] { new Claim("name", credentials[0]), new Claim(ClaimTypes.Role, "Admin") };
var identity = new ClaimsIdentity(claims, "Basic");
context.User = new ClaimsPrincipal(identity);
}
}
else
{
context.Response.StatusCode = 401;
context.Response.Headers.Set("WWW-Authenticate", "Basic realm=\"dotnetthoughts.net\"");
}
await _next(context);
}
This code is written in a beta version of asp.net core. Hope it helps.
To use this only for specific controllers for example use this:
app.UseWhen(x => (x.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)),
builder =>
{
builder.UseMiddleware<AuthenticationMiddleware>();
});
I think you can go with JWT (Json Web Tokens).
First you need to install the package System.IdentityModel.Tokens.Jwt:
$ dotnet add package System.IdentityModel.Tokens.Jwt
You will need to add a controller for token generation and authentication like this one:
public class TokenController : Controller
{
[Route("/token")]
[HttpPost]
public IActionResult Create(string username, string password)
{
if (IsValidUserAndPasswordCombination(username, password))
return new ObjectResult(GenerateToken(username));
return BadRequest();
}
private bool IsValidUserAndPasswordCombination(string username, string password)
{
return !string.IsNullOrEmpty(username) && username == password;
}
private string GenerateToken(string username)
{
var claims = new Claim[]
{
new Claim(ClaimTypes.Name, username),
new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()),
new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddDays(1)).ToUnixTimeSeconds().ToString()),
};
var token = new JwtSecurityToken(
new JwtHeader(new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Secret Key You Devise")),
SecurityAlgorithms.HmacSha256)),
new JwtPayload(claims));
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
After that update Startup.cs class to look like below:
namespace WebAPISecurity
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = "JwtBearer";
options.DefaultChallengeScheme = "JwtBearer";
})
.AddJwtBearer("JwtBearer", jwtBearerOptions =>
{
jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Secret Key You Devise")),
ValidateIssuer = false,
//ValidIssuer = "The name of the issuer",
ValidateAudience = false,
//ValidAudience = "The name of the audience",
ValidateLifetime = true, //validate the expiration and not before values in the token
ClockSkew = TimeSpan.FromMinutes(5) //5 minute tolerance for the expiration date
};
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMvc();
}
}
And that's it, what is left now is to put [Authorize] attribute on the Controllers or Actions you want.
Here is a link of a complete straight forward tutorial.
http://www.blinkingcaret.com/2017/09/06/secure-web-api-in-asp-net-core/
I have implemented BasicAuthenticationHandler for basic authentication so you can use it with standart attributes Authorize and AllowAnonymous.
public class BasicAuthenticationHandler : AuthenticationHandler<BasicAuthenticationOptions>
{
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var authHeader = (string)this.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
{
//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(':', StringComparison.OrdinalIgnoreCase);
var username = usernamePassword.Substring(0, seperatorIndex);
var password = usernamePassword.Substring(seperatorIndex + 1);
//you also can use this.Context.Authentication here
if (username == "test" && password == "test")
{
var user = new GenericPrincipal(new GenericIdentity("User"), null);
var ticket = new AuthenticationTicket(user, new AuthenticationProperties(), Options.AuthenticationScheme);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
else
{
return Task.FromResult(AuthenticateResult.Fail("No valid user."));
}
}
this.Response.Headers["WWW-Authenticate"]= "Basic realm=\"yourawesomesite.net\"";
return Task.FromResult(AuthenticateResult.Fail("No credentials."));
}
}
public class BasicAuthenticationMiddleware : AuthenticationMiddleware<BasicAuthenticationOptions>
{
public BasicAuthenticationMiddleware(
RequestDelegate next,
IOptions<BasicAuthenticationOptions> options,
ILoggerFactory loggerFactory,
UrlEncoder encoder)
: base(next, options, loggerFactory, encoder)
{
}
protected override AuthenticationHandler<BasicAuthenticationOptions> CreateHandler()
{
return new BasicAuthenticationHandler();
}
}
public class BasicAuthenticationOptions : AuthenticationOptions
{
public BasicAuthenticationOptions()
{
AuthenticationScheme = "Basic";
AutomaticAuthenticate = true;
}
}
Registration at Startup.cs - app.UseMiddleware<BasicAuthenticationMiddleware>();. With this code, you can restrict any controller with standart attribute Autorize:
[Authorize(ActiveAuthenticationSchemes = "Basic")]
[Route("api/[controller]")]
public class ValuesController : Controller
and use attribute AllowAnonymous if you apply authorize filter on application level.
As rightly said by previous posts, one of way is to implement a custom basic authentication middleware. I found the best working code with explanation in this blog:
Basic Auth with custom middleware
I referred the same blog but had to do 2 adaptations:
While adding the middleware in startup file -> Configure function, always add custom middleware before adding app.UseMvc().
While reading the username, password from appsettings.json file, add static read only property in Startup file. Then read from appsettings.json. Finally, read the values from anywhere in the project. Example:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public static string UserNameFromAppSettings { get; private set; }
public static string PasswordFromAppSettings { get; private set; }
//set username and password from appsettings.json
UserNameFromAppSettings = Configuration.GetSection("BasicAuth").GetSection("UserName").Value;
PasswordFromAppSettings = Configuration.GetSection("BasicAuth").GetSection("Password").Value;
}
You can use an ActionFilterAttribute
public class BasicAuthAttribute : ActionFilterAttribute
{
public string BasicRealm { get; set; }
protected NetworkCredential Nc { get; set; }
public BasicAuthAttribute(string user,string pass)
{
this.Nc = new NetworkCredential(user,pass);
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var req = filterContext.HttpContext.Request;
var auth = req.Headers["Authorization"].ToString();
if (!String.IsNullOrEmpty(auth))
{
var cred = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(auth.Substring(6)))
.Split(':');
var user = new {Name = cred[0], Pass = cred[1]};
if (user.Name == Nc.UserName && user.Pass == Nc.Password) return;
}
filterContext.HttpContext.Response.Headers.Add("WWW-Authenticate",
String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Ryadel"));
filterContext.Result = new UnauthorizedResult();
}
}
and add the attribute to your controller
[BasicAuth("USR", "MyPassword")]
In this public Github repo
https://github.com/boskjoett/BasicAuthWebApi
you can see a simple example of a ASP.NET Core 2.2 web API with endpoints protected by Basic Authentication.
ASP.NET Core 2.0 with Angular
https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login
Make sure to use type of authentication filter
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

Categories

Resources