Cannot signin using HttpContext.SignInAsync - asp.net-mvc

I'm developing an application using ASP.Net Core MVC 3.1 and i am facing a problem where it fails to sign-in. localhost response 401 unauthorized
AccountController
[HttpPost]
public async Task<IActionResult> Login(PixClient client)
{
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Email, client.Email));
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(principal));
return RedirectToAction("Index", "Home");
}
Startup.cs
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.LoginPath = "/account/login";
options.Cookie.Name = "sessionid";
});
Index.cs
[Authorize]
public IActionResult Index()
{ ...

I checked the codes you've shown,there's no mistake in it.
Make sure you've added the Authentication middleware and it was in correct order:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
.......
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
......
}
And you could create a middleware to check if the ticked is generated and added to cookie successfully:
app.Use(async (context, next) =>
{
var cookies = context.Request.Cookies;
await next.Invoke();
});
I tried as below:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie( m =>
{
m.LoginPath = new Microsoft.AspNetCore.Http.PathString("/Home/Login");
m.Cookie.Name = "CookieAuth";
});
When redirect to /Home/Login,you could see the cookie namedCookieAuth:

Related

This Page isn't working Localhost redirected too many times MVC

Program.cs File with Cookie authentication:
builder.Services.AddAuthentication("CookieAuthentication").AddCookie("CookieAuthentication", options =>
{
options.LoginPath = "/<Login/LoginView";
options.AccessDeniedPath = "/Login/AccessDenied";
});
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Login}/{action=Signup}/{id?}");
app.Run();
Login Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LoginView(string username, string password)
{
if (!ModelState.IsValid)
{
//Error code here
}
if (!UserExists(username, password))//Check if user exists in Database
{
//Error code here
}
TempData["Username"] = username;
return RedirectToAction("Index", "Home");
//I used breakpoint here and this code runs but doesn't work properly.
}
I have also used the [Authorize] attribute on Home Controller to prevent users from accessing it without login.Login/LoginView is the Login rage Path.
This Page isn't working Localhost redirected too many times MVC
For your current scenario,be sure add the [AllowAnonymous] on your Index action in the HomeController. And your LoginPath is /Home/Index, it is no need to be authorized.
[Authorize]
public class HomeController : Controller
{
[AllowAnonymous]
public async Task<IActionResult> Index()
{
//do your stuff...
return View();
}
//....
}
Update:
Cookie authentication to login
Program.cs:
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.LoginPath = "/Login/LoginView";
options.AccessDeniedPath = "/Login/AccessDenied";
});
var app = builder. Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication(); //be sure add authentication and authorization middleware.....
app.UseAuthorization();
//...
How to sigh in the user:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LoginView(string username, string password)
{
if (!ModelState.IsValid)
{
//Error code here
}
if (!UserExists(username, password))//Check if user exists in Database
{
//Error code here
}
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier,username) //add the claims you want...
};
//authProperties you can choose any option you want, below is a sample...
var authProperties = new AuthenticationProperties
{
//IssuedUtc = DateTimeOffset.UtcNow,
//ExpiresUtc = DateTimeOffset.UtcNow.AddHours(1),
//IsPersistent = false
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
TempData["Username"] = username;
return RedirectToAction("Index", "Home");
}

Asp.Net Core Twitch OAuth: Correlation Failed

