MVC 5 Forms authentication retuns null for User.Identity.Name - asp.net-mvc-5

Authentication fails to authenticate for forms authentication in my MVC 5 application. Page gets redirected correctly, but User.Identity.IsAuthenticated and User.Identity.Name values are empty.
My webconfig,
<system.web>
<authentication mode="Forms">
<forms cookieless="UseCookies" defaultUrl="~/" loginUrl="~/user/signin" name="MYAPPWeb" timeout="21600" slidingExpiration="true"/>
</authentication>
UserController,
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult SignIn(SignInViewModel user)
{
UserDTO userObj;
using (var services = new ServiceFactory())
{
userObj = services.UserManagement.ValidateLoginDetails(ConfigHelper.EnvironmentString, user.TenantName, user.Username, user.Password);
}
string userID = userObj.UserID.ToString();
//FormsAuthentication.RedirectFromLoginPage(userID, user.RememberMe);
FormsAuthentication.SetAuthCookie(userID.ToString(),true);
FormsAuthentication.RedirectFromLoginPage(userID, false); //DO NOT REMEMBER ME
}
HomeController (Default page)
public ActionResult Index()
{
bool x = User.Identity.IsAuthenticated; //false?
string y = User.Identity.Name; //null?
return View();
}
It looks pretty straight forward, am I missing something? Please help!
Note:
When I create the project I selected windows authentication. It created some Owin authenticaiton related configuration cs files (startup.auth.cs). I have removed them and added the above appsetting entry as it is required to stop loading Owin assemblies.
<add key="owin:AutomaticAppStartup" value="false"/>

If your project has Owin authentication by default, it will remove form authentication from the project.
If you see your web config you may see
<remove name="FormsAuthentication" />
configuration.
Simply remove it.
I had the same problem and it solved the issue.

Related

Connection String for EntityFramework Core in Azure Web App

I'm having an issue with an Azure SQL DB (SQL PaaS) connection string in my Azure Web App. It is defined in the "Connection Strings" settings of the Application Config. I see the Conn String value (format below) in https://myAppName.scm.azurewebsites.net/Env.cshtml#connectionStrings. My defined Conn String name is "MyApp" and Azure is prefixing it with "SQLAZURECONNSTR_" as you'd expect.
SQLAZURECONNSTR_MyApp = Server=tcp:mysvr.database.windows.net,1433;Initial Catalog=MyApp;Persist Security Info=False;User ID=user#mysvr;Password=passWord;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
In Startup.cs, I have this though I'm not certain it is necessary.
public void ConfigureServices(IServiceCollection services)
{
[...]
services.AddDbContext<MyAppContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyApp")));
And in my database context class, I have the following:
public partial class MyAppContext : DbContext
{
[...]
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true)
.Build();
var connectionString = configuration.GetConnectionString("MyApp");
optionsBuilder.UseSqlServer(connectionString);
}
}
}
When accessing the web app executing a method that connects to the database, I'm receiving a null reference to the conn string.
ArgumentNullException: Value cannot be null. (Parameter 'connectionString')
Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(string value, string parameterName)
Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, string connectionString, Action<SqlServerDbContextOptionsBuilder> sqlServerOptionsAction)
myapp.Models.MyAppContext.OnConfiguring(DbContextOptionsBuilder optionsBuilder) in MyAppContext.cs
No conn strings are defined in the local .json file, though I'll want to add that back for development purposes at some point.
NEWEST
Code First.
Database Initialization in Entity Framework 6
connectionStr should be like this.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="SchoolDBConnectionString" connectionString="tcp:servername.database.windows.net,1433;Initial Catalog=db; Persist Security Info=False; User ID=user;Password=mypassword; MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
PRIVIOUS
DB First.
Your project use ef core, so the connectionstrings should be like below.
<connectionStrings>
<add name="SchoolDBEntities" connectionString="metadata=res://*/SchoolDB.csdl|res://*/SchoolDB.ssdl|res://*/SchoolDB.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=SchoolDB;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient"/>
</connectionStrings>
For more details, you can refer my answer in the post.
Timeout period elasped prior to obtaining a connection from the pool - Entity Framework
You can also refer to this tutorial, which will help you.
Entity Framework Tutorial

