ITfoxtec SAML 2.0 with NET 5.0- Set cookie name - itfoxtec-identity-saml2

I'm implementing an ASP.NET Core webb application using .NET 5.0. We would like to set our own cookie-name and I can't find how to achieve that.
Is there any way to set your own cookie-name when using ITfoxtec SAML 2.0 with .NET 5.0?

The ITfoxtec Identity SAML 2.0 package use the .NET infrastructure as much as possible. The authentication cookie is handled by the ASP.Net core authentication.
You need to implement your own version of Saml2ServiceCollectionExtensions and set the o.Cookie.Name = "somenewname".
Like this:
public static IServiceCollection AddSaml2(this IServiceCollection services, string loginPath = "/Auth/Login", bool slidingExpiration = false, string accessDeniedPath = null, ITicketStore sessionStore = null, SameSiteMode cookieSameSite = SameSiteMode.Lax, string cookieDomain = null)
{
services.AddAuthentication(Saml2Constants.AuthenticationScheme)
.AddCookie(Saml2Constants.AuthenticationScheme, o =>
{
o.Cookie.Name = "somenewname";
o.LoginPath = new PathString(loginPath);
o.SlidingExpiration = slidingExpiration;
if(!string.IsNullOrEmpty(accessDeniedPath))
{
o.AccessDeniedPath = new PathString(accessDeniedPath);
}
if (sessionStore != null)
{
o.SessionStore = sessionStore;
}
o.Cookie.SameSite = cookieSameSite;
if (!string.IsNullOrEmpty(cookieDomain))
{
o.Cookie.Domain = cookieDomain;
}
});
return services;
}

Related

How to configure an mvc client running on .Net Framework 4.7.1 to Authenticate with IdentityServer4 (3.1) running on .Net Core

I am not sure how to configure an mvc client running on .Net Framework 4.7.1 to Authenticate with IdentityServer4 (3.1) running on .Net Core.
I have successfully authenticated clients running on .net core against IdentityServer4 before but not a client running on .Net Framework. I can't upgrade this client to .net core unfortunately.
Basically, I am not sure how to do this on the mvc client:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.Authority = "https://myIdentityServer:4532";
options.ClientId = "MVC_Net_Framework";
options.ClientSecret = "mysecret";
options.ResponseType = "code";
options.Scope.Add("myScope");
options.SaveTokens = true;
});
}
you need to use OwinStartup class . add partial class Startup in root of your project as
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Cors;
using System.Web.Http;
using System.Web.Mvc;
using System.Configuration;
[assembly: OwinStartup(typeof(MCVAppNet7.Startup))]
namespace MCVAppNet7
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
var services = new ServiceCollection();
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
ConfigureAuth(app);
// For Access-Control-Allow-Origin
app.UseCors(CorsOptions.AllowAll);
}
}
}
after this create a new file "Startup.Auth.cs" in "App_Start" folder and inside this create partial Startup class
using System.Configuration;
using Owin;
using Microsoft.Owin.Security.Cookies;
using IdentityServer3.AccessTokenValidation;
using System;
namespace MCVAppNet7
{
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
try
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies"
});
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "",
ClientId = "",
AuthenticationType = "Bearer",
RequiredScopes = new[] { "" },
ValidationMode = "",
PreserveAccessToken = true,
RequireHttps = ""
});
}
catch (Exception ex)
{
throw ex;
}
}
}
}
install these package from from NuGet
Microsoft.Owin
Microsoft.Owin.Security.OAuth
Microsoft.Owin.Host.SystemWeb
IdentityModel
IdentityServer3.Contrib.AccessTokenValidation
I'm using IdentityServer3.Contrib.AccessTokenValidation and it's working for me but it might work with IdentityServer4.AccessTokenValidation and more info here
https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-startup-class-detection
ASP.NET Web Api - Startup.cs doesn't exist
https://github.com/IdentityServer/IdentityServer4/issues/4188

ITfoxtec.Identity.Saml2 - multiple authentication schemas

