OWIN Authentication And Timeout - owin

I am using MVC 5 with OWIN Authentication.
Here are the code for my StartUp.cs.
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
ExpireTimeSpan = new TimeSpan(60000000000)
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}
The expiration time is set to 60000000000 nano seconds.
Now the requirement is when the cookie is expired, I need to redirect to Login screen.
How to do that?

Hope this will help someone to debug...
The error is in web.config file
<system.webServer>
<modules>
<remove name="FormsAuthenticationModule" />
</modules>
<system.webServer>
here the name Forms authenticationModule is a typo. it should be
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
<system.webServer>
And voilla it started working.

I found this example is more better:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(15),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
},
SlidingExpiration = false,
ExpireTimeSpan = TimeSpan.FromMinutes(30)
});
Paste code above in Startup.Auth.cs file from App_Start folder.

Related

How to get all secrets from Azure Key Vault and then load into configuration object using ASP.Net Core

I am working on to integrate the Azure Key Vault in ASP.NETCore 2.1 Azure WebJob. For that I tried to use the following code for WebJob.
.NetCore WebJob: Program.cs
private static IConfiguration GetConfiguration(ServiceCollection services)
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
// build config
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
var keyVault = configuration.GetSection("KeyVault");
configuration.AddAzureKeyVault(
$"https://{keyVault["Vault"]}.vault.azure.net/",
keyVault["ClientId"],
keyVault["ClientSecret"]);
return configuration;
}
But I am getting the following error:
IConfigurationBuilder Does Not Contain Definition for AddAzureKeyVault
I have used the following NuGet packages:
<PackageReference Include="Microsoft.Azure.KeyVault" Version="2.3.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="2.1.1" />
If you want to use Azure key vault in web job, please refer to the following code
Sdk
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="3.0.6" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="3.0.10" />
<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.1.0" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
Program.cs
class Program
{
static async Task Main()
{
var builder = new HostBuilder();
builder.ConfigureWebJobs(b =>
{
b.AddAzureStorageCoreServices();
b.AddAzureStorage();
});
builder.ConfigureLogging((context, b) =>
{
b.AddConsole();
});
var host = builder.Build();
using (host)
{
await host.RunAsync();
}
}
}
Functions.cs
public class Functions
{
public static void ProcessQueueMessage([QueueTrigger("queue")] string message, ILogger logger)
{
// create IConfigurationRoot to read appsetting.json
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
// create IConfigurationRoot to read Azure key vault
IConfigurationRoot config = new ConfigurationBuilder()
.AddAzureKeyVault(
$"https://{configuration["KeyVaultName"]}.vault.azure.net/",
configuration["AzureADApplicationId"],
configuration["AzureADCert"],
new DefaultKeyVaultSecretManager())
.Build();
// read one secret in Azure key vault
var str = config["hurysecret"];
logger.LogInformation(message + "\n str: " +str);
}
}

How to enable bundling in ASP.NET MVC 5

I was playing a little bit to prevent bundling files and now I am stuck at how to return them to be a bundled.
I tried to set debug=false, also I entered BundleOptimization to true and I have files separated.
My BundleCOnfig.cs looks like:
public class BundleConfig
{
// For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
BundleTable.EnableOptimizations = true;
#region Styles bundles
var bundlesCSS = new StyleBundle("~/bundles/css")
.Include("~/Content/css/libs/bootstrap/bootstrap.css")
//.Include("~/Content/css/libs/fontawesome/font-awesome.css")
.Include("~/Content/css/libs/camera/camera.css")
.Include("~/Content/css/libs/fontawesome/font-awesome.css", new CssRewriteUrlTransformWrapper());
var bundlesCustom = new StyleBundle("~/bundles/css/custom")
.Include("~/Content/css/custom/general.css")
bundlesCSS.Orderer = new AsIsBundleOrderer();
bundlesCustom.Orderer = new AsIsBundleOrderer();
bundles.Add(bundlesCSS);
bundles.Add(bundlesCustom);
bundles.Add(new StyleBundle("~/bundles/hotel-datepicker-css").Include(
"~/Content/css/libs/baguetteBox.min.css",
"~/Content/css/hotel-datepicker/hotel-datepicker.css"
));
#endregion
}
}
and my web.config looks like this:
<?xml version="1.0"?>
<system.web>
<compilation debug="false" targetFramework="4.7.2"/>
<httpRuntime targetFramework="4.7.2"/>
<httpModules>
<add name="TelemetryCorrelationHttpModule"
type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation"/>
</httpModules>
</system.web>
Have you added below line of code in Application_Start() of Global.asax.cs file?
BundleConfig.RegisterBundles(BundleTable.Bundles);
if yes, then BundleTable.EnableOptimizations = true enables bundling and minification in debug mode. If you set it to false then it will not do bundling and minification.

No assembly found containing a Startup or [AssemblyName].Startup class