Trying to change policies at runtime : IDX10501: Signature validation failed. Unable to match keys: kid

I want to have the user decide wether to use the standard login or with TOTP.
My Setup:
<add key="ida:SignUpSignInPolicyId" value="B2C_1_signupsignin_1" />
<add key="ida:EditProfilePolicyId" value="B2C_1_profileediting1" />
<add key="ida:ResetPasswordPolicyId" value="B2C_1_passwordreset1" />
In the code do following:
public void SignUpSignInTOTP(string redirectUrl)
{
redirectUrl = redirectUrl ?? "/";
HttpContext.GetOwinContext().Set("Policy", Globals.TOTPPasswordPolicyId);
// Use the default policy to process the sign up / sign in flow
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = redirectUrl });
return;
}
where as
public static string TOTPPasswordPolicyId = ConfigurationManager.AppSettings["ida:TOTPPasswordPolicyId"];
If I set the the TOTPPasswordPolicyId in the ida:SignUpSignInPolicyId it works fine. But if I change it at runtime I get the error.
IDX10501: Signature validation failed. Unable to match keys: kid
I do not understand why this is happening? Any sugestions?
The B2C_1_signupsignin_1 is a user flow and the B2C_1A_TOTP_signup_signin is a custom policy.
Can this maybe be the problem. Is it not possible to mix these?
regards
Stefan

Umbraco Preview not showing the correct content

When I have the following key in my web.config, umbraco preview is working fine, showing me the correct content but I can not login to my web site, I can login to umbraco backoffice without any problem.
When I comment out the following key, then I can login to my web site but this time umbraco preview is not showing the correct content.
What should I do to make preview work and at the same time I can login to my front end site? I have already searched for a solution, but I haven't managed to fix this so far. Any help is appreciated.
Umbraco version 7.4.3 assembly: 1.0.5948.18141
The key:
<add key="owin:appStartup" value="UmbracoDefaultOwinStartup" />
My OwinStartup class:
[assembly: OwinStartup(typeof(OwinStartup), "Configuration")]
namespace ABC.XYZ.Site
{
public class OwinStartup : UmbracoDefaultOwinStartup
{
public override void Configuration(IAppBuilder app)
{
base.Configuration(app);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies"
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions());
app.Use((context, next) =>
{
var loggedInMarkerCookie = context.Request.Cookies[Settings.CookieLoggedInMarkerName];
var autoLoginAttempt = context.Request.Cookies[Settings.CookieLoggedInMarkerAttemptName];
if (!context.Authentication.User.Identity.IsAuthenticated && !context.Request.Path.Value.StartsWith("/sso/") && (loggedInMarkerCookie != null && autoLoginAttempt == null))
{
context.Response.Cookies.Append(Settings.CookieLoggedInMarkerAttemptName, DateTime.Now.ToString(), new CookieOptions { Expires = DateTime.Now.AddMinutes(30) });
context.Authentication.Challenge();
}
return next.Invoke();
});
}
}
}
Your App Setting needs to be:
<add key="owin:appStartup" value="ABC.XYZ.Site, OwinStartup" />
And looking at the source I think that you need to call base.Configuration(app); after you've added your custom configuration.

ServiceStack Basic Authentication HtmlRedirect is not respected by MVC ServiceStackController

I'm probably not understanding something but I have the issue below:
AppHost.cs
Plugins.Add(new AuthFeature(
() => new AuthUserSession(),
new IAuthProvider[] { new BasicAuthProvider() }) { HtmlRedirect = null });
HomeController.cs
[Authenticate]
public class HomeController : ServiceStackController
The issue
The issue is that when I try to access the HomeController, I am redirected to ~/login?redirect=.....
I would assume that by setting HtmlRedirect to null, would also affect the MVC controllers too, but it doesn't seem to.
Is this expected behaviour? or is am I doing something wrong?
My end goal is to have the browser prompt with a challenge / response basic auth box.
Since this commit you are able to override the default behavior when authentication failed:
[Authenticate]
public class HomeController : ServiceStackController
{
public override ActionResult AuthenticationErrorResult
{
get
{
//return 401 Unauthorized for example
return new HttpStatusCodeResult(401);
}
}
}
ServiceStackController.AuthorizationErrorResult can be modified in the same way.
Setting HtmlRedirect to null doesn't work in this case, because the behavior of the [Authenticate] attribute (and all other ServiceStack attributes) is slightly different when used with ASP.net MVC controllers instead of ServiceStack services.
I have been on the ServiceStack Jabbr chat page and was told that this is a bug and a fix will be put on today!
https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack.FluentValidation.Mvc3/Mvc/ExecuteServiceStackFiltersAttribute.cs#L25

