akunzai / gss.authentication.cas Goto Github PK
View Code? Open in Web Editor NEWCAS Authentication Middleware for OWIN & ASP.NET Core
License: MIT License
CAS Authentication Middleware for OWIN & ASP.NET Core
License: MIT License
How can implement your library with the next scenario.
Angular 6 app.
Net Core 2.1 web api sln.
I can assume that the angular app will do the auth against CAS.
Does the Angular should add something to the header in the requests?
I got this working with my web api, using a browser as a client, but for example If I use postman I don't get results, maybe because I'm being redirected to CAS login page. And the same will happen with the Angular app as the client.
Thanks
Hello,
I have an IdentityServer 4 application that must support multiple CAS configurations.
In order to do that, I iterate through my cas configuration and add a builder for each one of them:
public static AuthenticationBuilder AddCasAuth(this AuthenticationBuilder builder, CasSetting casSetting)
{
// Scheme must be the company identifier
builder.AddCAS(casSetting.Scheme, casSetting.DisplayName, options =>
{
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
options.ServiceTicketValidator = new Cas20ServiceTicketValidator(options);
options.CasServerUrlBase = casSetting.BaseUrl;
// required for Cas SingleLogout
options.SaveTokens = true;
options.Events = new CasEvents
{
OnCreatingTicket = context =>
{
// ... Handle the recieved claims ...
return Task.CompletedTask;
},
OnRemoteFailure = context =>
{
// ... Handle the errors ...
return Task.CompletedTask;
}
};
});
return builder;
}
It works fine for the first element of my collection, but for the ones after, I have the following error after logging in the CAS server: State invalid or missing.
When I look at the context in the OnRemoteFailure, I find the configuration of the first element of my collection but the CAS login page matches the right element of the collection.
For example:
"CasSettings": [
{
"Scheme": "Scheme 1",
"DisplayName": "First CAS",
"BaseUrl": "https://domain1/cas"
},
{
"Scheme": "Scheme 2",
"DisplayName": "Second CAS",
"BaseUrl": "https://domain2/cas"
}
]
If I try to log in with Scheme 2, I land on the login page on https://domain2/cas, when I validate the form, I am redirected to my error page and the context of OnRemoteFailure has the Scheme 1 configuration. (hence the invalid state)
Is it supposed to be supported? Am I missing something here?
Thank you
先登录A站点,再登录B站点,退出A站点,B站点未退出
First login A site, then log on to B site, exit A site, B site did not quit.
Is your feature request related to a problem? Please describe.
GSS.Authentication.CAS.RuntimeCache can be replaced by GSS.Authentication.CAS.DistributedCache with Microsoft.Extensions.Caching.Memory.
Describe the solution you'd like
we should maintain and support GSS.Authentication.CAS.DistributedCache only. and deprecating GSS.Authentication.CAS.RuntimeCache.
Describe alternatives you've considered
keep GSS.Authentication.CAS.RuntimeCache on NuGet Gallery
Additional context
N/A
when site provide json request, client send content-type=application/json, the middleware will cause a error, it need futher judge
if (context.Request.Method.Equals(HttpMethod.Post.Method, StringComparison.OrdinalIgnoreCase) && context.Request.ContentType.Equals("application/x-www-form-urlencoded", StringComparison.InvariantCulture))
and futher more, when app is cluster the function may not working, I provider a function to return a ip and point list to return the all nodes, exclude the localnode, I also send the message to other node,
`namespace Cas.Authentication.AspNetCore
{
public class SingleSignOutOptions
{
public SingleSignOutOptions()
{
LoginPath = new PathString("/cas-login");
LogoutPath = new PathString("/cas-logout");
}
public string CasBaseUrl { get; set; }
public PathString LoginPath { get; set; }
public PathString LogoutPath { get; set; }
public IClusterNodeDiscover NodeDiscover { get; set; }
}
}
public interface IClusterNodeDiscover
{
IList GetAllNodes();
}`
it may read nodes from consul or zk
in this middleware I also provider the signin and signout endpoint
else if(context.Request.Path.StartsWithSegments(_signOutOptions.LoginPath)) { await context.ChallengeAsync(CasDefaults.AuthenticationType, new AuthenticationProperties { RedirectUri = context.Request.Query["ReturnUrl"] }); return; } else if(context.Request.Path.StartsWithSegments(_signOutOptions.LogoutPath)) { await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); context.Response.Redirect($"{_signOutOptions.CasBaseUrl}/logout?service={Uri.EscapeDataString(context.Request.Scheme + "://" + context.Request.Host)}"); return; }
for session store, I provider a simple wapper to support IDistributedCache and IMemoryCache, any implement can use, did not need to reference an dll
.AddCas(new MemoryCache(Options.Create(new MemoryCacheOptions())), null,...;
I am using CAS as the authentication schema without identity and once a user is authorized and the cookie is created. The user tries to access unauthorized area instead of redirecting the user to unauthorized page it's redirecting to log-In page with the ticket in the URL.
Ie
https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-3.0
Hello
I read that I have to ensure that https should be configure so the log in from CAS to be enable.
Now I have another issue...
I get
An unhandled exception occurred while processing the request.
XmlException: '=' is an unexpected token. The expected token is ';'. Line 32, position 91.
See Microsoft OWIN 4.1.1 Release Notes
Assertion Attribute value is StringValues, get stored json from cache is ok, but when deserialize is missing,can you replace string insted?
What in ticket validation determines whether the assertion PrincipalName is encrypted or not. Different behavior on different machines where on one the PrincipalName is clear while on other machines the PrincipalName is encrypted.
Hello,
since your last modifications (thank you for them, by the way) I cannot install the 2.1.0 version of GSS.Authentication.CAS.Owin, because it seeks a version of GSS.Authentication.CAS.Core superior to 2.0.1 (which doesn't exists).
Best regards.
Does the software support CAS protocol 3.0?
Hello,
I have an .net core 6 app and when I try to login through CAS I get the following message
Exception: Correlation failed.
Unknown location
Exception: An error was encountered while handling the remote login.
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler.HandleRequestAsync()
Any idea?
Thank you
Hello,
I would like to ask how can we skip the middle page which displays the
"Register
Associate your CAS account." message
I use .net core 7
thank you
I have a ASP.NET Web API project using OWIN authentication. We do not always set the ContentType when doing post. It looks like there is a check on line 34 that breaks when ContentType is null.
Using GSS.Authentication 5.3.3
Describe the bug
On occasion, the /signin-cas
endpoint gets hit and throws an exception.
[09:04:12 DBG] 0HN0JI1URRJHK:00000004 The request path /signin-cas does not match a supported file type
[09:04:12 INF] 0HN0JI1URRJHK:00000004 Error from RemoteAuthentication: Missing CAS ticket..
[09:04:13 ERR] 0HN0JI1URRJHK:00000004 An error was encountered while handling the remote login.
System.Exception: An error was encountered while handling the remote login.
---> System.Exception: Missing CAS ticket.
--- End of inner exception stack trace ---
at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
I'm not sure what would cause this, as I believe the cas server is redirecting back to this app when this happens. Ultimately I'd like to find a way to intercept and redirect back to login or somethign when I encounter this error.
The vast majority of time, this library works perfectly and I never run into problems... so again... not exactly sure what I'm doing wrong, or if it could indicate a problem with the cas server or something else.
Any pointers here would be greatly appreciated.
This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.
These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.
Microsoft.AspNetCore.WebUtilities
, Microsoft.Extensions.Caching.Abstractions
, Microsoft.Extensions.Caching.Memory
, Microsoft.Extensions.Options
, Microsoft.Extensions.Primitives
, System.Text.Encodings.Web
, System.Text.Json
).github/workflows/cd.yml
actions/checkout v4
actions/setup-dotnet v3
.github/workflows/ci.yml
actions/checkout v4
actions/setup-dotnet v3
microsoft/setup-msbuild v1
codecov/codecov-action v3
samples/AspNetCoreReactSample/ClientApp/package.json
@types/node ^20.10.0
@types/react ^18.2.38
@types/react-dom ^18.2.17
axios ^1.6.2
bootstrap ^5.3.2
react ^18.2.0
react-dom ^18.2.0
react-router-bootstrap ^0.26.2
rimraf ^5.0.5
typescript ~5.3.2
web-vitals ^3.5.0
wouter ^2.12.1
@vitejs/plugin-react ^4.2.0
eslint ^8.54.0
eslint-config-react-app ^7.0.1
vite ^5.0.2
semver ^7.5.4
yarn 4.0.2
.config/dotnet-tools.json
dotnet-reportgenerator-globaltool 5.2.0
Directory.Packages.props
xunit 2.6.2
xunit.runner.visualstudio 2.5.4
System.Text.RegularExpressions 4.3.1
System.Net.Http 4.3.4
System.Drawing.Common 8.0.0
StackExchange.Redis 2.7.4
RichardSzalay.MockHttp 7.0.0
Owin.OAuthGeneric 1.0.3
NLog.Web 5.3.5
NLog.Web.AspNetCore 5.3.5
NLog.Owin.Logging 4.0.0
NLog.Extensions.Logging 5.3.5
Newtonsoft.Json 13.0.3
MSBuild.Microsoft.VisualStudio.Web.targets 14.0.0.3
Moq 4.20.70
Microsoft.TestPlatform.ObjectModel 17.8.0
Microsoft.Owin.Testing 4.2.2
Microsoft.Owin.Security.OpenIdConnect 4.2.2
Microsoft.Owin.Security.Cookies 4.2.2
Microsoft.Owin.Host.SystemWeb 4.2.2
Microsoft.NETFramework.ReferenceAssemblies 1.0.3
Microsoft.NET.Test.Sdk 17.8.0
Microsoft.IdentityModel.Protocols.OpenIdConnect 7.0.3
Microsoft.Extensions.DependencyInjection 8.0.0
Microsoft.Extensions.Configuration.Json 8.0.0
Microsoft.Extensions.Configuration.EnvironmentVariables 8.0.0
Microsoft.Extensions.Configuration.Binder 8.0.0
Microsoft.Extensions.Caching.StackExchangeRedis 8.0.0
Microsoft.EntityFrameworkCore.Tools 8.0.0
Microsoft.EntityFrameworkCore.Sqlite 8.0.0
Microsoft.CodeDom.Providers.DotNetCompilerPlatform 4.1.0
Microsoft.AspNetCore.TestHost 8.0.0
Microsoft.AspNetCore.SpaProxy 8.0.0
Microsoft.AspNetCore.Identity.UI 8.0.0
Microsoft.AspNetCore.Identity.EntityFrameworkCore 8.0.0
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore 8.0.0
Microsoft.AspNetCore.Authentication.OpenIdConnect 8.0.0
Microsoft.AspNet.Mvc 5.3.0
coverlet.collector 6.0.0
System.Text.Json 8.0.0
System.Text.Encodings.Web 8.0.0
Microsoft.Extensions.Primitives 8.0.0
Microsoft.Extensions.Options 8.0.0
Microsoft.Extensions.Caching.Memory 8.0.0
Microsoft.Extensions.Caching.Abstractions 8.0.0
System.Text.Json 4.7.2
System.Text.Encodings.Web 4.7.2
Microsoft.Extensions.Primitives 2.2.0
Microsoft.Extensions.Options 2.2.0
Microsoft.Extensions.Caching.Memory 2.2.0
Microsoft.Extensions.Caching.Abstractions 2.2.0
Microsoft.AspNetCore.WebUtilities 2.2.0
Hi,
I've following Login method:
[HttpGet("login")]
public IActionResult Login(string returnUrl)
{
if (User.Identity?.IsAuthenticated == true)
{
return Redirect(returnUrl);
}
return Challenge(new AuthenticationProperties { RedirectUri = returnUrl }, "CAS");
}
When I load the react.js page for a first time then after succesfull login to CAS User.Identity?.IsAuthenticated is always false. Next 3 requests to different controller entpoints are causing another calls to login endpoint and finnaly some 500 errors. Sometimes lastcontroller entpoint call is succesful. It seems like controllers calls are made before first login call is finished and HttpContext.User.Identity isnt's yet set.
When I reload the page the Login endpoint isn't called at all and everything works fine.
I'm using GSS.Authentication.CAS.AspNetCore 5.3.3.
I setup CAS service like that:
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Events.OnSigningOut = context =>
{
var redirectContext = new RedirectContext<CookieAuthenticationOptions>(
context.HttpContext,
context.Scheme,
context.Options,
context.Properties,
"/");
if (builder.Configuration.GetValue("Authentication:CAS:SingleSignOut", false))
{
// Single Sign-Out
var casUrl = new Uri(builder.Configuration["Authentication:CAS:ServerUrlBase"]);
var links = context.HttpContext.RequestServices.GetRequiredService<LinkGenerator>();
var serviceUrl = context.Properties.RedirectUri ?? links.GetUriByPage(context.HttpContext, "/");
redirectContext.RedirectUri = UriHelper.BuildAbsolute(
casUrl.Scheme,
new HostString(casUrl.Host, casUrl.Port),
casUrl.LocalPath, "/logout",
QueryString.Create("service", serviceUrl!));
}
context.Options.Events.RedirectToLogout(redirectContext);
return Task.CompletedTask;
};
options.Cookie.Name = ".ASPXAUTH_EPROTOCOLS";
})
.AddCAS(options =>
{
options.CasServerUrlBase = builder.Configuration["Authentication:CAS:ServerUrlBase"];
// required for CasSingleLogoutMiddleware
options.SaveTokens = builder.Configuration.GetValue("Authentication:CAS:SaveTokens", false);
var protocolVersion = builder.Configuration.GetValue("Authentication:CAS:ProtocolVersion", 3);
if (protocolVersion != 3)
{
options.ServiceTicketValidator = protocolVersion switch
{
1 => new Cas10ServiceTicketValidator(options),
2 => new Cas20ServiceTicketValidator(options),
_ => null
};
}
options.Events.OnCreatingTicket = context =>
{
if (context.Identity == null)
{
return Task.CompletedTask;
}
// Map claims from assertion
var assertion = context.Assertion;
context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, assertion.PrincipalName));
context.Identity.AddClaim(new Claim(ClaimTypes.Name, assertion.PrincipalName));
if (assertion.Attributes.TryGetValue("display_name", out var displayName))
{
context.Identity.AddClaim(new Claim(ClaimTypes.Name, displayName!));
}
if (assertion.Attributes.TryGetValue("email", out var email))
{
context.Identity.AddClaim(new Claim(ClaimTypes.Email, email!));
}
return Task.CompletedTask;
};
});
Anyone can help?
Hello,
Would you consider signing the assemblies in order to give them a strong name ?
Microsoft published an article about signing open-source assemblies: https://docs.microsoft.com/en-us/dotnet/standard/library-guidance/strong-naming
Thanks
We've build an app like the example "ASP.NET Core app with Single-Sign-Out". But it's running behind a reverse proxy in a subfolder.
The basePath is set like
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UsePathBase("/base");
app.UsePathBase("/base");
...
}
All other parts of the app are working like excepted but after login it should redirect to www.myserver.com/base
but does redirect to www.myserver.com/
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.