How do we get the current Authentication Mode in SharePoint using C# - c#

I have a sharepoint site which has different authentication options available for users to login like Windows, Trusted SAML etc
How can i determine which is the authentication mode of the current request?
I have tried the "SPSecurity.AuthenticationMode" but its value is always forms.

You would need to get it via SPOriginalIssuerType Property
var localClaimManager = SPClaimProviderManager.Local;
if (localClaimManager != null)
{
var issuerType=SPOriginalIssuers.GetIssuerType(localClaimManager.DecodeClaim(SPContext.Current.Web.CurrentUser.LoginName).OriginalIssuer);
//Write your logic based on the issuerType received
//https://learn.microsoft.com/en-us/dotnet/api/microsoft.sharepoint.administration.claims.sporiginalissuertype?view=sharepoint-server
}

Related

Create Magic Links for users to access a .Net MVC WebApp

I want to add a new feature to my WebApp for events - build with .Net MVC - to send a magic link to each participant - after they register in the event - to access the WebApp and be able to participate in a Gamification challenge.
I am using Microsoft Owin for the backoffice access, and I would like to use it to create the magic link, but I cant find any solution for that.
I have searched a token login solution but no success.
Is it ASP.NET or ASP.NET Core application? It shouldn't matter if you're using OWIN or not. In a ASP.NET project I have used MachineKey's Protect and Unprotect methods. Set a static machine key using machineKey element in the web.config, because it keeps being regenerated by default. If it's a load-balancing environment, set identical machine key on each node.
For example, let's say you have some key identifying the participant, most likely the email address. Include ?user=key&token=token in the link. To generate the token
var unprotected = Encoding.UTF8.GetBytes(key);
var protected = MachineKey.Protect(unprotected);
var token = HttpServerUtility.UrlTokenEncode(protected);
To validate the token, when the user accesses the application:
bool Validate(string token, string expectedKey)
{
var protected = HttpServerUtility.UrlTokenDecode(token);
try
{
var unprotected = MachineKey.Unprotect(protected);
var key = Encoding.UTF8.GetString(unprotected);
return key == expectedKey;
}
catch (CryptographicException)
{
return false;
}
}
The MachineKey's successor in ASP.NET Core is Data Protection.

Use ITfoxtec.Identity.Saml2 to login user