jsf spring security session timeout viewExpiredException

I have the following problem with the timeouts in Spring Security with JSF:
I've customized the sessionmanagement filter so that the user is redirected to the invalidSessionUrl just if the requested page is secured (i.e. if it is allowed just for authenticated users). The custom code I put into the session management filter provided by Spring Security is:
if (invalidSessionUrl != null) {
String pagSolicitada = UtilSpringSecurity.extraerPagina(request);
if ( UtilSpringSecurity.paginaAutenticada(pagSolicitada ) ) {
request.getSession();
redirectStrategy.sendRedirect(request, response, invalidSessionUrl);
return;
}
//the requested page doesn't require the user to be authenticated
//so i just skip this filter and continue with the filter chain
chain.doFilter(request, response);
return;
}
The method "UtilSpringSecurity.extraerPagina(request)" returns the requested page this way:
public static String extraerPagina (HttpServletRequest request) {
String uri = request.getRequestURI().toLowerCase();
String cPath = request.getContextPath().toLowerCase();
// uri = cPath + pagina
int longCPath = cPath.length();
String pagina = uri.substring(longCPath);
return pagina;
}
And the method "UtilSpringSecurity.paginaAutenticada(pagSolicitada)" returns true if the the param is a page that requires the user to be authenticated (I do the check with IFs, considering the intercept-url elements of my xml security config file which have the attribute access="isAuthenticated()"):
public static boolean paginaAutenticada (String pagina) {
if (pagina.startsWith("/faces/paginas/administracion/") || pagina.startsWith("/faces/paginas/barco/") ) {
return true;
}
return false;
}
This solution works, but it has just one problem:
If I leave the browser staying idle at a page until the session timeout expires, and then I request the same page, then I get a "viewExpiredException". This is because the filter worked well, it bypassed the redirection to the invalidSessionUrl, but as the session expired anyway, then I get that exception trying to re-render the same page.
If I request any other unsecured page when the session timout has expired, it works well, it redirects correctly to the page and I don't get the viewExpiredException.
Anyone knows how to solve this?
Thank you in advance.
Spring security should give you anonymous access to sets of pages for an un-authenticated user. Below is an excerpt of my XML configuration for how I achieved this.
<http auto-config="true" access-denied-page="/unauthorized.xhtml" >
<intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
<intercept-url pattern="/app/**" access="ROLE_USER,ROLE_ADMIN" />
<intercept-url pattern="/*.xhtml" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<form-login login-page="/login.xhtml" login-processing-url="/j_spring_security_check"
authentication-success-handler-ref="authenticationSuccessBean"
authentication-failure-handler-ref="authenticationFailureBean" />
<session-management invalid-session-url="/login.xhtml" >
</session-management>
</http>
I essentially use intercept-url tags to claim that pages within certain relative contexts can only be accessed by the following roles. You can see that all pages at the web application default context are available to anonymous users. If the user is unauthorized to view the page then they will be redirected to access-denied-page.
The only catch is that your User bean has to implement the UserDetails interface and have a property that returns a role bean which implements the GrantedAuthority interface. Spring will look for a UserDetails to have a GrantedAuthority property to determine what the role is. If this user does not exist, is unauthenticated, or unknown then it will default to anonymous role.
Finally I solved it. It's a JSF issue, nothing to do with Spring Security.
I've overriden the restoreView method of jsf this way:
#Override
public UIViewRoot restoreView(FacesContext facesContext, String viewId) {
UIViewRoot root = wrapped.restoreView(facesContext, viewId);
if(root == null) {
root = createView(facesContext, viewId);
}
return root;
}
Now the problem is that if the page had parameters, I lost them when I do the post to the recently created view, but that's another distinct issue (PRG pattern) dealing again with JSF.

Resources