I've tried resolving this from answers in other and similar posts, but no luck.
I'm Using MVC 5, framework 4.8 latest VS2017.
Thanks
My Config is: (including other attempts)
<configuration>
<appSettings>
<!--<add key="owin:AutomaticAppStartup" value="false" />-->
<add key="owin:HandleAllRequests" value="true"/>
<!--<add key="owin:AppStartup" value="Api.xxx" />-->
</appSettings>
</configuration>
Startup class is:
[assembly: OwinStartupAttribute(typeof(Api.xxx.Startup))]
namespace Api.xxx
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Allow all origins
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
….
}
}
}
and Api is:
namespace Api.xxx
{
[Route("values")]
public class ValuesController : ApiController
{
private static readonly Random _random = new Random();
public IEnumerable<string> Get()
{
var random = new Random();
return new[]
{
_random.Next(0, 10).ToString(),
_random.Next(0, 10).ToString()
};
}
}
}
I think you need to change
[assembly: OwinStartupAttribute(typeof(Api.xxx.Startup))]
to
[assembly: OwinStartup(typeof(Api.xxx.Startup))]
Reference: https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-startup-class-detection

web api get is working but post and delete not working after published in iis

I've been struggling for 4 hours and I still didn't get any solution. I already apply some modification but still my post and delete api returns the error 500.
GET js
$.getJSON(API_URL + 'api/claim/search', params).done(function (data) {
myJsonObject = data;
d.resolve(data);
});
return d.promise();
API
[Route("api/claim/search")]
[System.Web.Http.AcceptVerbs("GET")]
[System.Web.Http.HttpGet]
public IEnumerable<ClaimInfo> Get([FromUri] ClaimSearch obj_ClaimSearch)
{
//my code
}
This get method is working 100%
POST js
$.ajax({
type: "POST",
data: JSON.stringify(p[0]),
url: API_URL + "api/claim/" + (editorPage === "resubmission" ? "saveresubmissionpatient": "savepatient"),
contentType: "application/json",
success: function (data) {
},
error: function () {
}
});
API
[Route("api/claim/savepatient")]
[System.Web.Http.AcceptVerbs("POST")]
[System.Web.Http.HttpPost]
public Guid SavePatient([FromBody]ClaimInfo claimInfo)
{
//my code
}
And here is my WebApi.Config.cs
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
I already apply this webserver thing in my config
<modules>
<remove name="WebDAVModule" />
<add type="DevExpress.Web.ASPxHttpHandlerModule, DevExpress.Web.v16.2, Version=16.2.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" name="ASPxHttpHandlerModule" />
</modules>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
I had a similar issue, and it had to do with the name of the function catching the request. For some reason, GET functions did this automatically but POST did not always do so. You could try explicitly naming it like this, and see if it also solves your problem:
[Route("api/claim/savepatient")]
[System.Web.Http.AcceptVerbs("POST")]
[System.Web.Http.HttpPost, ActionName("SavePatient")]
public Guid SavePatient([FromBody]ClaimInfo claimInfo)
{
//my code
}
Note that I changed [System.Web.Http.HttpPost] to [System.Web.Http.HttpPost, ActionName("SavePatient")]
You have named the action "savepatient" instead of Post. The router matches /api/{controller} to your {controller}Controller Class. The HTTP method must match the public method of the class. Try renaming "SavePatient" to "Post" (or "Put" if you use that method).
public class ClaimController : ApiBaseController
{
//[Route("api/claim/")] don't need this
public Guid Post([FromBody]ClaimInfo claimInfo)
{
//my code to add new claiminfo
}
//[Route("api/claim/")] don't need this
public Guid Put([FromBody]ClaimInfo claimInfo)
{
//my code to edit claiminfo
}
And remove the extra path on the url:
url: API_URL + "api/claim/"

404 Not Found error when running ServiceStack on IIS8 Express

Regarding to this thread: 404 Not found
I still have this issue on Win 8.1 - VS 2013-1
<!--<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>-->
<location path="api">
<system.web>
<httpHandlers>
<add path="*" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" />
</httpHandlers>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<add path="*" name="ServiceStack.Factory" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
</handlers>
</system.webServer>
and
public class HelloAppHost : AppHostBase
{
/// <summary>
/// Initializes a new instance of your ServiceStack application, with the specified name and assembly containing the services.
/// </summary>
public HelloAppHost() : base("Hello Web Services", typeof(HelloService).Assembly) { }
/// <summary>
/// Configure the container with the necessary routes for your ServiceStack application.
/// </summary>
/// <param name="container">The built-in IoC used with ServiceStack.</param>
public override void Configure(Container container)
{
//Register user-defined REST-ful urls. You can access the service at the url similar to the following.
//http://localhost/ServiceStack.Hello/servicestack/hello or http://localhost/ServiceStack.Hello/servicestack/hello/John%20Doe
//You can change /servicestack/ to a custom path in the web.config.
SetConfig(new HostConfig
{
HandlerFactoryPath = "api"
});
SetConfig(new HostConfig { DebugMode = true });
Routes
.Add<Hello>("/hello")
.Add<Hello>("/hello/{Name}");
}
}
When I uncomment the second system.webServer tag, I only get HandlerNotFound Exceptions from the api route. When I remove the location tag in web.config the same errors occur.
Like it is now it works ...
Any help for clarification appreciated,
thanks Norbert
You need to change the following:
SetConfig(new HostConfig
{
HandlerFactoryPath = "api"
});
SetConfig(new HostConfig { DebugMode = true });
to
SetConfig(new HostConfig
{
HandlerFactoryPath = "/api",
DebugMode = true
};
Just a guess, but your second instance of HostConfig is probably overriding the first one.

Resources