Is there a way to integrate into the same project SAML authentication and form authentication?
I have today only SAML authentication:
services.AddSaml2("/login", true);
If I add another schema after the SAML, the SAML stops working. If I add it before, the from authentication is not triggered.
This is a code of the form authentication:
services.AddAuthentication("Form")
.AddScheme<FormAuthenticationOptions, FormAuthenticationHandler>("Form", null)
.AddCookie(options => {
options.LoginPath = "....";
options.LogoutPath = "...";
options.EventsType = typeof(CustomCookieAuthenticationEvents);
});
Please, advise.
I checked it and cause it to work only as follows:
// Add SAML2 schema
services.AddAuthentication(Saml2Constants.AuthenticationScheme)
.AddCookie(Saml2Constants.AuthenticationScheme, o => {
o.LoginPath = new PathString("loginPath");
o.SlidingExpiration = true;
}
);
services.AddAuthentication("TMP")
.AddPolicyScheme("TMP", "TMP Authorization", options => {
options.ForwardDefaultSelector = context => {
if (context.Request.Headers["Form"].Any() || context.Request.Cookies.ContainsKey("Form")) {
return FormAuthenticationOptions.Schema;
}
return Saml2Constants.AuthenticationScheme;
};
})
.AddScheme<FormAuthenticationOptions, FormAuthenticationHandler>("Form", null)
.AddCookie(options => {
options.LoginPath = LoginPath ;
options.LogoutPath = LogoutPath ;
options.EventsType = typeof(CustomCookieAuthenticationEvents);
});
The reason for it that itfoxtec adds its schema as default. So I added my schema policy and make the decision as to what schema to go by adding an HTTP header and cookie.
Not so elegant, but works.
I think it will be nice you'll enable only add your library by adding it like this
.AddScheme<SamlAuthenticationOptions, SamlAuthenticationHandler>(FormAuthenticationOptions.Schema, null)
and move the authentication logic to SamlAuthenticationHandler.
You cannot use the services.AddSaml2 in this case because the method do not return the AuthenticationBuilder.
https://github.com/ITfoxtec/ITfoxtec.Identity.Saml2/blob/master/src/ITfoxtec.Identity.Saml2.MvcCore/Configuration/Saml2ServiceCollectionExtensions.cs#L15
Instead, you have to use the code from the method in combination with the new authentication schema(s).
Maybe it would be something like this, but I have not tried it:
services.AddAuthentication(Saml2Constants.AuthenticationScheme)
.AddCookie(Saml2Constants.AuthenticationScheme, o =>
{
o.LoginPath = new PathString(loginPath);
o.SlidingExpiration = slidingExpiration;
if(!string.IsNullOrEmpty(accessDeniedPath))
{
o.AccessDeniedPath = new PathString(accessDeniedPath);
}
})
.AddScheme<FormAuthenticationOptions, FormAuthenticationHandler>("Form", null);

How to Consume Secured Web Api from C# MVC and AngularJS

How to Consume Secured Web Api from other application C# MVC and AngularJS .
[Authorize(Users = "Steve,Mike")]
public class EmployeeController : ApiController
{
MyDB db = new MyDB();
public IEnumerable<EmployeeViewModel> GetAllEmployee()
{
return db.Employee.Select(item => new EmployeeViewModel { EmpID = item.EmpID, Name = item.Name, Region = item.Region }).ToList();
}
}
The following code I can get without Secure WebApi from AngularJS
var ft = searchText.toLowerCase();
$http.get('/api/Employee/GetAllEmployee').success(function (largeLoad) {
data = largeLoad.filter(function (item) {
return JSON.stringify(item).toLowerCase().indexOf(ft) != -1;
});
$scope.setPagingData(data, page, pageSize);
});
Your help is highly appreciated...
what kind of Secured Web Api do you want to consume?
you may think about oAuth

WPF to authenticate against ASP.NET MVC Rest Service using basic authentication

I'm working on a WPF application which is consuming an ASP.NET MVC (Restful Behavior). MVC application is using Basic Authentication. So, how can I authenticate my WPF application to access MVC Url? Please suggest.
Thanks
You could use an HttpClient:
using (var client = new HttpClient())
{
var username = "john";
var password = "secret";
var buffer = Encoding.ASCII.GetBytes(string.Concat(username, ":", password));
var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(buffer));
client.DefaultRequestHeaders.Authorization = authHeader;
var task = client.GetAsync("https://example.com/somemethod");
if (task.Result.StatusCode == HttpStatusCode.Unauthorized)
{
Console.WriteLine("wrong credentials");
}
else
{
task.Result.EnsureSuccessStatusCode();
Console.WriteLine(task.Result.Content.ReadAsAsync<string>().Result);
}
}

Silverlight ActiveDirectore Autentification

How i can get Current User. And how i can validate user via Active Directory by user and pass.
You should use ASP.NET authentification to achieve this. In order to implement this, I would strongly recommend you to use something as RIA Services, which contains all the plumbing required to enable ASP.NET authentification in a Silverlight App.
With ASP.NET auth enabled, you will be able to edit your config file to use a AD identity provider, as in any other ASP.NET web app.
More informations about the ActiveDirectoryMembershipProvider on MSDN
[OperationContract]
public string GetCurrentUserWindowsLogin()
{
return Environment.UserName;
}
[OperationContract()]
public User DoLogIn(string login, string password)
{
string userName = String.Format(#"ELEGION\{0}", login);
string SERVER = "LDAP://Caesar.elegion.local";
User user = null;
try
{
DirectoryEntry entry = new DirectoryEntry(SERVER, userName, password, AuthenticationTypes.ReadonlyServer);
object nativeObject = entry.NativeObject;
if (nativeObject != null)
{
HeRMeSSunRiseDBEntities ent = EntitySingleton.Entities;
user = ent.Users.Where(l => l.Login == login && l.IsDisabled == false).FirstOrDefault();
if (user != null)
{
user.ADObject = entry.Guid.ToString();
ent.SaveChanges();
return user;
}
}
}
catch (DirectoryServicesCOMException cex)
{
Debug.Write(cex.Message);
}
catch (Exception ex)
{
Debug.Write(ex.Message);
}
return user;}

Resources