I am trying to implement SAML2.0 authentication using IdentityServer4 and ITfoxtec.Identity.Saml2 library.
The first step is to login via the LDAP connection and this part worked well and i get user claims.
Next step is to integrate login using AD FS
I followed principally this tutorial
https://developer.okta.com/blog/2020/10/23/how-to-authenticate-with-saml-in-aspnet-core-and-csharp
The Saml configuration code is below
services.Configure<Saml2Configuration>(saml2Configuration =>
{
saml2Configuration.AllowedAudienceUris.Add(saml2Configuration.Issuer);
var entityDescriptor = new EntityDescriptor();
entityDescriptor.ReadIdPSsoDescriptorFromUrl(new Uri(Configuration["Saml2:IdPMetadata"]));
if (entityDescriptor.IdPSsoDescriptor != null)
{
saml2Configuration.SingleSignOnDestination = entityDescriptor.IdPSsoDescriptor.SingleSignOnServices.First().Location;
saml2Configuration.SignatureValidationCertificates.AddRange(entityDescriptor.IdPSsoDescriptor.SigningCertificates);
}
else
{
throw new Exception("IdPSsoDescriptor not loaded from metadata.");
}
});
services.AddSaml2();
After server redirection and before displaying the Idp login page i have an error "certificate are not properly configured at application end"
This is the first time that I deal with SAML protocol. Any help is appreciated.
Edit : The error is on the AD FS Side
For more information, the ITfoxtec.Identity.Saml2 documentation and a ASP.NET Core sample.
I'm in doubt where you see the error. Is it at the IdentityServer4 application or in AD FS?
The configuration you show read the AD FS metadata and set up the IdP configuration. You also need to load the relying party configuration.
services.Configure<Saml2Configuration>(Configuration.GetSection("Saml2"));
and set the relying party signing certificate e.g., like this
saml2Configuration.SigningCertificate = CertificateUtil.Load(AppEnvironment.MapToPhysicalFilePath(
Configuration["Saml2:SigningCertificateFile"]),
The configuration together
services.Configure<Saml2Configuration>(Configuration.GetSection("Saml2"));
services.Configure<Saml2Configuration>(saml2Configuration =>
{
saml2Configuration.SigningCertificate = CertificateUtil.Load(AppEnvironment.MapToPhysicalFilePath(
Configuration["Saml2:SigningCertificateFile"]), Configuration["Saml2:SigningCertificatePassword"]);
saml2Configuration.AllowedAudienceUris.Add(saml2Configuration.Issuer);
var entityDescriptor = new EntityDescriptor();
entityDescriptor.ReadIdPSsoDescriptorFromUrl(new Uri(Configuration["Saml2:IdPMetadata"]));
if (entityDescriptor.IdPSsoDescriptor != null)
{
saml2Configuration.SingleSignOnDestination = entityDescriptor.IdPSsoDescriptor.SingleSignOnServices.First().Location;
saml2Configuration.SingleLogoutDestination = entityDescriptor.IdPSsoDescriptor.SingleLogoutServices.First().Location;
saml2Configuration.SignatureValidationCertificates.AddRange(entityDescriptor.IdPSsoDescriptor.SigningCertificates);
}
else
{
throw new Exception("IdPSsoDescriptor not loaded from metadata.");
}
});
services.AddSaml2();
Remark
To solve a situation like yours I have created FoxIDs which support OpenID Connect and can be connected to an AD FS with SAML 2.0. FoxIDs handles the conversion between OpenID Connect and SAML 2.0. Actually, FoxIDs also use the ITfoxtec.Identity.Saml2 library.

Azure AD B2C user info Xamarin

Hello I am trying to get user info like name and address in an Xamarin app using Azure AD B2C for authentication.
So far I've gotten the authentication working fine
public async Task<MobileServiceUser> LoginAsync(MobileServiceClient client, MobileServiceAuthenticationProvider provider)
{
try
{
//login and save user status
var user = await client.LoginAsync(Forms.Context, provider);
Settings.AuthToken = user?.MobileServiceAuthenticationToken ?? string.Empty;
Settings.UserId = user?.UserId ?? string.Empty;
return user;
}
catch (Exception e)
{
}
return null;
}
However I would like to know how to get the user's name and birthday. I haven't been able to find a clear course of action for that.
You do not explicitly get this information using the MobileService SDK. Check out the complete documentation about App Service Authentication/Authorization here.
You will reach the point where it mentions:
Your application can also obtain additional user details through an
HTTP GET on the /.auth/me endpoint of your application. A valid token
that's included with the request will return a JSON payload with
details about the provider that's being used, the underlying provider
token, and some other user information. The Mobile Apps server SDKs
provide helper methods to work with this data.
So, in your Xamarin, after the user is successfully authentication, you have to explicitly make a HTTP GET request to /.auth/me and parse the result to get all information about the logged-in user.
Not sure how to do this in Xamarin, but here is how to do it in C# UWP (Universal Windows Platform):
var url = App.MobileService.MobileAppUri + "/.auth/me";
var clent = new Windows.Web.Http.HttpClient();
clent.DefaultRequestHeaders.Add("X-ZUMO-AUTH", this.user.MobileServiceAuthenticationToken);
var userData = await clent.GetAsync(new Uri(url));
at the of this code execution, the userData varibale will be a JSON srting with all user's claims.

Facebook SDK integration in WPF application

I have wpf desktop application and I want Facebook login integration in this application so that users can share images from local machine, moreover I am using "Facebook.7.0.6" sdk. Apparently I am facing following issue on login screen.
Given URL is not allowed by the Application configuration: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.
And below coding I am using in my application.
private Uri GenerateLoginUrl(string appId, string extendedPermissions)
{
// for .net 3.5
// var parameters = new Dictionary<string,object>
// parameters["client_id"] = appId;
dynamic parameters = new ExpandoObject();
parameters.client_id = appId;
parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";
// The requested response: an access token (token), an authorization code (code), or both (code token).
parameters.response_type = "token";
// list of additional display modes can be found at http://developers.facebook.com/docs/reference/dialogs/#display
parameters.display = "popup";
// add the 'scope' parameter only if we have extendedPermissions.
if (!string.IsNullOrWhiteSpace(extendedPermissions))
parameters.scope = extendedPermissions;
// generate the login url
var fb = new FacebookClient();
return fb.GetLoginUrl(parameters);
}
void facebookBrowser_Navigated(Object sender,NavigationEventArgs e)
{
var fb = new FacebookClient();
FacebookOAuthResult oauthResult;
if (!fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
return;
if (oauthResult.IsSuccess)
LoginSucceeded(oauthResult);
}
Note : Let me know if Facebook have any change in term and condition for desktop application.
Thanks
After some study I got this link and now my application working fine.
Please set below settings on Facebook app first.
Native or desktop app? - Yes
Client OAuth login - Yes
Embedded browser OAuth Login - Yes
read more from this link :-https://www.hackviking.com/2014/11/facebook-api-login-flow-for-desktop-application/
Thanks
This error means you haven't configured well you app on facebook
If you are testing on localhost, you need to add a platform to your app, then configuring the "site url" for the example http://localhost. Then create a test app (a copy of your main app) and use it for your tests.

Windows identity foundation - sign out or update claims

I am using Windows Identity foundation to manage login to our site.
When a user logs in i am using some information in his request to put into the claims.
It is all working fine, but now I need to manage this scenario:
user is already logged in, athenticated and has a valid token.
But user decides to browses in again (via a redirect from another site)
So his information in his request is different.
I want to either
Sign him out - so that he naturally creates a new token with his new information
OR update his existing token.
So my question is:
How do i Sign out of Windows Identity foundation?
Or How do I update the existing claims?
I have tried this code:
public void ExpireClaims(HttpContextBase httpContextBase)
{
var module =
httpContextBase.ApplicationInstance.Modules["WSFederationAuthenticationModule"] as
WSFederationAuthenticationModule;
if (module == null)
{
return;
}
module.SignOut(true);
}
But module is alway null.
and i tried this:
public void FederatedSignOut(string replyUrl)
{
WSFederationAuthenticationModule.FederatedSignOut(null, new Uri(replyUrl));
}
But i get a null reference execption when i do this.
Thanks very much.
Essentially sign-out is just deleting the cookie so:
FormsAuthentication.SignOut
or
FederatedAuthentication.SessionAuthenticationModule.SignOut
or
FederatedAuthentication.SessionAuthenticationModule.DeleteSessionTokenCookie
will work.
Or use the FederatedPassiveSignInStatus (should be in your Toolbox). Set the property SignOutAction to FederatedSignOut and the control will clear out your STS session as well.

Categories

Resources