jitbit / aspnetsaml Goto Github PK
View Code? Open in Web Editor NEWVery simple SAML 2.0 consumer module for ASP.NET/C#
Home Page: https://www.jitbit.com
License: Apache License 2.0
Very simple SAML 2.0 consumer module for ASP.NET/C#
Home Page: https://www.jitbit.com
License: Apache License 2.0
I posted a question here: https://stackoverflow.com/questions/63490901/redirect-not-working-in-local-machine-for-ad-fs-saml-response
It does not seem to work with localhost. Is there anything that needs to be modified for it to work?
Thanks
Hi,
I managed to get SSO working with my company G suite domain.
Our app gets the email just fine as stated.
The problem is when the browser has other domain gmail user session.
When the browser has already signed "regular" gmail account (aka @gmail.com) when redirecting to the generated redirect url we get :
which is "half bad" , but when the browser has other active g suite session we get :
Only way fixing it is to goto to other gmail/google page on client browser and sign out the account, but of course we can't expect a user to do that or to know that he needs to do that.
When no account is signed in we get a good selection dialog from google :
1.Is this a common problem or i am missing something ?
2.Any way to generate a redirect url that the user will always see the account selection dialog if relevant.
3.Any other way to handle this issue ?
Thanks in advance.
All IdPs I've come across so far require a hardconfigured ACS URL to be set in the IdP setup.
The ACS passed in the Authentication request by seems to be completely ignored. Is this expected behavior, or is something wrong?
Iam using aspnetsaml to SSO authentication page load i called "GetRedirectUrl" to called IDp and getting Samlrequest URL. where i need to call "Samlconsumer" after getredirect iam getting null from response. how to achieve asp.net web form
static void Redir(Response samlResponse)
{
//specify the SAML provider url here, aka "Endpoint"
var samlEndpoint = "https://saml.xxxx.com/idp/SSO.saml2";
AuthRequest request = new AuthRequest(
"https://www.xxxx.com/", //put your app's "unique ID" here
"https://localhost:xxxxx/Home/SamlConsume" //assertion Consumer Url - the redirect URL where the provider will send authenticated users
);
string url = request.GetRedirectUrl(samlEndpoint);
Saml.Response samlResponse = new Response(samlCertificate, Request.Form["SAMLResponse"]);--it is valid to call
Response.Redirect(url);
}
not sure why. but when i enable fips on windows server 2016
ADFS Response will have this error
2020-09-25 17:02:57.6508 DEBUG "System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms.
at System.Security.Cryptography.SHA256Managed..ctor()
Application is build on .net framework 4.7.2
I could get the SAML response,
when hit the code samlResponse.IsValid(), then i got the error message as below :
SignatureDescription could not be created for the signature algorithm suppliedSystem.Security.Cryptography.CryptographicException: SignatureDescription could not be created for the signature algorithm supplied.
at System.Security.Cryptography.Xml.SignedXml.CheckSignedInfo(AsymmetricAlgorithm key)
at System.Security.Cryptography.Xml.SignedXml.CheckSignature(AsymmetricAlgorithm key)
at System.Security.Cryptography.Xml.SignedXml.CheckSignature(X509Certificate2 certificate, Boolean verifySignatureOnly)
at Testing.Security.SAML.SSOSignIn.Response.IsValid()
could you please help.
Thank you.
Hi, a doubt: this class only works for SHA-256 hash algorithm? Does not work for RSA-SHA1?
In IsExpired(), it might be preferable to replace
DateTime expirationDate = DateTime.MaxValue;
with
DateTime expirationDate = DateTime.MinValue;
to assume expiration if a valid NotOnOrAfter is not located.
Hello,
I am getting a NullReferenceException on this line of code.
I am using a valid certificate and valid SAMLResponse payload. I narrowed it down to the CheckSignature function. It fails whether I use CheckSignature(_certificate, true) or just CheckSignature() by itself.
I confirmed validity here: https://www.samltool.com/validate_response.php so I'm at a loss as to what might be happening at this point.
Tried on both .net core 3.1 and .net 5. Failed on both, if that matters.
Is there a known issue or bug? Any ideas?
Thanks
How can I check if a user already has logged in to SSO? Is there any function which checks that?
Using Convert.FromBase64()
instead of the method in StringFromByteArray
How to make POST Binding. Nice sample.
Thanx.
The saml.cs file appears to have a MIT license at the top which I greatly prefer.
But the License file in the project is Apache License Version 2.0, January 2004
Just checking which it actually is.
Thanks.
We're building an MVC 5 app and utilizing the SSO with this AspNetSaml. Everything appears to work but I was just wondering if I can find out the Redirect URL when the assertionConsumerServiceUrl is called. This is to redirect the user back (after the successful authentication) to the same page that user initially navigated to instead of the app landing page.
Please advise.
Hi!
Thanks for this project. It really simplified my life.
I've tested it and it works great.
But I have a suggestion, and I think you kinda started implementing it, which is, when the attribute name in the assertion is not what you expect or different identity providers have different names.
The way I'm solving it, I have a small class to hold "attribute name" and "attribute value number" (in case is a multi-value attribute) and then just changed this line:
AttributeConfig a = sm.GetUserGroupAttribute();
XmlNode node = _xmlDoc.SelectSingleNode("/samlp:Response/saml:Assertion/saml:AttributeStatement/saml:Attribute[@Name='"+a.Name+"']/saml:AttributeValue["+a.Value+"]", _xmlNameSpaceManager);
I have a helper class (sm above) that reads from configuration and retrieves the configured name. This allows to configure for Azure (for example) which uses a different name. And testing with another identity provider, I noticed a different name as well.
You could put those helper methods "GetUserGroupAttribute", "GetUserFirstName", etc. as part of the class or as a helper class returning some fixed values and then it will be up to the implementer to modify it in order to retrieve it from configuration.
Thanks
The configuration that is required for SAML to work is often presented in a SAML metadata XML file. How would that be used with this module?
Hi,
Im using same lib but when i deploy my application in IIS and hits defalut.aspx page its redirect my page to ADFS page but ADFS page gives error.
Error as below:
An error occurred
An error occurred. Contact your administrator for more information.
• Activity ID: 00000000-0000-0000-e934-0080060000f8
• Error time: Mon, 04 Mar 2019 05:30:06 GMT
• Cookie: enabled
• User agent string: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)
So can you help me for How to configure ADFS SAML in AD server with steps?
Thanks,
Chetan
Your nuget package is not updated to latest. As it is missing get custom attr function.
Hi,
I tested the Saml2 and it returns this:
NullPointerException: Method parameter 2 should not be null; null parameters are not supported in orignal XML-RPC specs
after redirecting to the endpoint. Any thoughts?
Many thanks.
In the sample code provided, it includes this line:
Saml.Response samlResponse = new Response(samlCertificate, Request.Form["SAMLResponse"]);
However, the code for the function "Response" only contains one parameter, not two. Is the sample code in error or is the code within the "Saml.cs" file incorrect?
Thanks
The OneLogin projet (this project was forked from) contained the following warning.
This project was a proof of concept, not recommended to use it in production environments since it not cover all security checks that SAML demand.
This fork also doesn't cover "all security checks" and should retain the original warning that it must not be used in production.
Some of the validation that are not performed :
Hi, may i have your help about how to build a saml logout request to sign out the account, after sign out success, redirect to specific page of the application?
Getting this error while trying to import the certificate:
Error: X509Certificate is immutable on this platform. Use the equivalent constructor instead.'
cert = new X509Certificate2();
cert.Import(certificate);
I created an ASP.NET MVC project and then added your NuGet package, but I also needed to add a reference to System.Security to be able to compile. Could be worth mentioning in the readme to make it more complete.
I am attempting to implement AspNetSaml in mvc but ran into an error. The Response.Redirect line in step 1 of your example gives an error that says it doesn't exist in the current context. I have placed the code into the StartUp.cs page of the application replacing the app.UseAuthentication() method.
How do I do a redirect to my provider in mvc and am I placing the code in the correct place?
Thanks
I am trying to use the AspNetSaml nuget package and I am getting an error when trying to use the Response.Redirect(url) method.
This is the error:
Error CS0117 'Response' does not contain a definition for 'Redirect'
I am already using the namespace System.Web and also I added the System.Web.dll
CODE:
static void Redir(Response samlResponse)
{
//specify the SAML provider url here, aka "Endpoint"
var samlEndpoint = "https://saml.xxxx.com/idp/SSO.saml2";
AuthRequest request = new AuthRequest(
"https://www.xxxx.com/", //put your app's "unique ID" here
"https://www.xxxx.com/" //assertion Consumer Url - the redirect URL where the provider will send authenticated users
);
// Generate the provider URL
string url = request.GetRedirectUrl(samlEndpoint);
Response.Redirect(url);
}))
As you can guess by the title, wondering if there are plans or thoughts on an approach for signing requests to the idp?
sorry for duping #4 but that one was closed
I am getting authenticated but I want to get a SAML token to use in my windows application after authentication. How to retrieve the token?
Hi,
Where i can find my samlCertificate ?
I am getting error when it redirects to the application after login
System.Security.Cryptography.CryptographicException: Cannot find the requested object.
Please let me know.
thanks,
sri
Hi, is there anyway to digitally sign samlRequest sent to idp? or am i missing something here ?
I'm getting The SAML message signature could not be validated as response from idp.
Could you explain how to consume for web forms?
As the title say. I want to ask that does this library support SSO to Google suite? Because I am looking for simple SAML2 library to use in my web application. I want only SSO login and get attributes of user only.
Hi Alex,
I saw your code , and same implementation is done is at my company side ,I need your help ,there is a requirement ,we have one typescript/html page where we are showing two radio buttons ,on click of that I have to hit particular IDP Url's (we have two IDP Url's) , could you modified your code and let me know how to achieve this ,On success callback (typescript) after authentication ,setting up session ,I have to redirect to Dashboard page .I could not find any useful article with my scenario
Hi,
I would like to know how the following issue can be solved in the code.
Weak Encryption: Inadequate RSA Padding. Which was identified by Fortify during a security check. On the bold lines
Would it be to altogether use a different SignatureDescription.Or would Fortify have raised a false positive issue.
public override AsymmetricSignatureDeformatter CreateDeformatter(AsymmetricAlgorithm key)
{
if (key == null)
throw new ArgumentNullException("key");
**RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(key);
deformatter.SetHashAlgorithm("SHA256");**
return deformatter;
}
Hi,
I am trying to use saml for .net 3.5. I installed the package through the nuget package manager. After install package I get error of "CrytoConfig does not contain a definition to AddAlgorith "on below code
public static void Init()
{
if(!_initialized)
CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
_initialized = true;
}
But if I copy the Saml.cs content from the github then the saml file content is totaly different. I am confused should I used the saml class that I get after package installation or the saml class showing in the github page.
During testing, we altered some of the characters in the certificate string. If it's just a minor change, it sometimes throws an invalid certificate exception, but other times it will still pass the IsValid()
check that is performed. I was able to get IsValid()
to return true by replacing the last character in the certificate issued by the SAML provider before the
-----END CERTIFICATE-----
line with an f
instead of an X
.
I tested changing signedXml.CheckSignature(_certificate, true)
to signedXml.CheckSignature(_certificate, false)
and doing so made IsValid()
return false when presented with an altered certificate string.
Is there a reason why this code isn't verifying that the certificate is valid, only that the signature is?
When the SAMLResponse contains an EncryptedAssertion, the attributes are not read.
Your class is partial which I like, we can extend it but could you also make your getEmail, etc functions virtual too so we could extend them in case of custom something.
Hi, I tried using your code, but I don't know MVC. So, i put it on a consume.aspx page, in the Page_Load.
Anyhow, i'm getting Object reference not set to an instance of an object when it gets to this part of the code:
Saml.Response samlResponse = new Response(samlCertificate, Request.Form["SAMLResponse"]);
I'm not sure if what i'm doing wrong is the MVC part of it, the samlCertificate, or something else,or all of the above.
Here is the code. Thanks for any help.
protected void Page_Load(object sender, EventArgs e) {
try {
string samlCertificate = @"MIIDvTCCAqWgAwIBAgIQS1+YLCdzuulaz9PgVXaUZYjANBgkqhkiG9w0BAQsFADBoMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEQMA4GA1UECgwHWnNjYWxlcjEyMDAGA1UEAwwpRVQg enBhYmV0YS5uZXQgSW50ZXJtZWtRpYXRlIENlcnRpZmljYXRlIDIwHhcNMTkwMTE4MDY0MTAxWhcN MjEwMTE3MDY0MTAxWjBSMQswCQeYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEQMA4GA1UE CgwHWnNjYWxlcjEcMBoGA1UEAwxwTc2FtbHNwMS56cGFiZXRhLm5ldDCCASIwDQYJKoZIhvcNAQEB BQADggEPADCCAQoCggEBALRBEMWTtgQw//PxoubAum3fTakGQNk2C8/WsG+zr3ouETVg3AJFcU49l W6PvzMyq9ySNZouGtI2OraLLdisyo3qkUFluMXCT5nSZ6mxFQ+pYzASCFwc6BwLKSBZioUL8/FkLp LbQgSGNqwH0c8Zgm+Ys0Yc3CqAtkgO/kVsJfyD7Aj5lGas7EmXB1lVbGfELzKEXSNXQgR4lFVF7PF 1MgFontEECKHKYITny+gohtnzulTsy+UE8SvBes6uR69EZAwGQ88KwZ3GLsS+mhFqxdrflHzom1rj QaHf44FnqBFRX6tcd3QbOggR77sTAFC6fHY1vgYtT4eDiKIa8LMYCNv9vrFMCAwEAAaN5MHcwCQYD VR0TBAIwADALBgNVHQ8EBAMCBadAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMB0GA1Ud DgQWBBSUgr1Me29VPEtICrxnOitbjhIspMzAfBgNVHSMEGDAWgBThF4kFL8wt78YK/4VWAM5/Zyr2 aTANBgkqhkiG9w0BAQsFAAOCAQEAjqkavdpcvsyv+4exf0mzqvCOTpDSKSKqgD4uZBrPFwsOfU8ma k3JyVqEde7vZPcvL9md0rpUqFFiqfeApqRKN2FEEsdrK2CUrr1NRVk/vB1vm/wMJ60KcF/coAUo7M +WamSdyEsY9ApHu3/oP4fKX6/kbUgn2s5dt+DhGH2YvoDUquToDXYJ4uEM+PKMs1/Ns7alCGbBR16 N51dH+bW6Jq+uBcNhlv4HHSD2xQtWoimf6xQLAtod7VVFyIh/8N0eakQ9CutV0Bsq6F6/jwb+gEiH ljnzutyWDyh0a+5OQj6ULQkKYyK4r8UozOKBC5b5Rq3yVt2Q5FZgYe2j1hJGXsxAKQ==";
Saml.Response samlResponse = new Response(samlCertificate, Request.Form["SAMLResponse"]);
if (samlResponse.IsValid())
{
Label1.Text = "WOOHOO!!! user is logged in";
string username, email, firstname, lastname;
try
{
username = samlResponse.GetNameID();
Label2.Text = "user eid is:" + username;
}
catch (Exception ex)
{
}
finally
{
}
}
else
{
}
}
catch (Exception ex)
{
}
finally
{
}
}`
I have been provided tokensigning.cer file by SAML provider. How can I use it to specify the certificate in string variable as mentioned in set 2 code as below:
//specify the certificate that your SAML provider has given to you string samlCertificate = @"-----BEGIN CERTIFICATE----- BLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAH123543== -----END CERTIFICATE-----";
Came across this article and was wondering whether the code for this library is impacted? https://snede.net/the-most-dangerous-constructor-in-net/
I am using .net framework 3.5
public static void Init()
{
if (!_initialized)
CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
_initialized = true;
}
CryptoConfig.AddAlgorithm is not found, may be because I am using lower version of .net frame work.
Can you suggest what can be work around for this.
In the sample code when creating a authentication request, the issuer is set to the application URL.
var request = new AuthRequest(
"http://www.myapp.com", //TODO: put your app's "unique ID" here
"http://www.myapp.com/SamlConsume" //TODO: put Assertion Consumer URL (where the provider should redirect users after authenticating)
);
I've noticed that when I leave this empty, everything seems to "just work". What is the purpose of this field?
Hi,
Do you have a way to manage the single logout?
https://developers.onelogin.com/saml/examples/logout-request
I tried to create the request (following your example) but then it has to be signed and I don't know how to do that (I was trying to do the HTTP-Redirect)
To verify the signature of the SAML response, the code calls the method IsValid()
, which in turn calls signedXml.CheckSignature(_certificate, true)
, with _certificate
being a X509Certificate2
object.
Instead of such a X509Certificate2
object, I'm getting handed a SecurityKeyIdentifierClause
object from the System.IdentityModel.Tokens
namespace. Is it possible to use this clause to verify the signature of the SAML response?
When trying the first snippet of code in the README, I get two compile errors. One about the semicolon on the last line, and one about not all code paths returning a value. In fact, none of the paths return a value.
//this example is an ASP.NET MVC action method
public ActionResult Login()
{
//TODO: specify the SAML provider url here, aka "Endpoint"
var samlEndpoint = "http://saml-provider-that-we-use.com/login/";
var request = new AuthRequest(
"http://www.myapp.com", //TODO: put your app's "unique ID" here
"http://www.myapp.com/SamlConsume" //TODO: put Assertion Consumer URL (where the provider should redirect users after authenticating)
);
//redirect the user to the SAML provider
Response.Redirect(request.GetRedirectUrl(samlEndpoint););
}
Hi
I try to use this with Google SSO but get this error "Error: app_not_configured_for_user" when using it.... Maybe I have done things wrong.. This is what I use...
Dim samlEndpoint = "https://accounts.google.com/o/saml2/idp?idpid=xxxxx"
Dim request = New AuthRequest("https://rootfoldertomywebsite/", "https://rootfoldertomywebsite/SamlConsume")
In this adress https://rootfoldertomywebsite/SamlConsume I have the code below...
Public Sub SamlConsume()
' 1. TODO: specify the certificate that your SAML provider gave you
'Dim samlCertificate = "-----BEGIN CERTIFICATE-----
' BLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAH123543==
' -----END CERTIFICATE-----"
' 2. Let's read the data - SAML providers usually POST it into the "SAMLResponse" var
Dim samlResponse = New Response(samlCertificate, Request.Form("SAMLResponse"))
' 3. We're done!
If samlResponse.IsValid() Then
'WOOHOO!!! user is logged in
'Some more optional stuff for you
'let's extract username/firstname etc
Dim username, email, firstname, lastname As String
Try
username = samlResponse.GetNameID()
email = samlResponse.GetEmail()
firstname = samlResponse.GetFirstName()
lastname = samlResponse.GetLastName()
Catch ex As Exception
'insert error handling code
'no, really, please do
'return null;
End Try
'user has been authenticated, put your code here, like set a cookie or something...
'or call FormsAuthentication.SetAuthCookie() or something
FormsAuthentication.RedirectFromLoginPage(username, False)
'FormsAuthentication.SetAuthCookie(username,True)
End If
End Sub
Sorry if this is a newbie question but is this the correct setup?
Hello,
I have an issue with an authentication request which is correctly decoded but after decryption gets something a PasswordProtectedTransport indication. The content remains impossible to read. Any idea on how to address this?
Thanks.
Stéphane
Hello,
this is my first time working with SSO SAMIL 2.0.
I have a web application in ASP.NET "old" framework, I would like to understand how I can integrate SSO using saml.cs page.
I have a windows server 2019 and I do install and configure Service Provider Shibboleth
Can you give me some info to understand what I have to do?
Thank you
Hello
Hi all
Thanks for your lib. It is super easy to use. It works really well with AzureAD app.
However, I have an issue for implementation it to work with ADFS server. I have error message:
"ADFS - Invalid URI: The format of the URI could not be determined"
Please help me with some hints. Thank you so much. I am really appreciated.
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.