I configured Twitch authentication for my website using this tutorial: https://blog.elmah.io/cookie-authentication-with-social-providers-in-asp-net-core/
In the Twitch dev console I added the https://localhost:44348/signin-twitch url to the callback urls. I've implemented oauth for other providers before, but having troubles with Twitch.
When I try to login, I get the Twitch authorization screen, but after clicking 'Authorize' it redirects me to /signin-twitch + params which returns a Correlation Failed exception.
Exception: An error was encountered while handling the remote login.
I have a feeling it might have to do with the routing. It's setup like this because I have a frontend application with it's own routing (hence the Fallback)
Here is all relevant code.
public void ConfigureServices(IServiceCollection services)
{
...
services.AddAuthentication(options =>
{
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.LoginPath = "/signin";
options.LogoutPath = "/signout";
})
.AddTwitch(TwitchAuthenticationDefaults.AuthenticationScheme, options =>
{
options.ClientId = "xxx";
options.ClientSecret = "xxx";
options.Scope.Add("user:read:email");
options.SaveTokens = true;
options.AccessDeniedPath = "/";
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapFallbackToController("Index", "Home");
});
}
public class AuthenticationController : Controller
{
[HttpGet("~/signin")]
public IActionResult SignIn(string returnUrl = "")
{
return Challenge(TwitchAuthenticationDefaults.AuthenticationScheme);
}
}
I think that the error occurs because you're trying to access the URL which is assigned as Callback Path.
Try some variant of this:
[HttpGet("~/signin")]
public IActionResult SignIn()
{
var authProperties = _signInManager
.ConfigureExternalAuthenticationProperties("Twitch",
Url.Action("LoggingIn", "Account", null, Request.Scheme));
return Challenge(authProperties, "Twitch");
}
Source: this answer and this one.
Other stuff to check:
Multiple clients with the same Callback Path
CookiePolicyOptions
HTTPS redirect

How do i get this Basic Authentication working in .NET Core

I am using Basic Authentication and I have created a Middleware for this. When I use the Authorize attribute and try to make an API call through Postman, i get 401 Unauthorize even as I am added the authorization details in Postman.
I am not sure if it is the way i am calling the controller action via postman or whether I am missing a header option in postman.
ConfigureServices
services
.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
.AddBasicAuthentication(GetBasicAuthenticationOptions(users));
Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
app.UseCors("SiteCorsPolicy");
app.UseAuthentication();
}
Basic Authentication Implementation
private Action<BasicAuthenticationOptions> GetBasicAuthenticationOptions(IList<UserConfiguration> users)
{
return options =>
{
options.Realm = "Public API";
options.Events = new BasicAuthenticationEvents
{
OnValidatePrincipal = context =>
{
var authenticatedUser = users.FirstOrDefault(u =>
u.Username == context.UserName && u.Password == context.Password);
if (authenticatedUser != null)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name,
context.UserName,
context.Options.ClaimsIssuer)
};
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims,
BasicAuthenticationDefaults.AuthenticationScheme));
context.Principal = principal;
return Task.CompletedTask;
}
return Task.FromResult(AuthenticateResult.Fail("Authentication failed."));
}
};
};
}
Controller Action with Authorize
[Authorize]
[HttpPost]
[Route("test")]
public IActionResult Test()
{
return Json("yes");
}
Postman request
The username and passwords are in the appsettings.json file
The issue was just because app.UseMvc(); was placed before app.UseAuthentication(); . I just had to place app.UseMvc(); after app.UseAuthentication(); and that fixed it.

storing JWT token in cookie in MVC 5

I wanted to make JWT auth in my MVC app. I make Authorization web service in Web API which returns token correctly. After that Im trying to store token in cookie.
[HttpPost]
public async Task<ActionResult> Login(LoginDto loginDto)
{
var token = await loginService.GetToken(loginDto);
if (!string.IsNullOrEmpty(token))
{
var cookie = new System.Web.HttpCookie("token", token)
{
HttpOnly = true
};
Response.Cookies.Add(cookie);
return RedirectToAction("Index", "Product");
}
return View("LoginFailed");
}
But now I wanted to add this token to headers for every request. So I decided action filters would be best for achieve this.
public class CustomActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var token = filterContext.HttpContext.Request.Cookies.Get("token");
if (token != null)
filterContext.HttpContext.Request.Headers.Add("Authorization", $"Bearer {token}");
base.OnActionExecuting(filterContext);
}
}
Startup
public class Startup
{
public void Configuration(IAppBuilder app)
{
AutofacConfig.Configure();
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
ConfigureOAuth(app);
}
public void ConfigureOAuth(IAppBuilder app)
{
var issuer = System.Configuration.ConfigurationManager.AppSettings["issuer"];
var audience = System.Configuration.ConfigurationManager.AppSettings["appId"];
var secret = TextEncodings.Base64Url.Decode(System.Configuration.ConfigurationManager.AppSettings["secret"]);
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audience },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
},
});
}
}
And then I just marked controller which authorize attribute. It works fine when I called it with POSTMAN.
But action filters in MVC are fired always after authorization filter. So I have questions:
How to add token from cookie to every request ? Is it good practice? If not what I should do?
How about csrf attacks and others ? Is AntiForgeryTokenAttr will do the work? What about ajax calls then?
Additional Information
This is how login service looks like. Its just making call to auth endpoint.
public class LoginService : ILoginService
{
public async Task<string> GetToken(LoginDto loginDto)
{
var tokenIssuer = ConfigurationManager.AppSettings["issuer"];
using (var httpClient = new HttpClient {BaseAddress = new Uri($"{tokenIssuer}/oauth2/token")})
{
using (var response = await httpClient.PostAsync(httpClient.BaseAddress, new FormUrlEncodedContent(
new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", loginDto.Username),
new KeyValuePair<string, string>("password", loginDto.Password),
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("client_id", ConfigurationManager.AppSettings["appId"])
})))
{
var contents = await response.Content.ReadAsStringAsync();
if (response.StatusCode == HttpStatusCode.OK)
{
var deserializedResponse =
new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(contents);
var token = deserializedResponse["access_token"];
return token;
}
}
return null;
}
}
}
I found a solution. I just make custom OAuthBearerAuthenticationProvider provider and inside this class Im retrieve token from cookie and then assign this to context.Token
public class MvcJwtAuthProvider : OAuthBearerAuthenticationProvider
{
public override Task RequestToken(OAuthRequestTokenContext context)
{
var token = context.Request.Cookies.SingleOrDefault(x => x.Key == "token").Value;
context.Token = token;
return base.RequestToken(context);
}
}
And then inside startup.cs
public class Startup
{
public void Configuration(IAppBuilder app)
{
AutofacConfig.Configure();
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
ConfigureOAuth(app);
}
public void ConfigureOAuth(IAppBuilder app)
{
var issuer = System.Configuration.ConfigurationManager.AppSettings["issuer"];
var audience = System.Configuration.ConfigurationManager.AppSettings["appId"];
var secret = TextEncodings.Base64Url.Decode(System.Configuration.ConfigurationManager.AppSettings["secret"]);
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audience },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
},
Provider = new MvcJwtAuthProvider() // override custom auth
});
}
}

Asp.Net MVC 6 Identity 3 MongoDB External Login (Facebook)

I'm running the RC1 of ASP.NET MVC 6 and would like to use a MongoDB Identity Provider.
I have implemented the provider by Grant Megrabyan which is doing a great job of registering new users and allowing them to log in but I get the error:
InvalidOperationException: No authentication handler is configured to handle the scheme: Microsoft.AspNet.Identity.External
Microsoft.AspNet.Http.Authentication.Internal.DefaultAuthenticationManager.d__13.MoveNext()
I had the external login previously working using EntityFramework so I'm assuming my configuration for third party auth is probably correct.
When the user clicks login with Facebook they are redirected to the following action :
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return new ChallengeResult(provider, properties);
}
There is no exception thrown at this point however when the Facebook returns from the ChallengeResponse it sends a GET to : http://localhost:51265/signin-facebook?code=[facebook user token].
At this point ASP.NET throws the exception:
The callback url made by Facebook doesn't seem to make sense. Surely it should return to my ExternalLoginCallback action?
It's about here that I'm out of ideas?!
If anyone can see where I've gone wrong then I'd be a very happy guy.
My startup.cs:
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ApplicationDbContext>();
// Add framework services.
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddMongoStores<ApplicationDbContext, ApplicationUser, IdentityRole>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
app.UseStaticFiles();
app.UseFacebookAuthentication(options =>
{
options.AppId = "removed";
options.AppSecret = "removed";
});
app.UseIdentity();
app.UseMvcWithDefaultRoute();
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
Call UseFacebookAuthentication after UseIdentity, but before UseMvc;
app.UseIdentity();
app.UseFacebookAuthentication(options =>
{
options.AppId = "removed";
options.AppSecret = "removed";
});
app.UseMvcWithDefaultRoute();
Edit:
I think the problem is the Order of defining configurations. Try to add Identity first then Facebook Authentication.
** Suggested Example **
app.UseIdentity();
app.UseMvcWithDefaultRoute();
app.UseFacebookAuthentication(options =>
{
options.AppId = "removed";
options.AppSecret = "removed";
});

Resources