How can I change my LDAP configs to Spring Security realization? - spring-security

I have this LDAP configuration:
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://.....");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "login);
env.put(Context.SECURITY_CREDENTIALS, password);
// Create the initial context
DirContext ctx = new InitialDirContext(env);
boolean result = ctx != null;
How can I change this configuration for Spring Security realization?
auth.ldapAuthentication().....

You can use this sample code as a template. In my case, the LDAP provider URL is ldap://localhost:1389/dc=example,dc=com and the user entries have the following DN pattern: uid={0},ou=people,dc=example,dc=com. This means that the uid attribute will be used as the username.
LdapContextSource ctxSrc = new LdapContextSource();
ctxSrc.setUrl("ldap://localhost:1389");
ctxSrc.setBase("dc=example,dc=com");
ctxSrc.setUserDn("login");
ctxSrc.setPassword("password");
ctxSrc.afterPropertiesSet();
auth
.ldapAuthentication()
.contextSource(ctxSrc)
.userSearchBase("ou=people")
.userSearchFilter("(uid={0})");

Related

Google OAuth2 Java code asking permissions every time

I am using the following with a google-client-secret.json file and trying to run this as just a java application in eclipse. I want to store the permissions so once I accept the permissions it doesn't ask again. Right now it is prompting everytime. After that everything works as expected and writes to my google sheets.
public static Credential authorizeSHEETS() throws IOException, GeneralSecurityException {
File fileIn = new File("src/jg/sos/orders/google-sheets-client-secret.json");
// InputStream in = GoogleAuthorizeUtil.class.getResourceAsStream("src/jg/sos/orders/google-sheets-client-secret.json");
InputStream in = new FileInputStream(fileIn);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in));
List<String> scopes = Arrays.asList(SheetsScopes.SPREADSHEETS);
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), clientSecrets, scopes).setDataStoreFactory(new MemoryDataStoreFactory())
.setAccessType("offline").setApprovalPrompt("auto").build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
return credential;
}
Any ideas on how to only have this prompt me the first time for permissions, then the next time I run this it will not?
Thanks for the help!
JJ
So found an answer to this in case anyone comes across. I used a service account instead, and downloaded the json file for it and placed in my project.
Then I just referenced it instead, and saved the token using DataStoreFactory as below:
public static Credential authorizeSHEETS() throws IOException, GeneralSecurityException {
File fileIn = new File("src/jg/sos/orders/google-sheets-client-secret.json");
// InputStream in = GoogleAuthorizeUtil.class.getResourceAsStream("src/jg/sos/orders/google-sheets-client-secret.json");
InputStream in = new FileInputStream(fileIn);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in));
List<String> scopes = Arrays.asList(SheetsScopes.SPREADSHEETS);
FileDataStoreFactory dataStoreFactory = new FileDataStoreFactory(new File("src/jg/sos/orders"));
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), clientSecrets, scopes)
.setDataStoreFactory(dataStoreFactory)
.setAccessType("offline").setApprovalPrompt("auto").build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
System.out.println("token" + credential.getAccessToken());
return credential;
}

Project Server In premise 2016 CSOM code with Claim based Authentication

One of our clients has enabled ADFS on his Project server 2016 In premise environment . We are using CSOM operation in our custom application and CSOM operations have failed due to this change.
For ADFS Claims based authentication we need to pass Authenticated cookie . Can someone help us with how to add authenticated Cookie with CSOM code.
Existing CSOM Code for getting list of projects:
public static void GetProjectListInpremise()
{
NetworkCredential net = null;
Console.WriteLine("Read Project Online Started ..");
string PWAOnlineUrl = ConfigurationManager.AppSettings ["pwaInpremiseUrl"];
string userName = ConfigurationManager.AppSettings["pwaInpremiseUser"];
string password = ConfigurationManager.AppSettings["pwaInpremiseUserPwd"];
string domain = ConfigurationManager.AppSettings["pwaInpremiseDomian"];
net = new NetworkCredential(userName, password, domain);
ProjectContext projContext = null;
projContext = new ProjectContext(PWAOnlineUrl);
// projContext.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
projContext.Credentials = net;
projContext.Load(projContext.Projects);
projContext.ExecuteQuery();
Console.WriteLine("Read Project Execute Query Successful..");
foreach (PublishedProject pubProj in projContext.Projects)
{
Console.WriteLine("Project Name :" + pubProj.Name);
}
Console.ReadLine();
}

IDX10503: Signature validation failed after updating to Owin.Security v 4.0.0

As per subject, I updated the Owin.Security.WsFederation and dependent packages to version 4.0 and I get the error.
I did not make any code changes other than changing
using Microsoft.IdentityModel.Protocols;
to
using Microsoft.IdentityModel.Protocols.WsFederation;
where is the WsFederationConfiguration class seems to be now.
Here is my StartupAuth:
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(
new CookieAuthenticationOptions
{
AuthenticationType = CookieAuthenticationDefaults.AuthenticationType
});
// Create WsFed configuration from web.config wsfed: values
var wsconfig = new WsFederationConfiguration()
{
Issuer = ConfigurationManager.AppSettings["wsfed:Issuer"],
TokenEndpoint = ConfigurationManager.AppSettings["wsfed:TokenEndPoint"],
};
/*
* Add x509 certificates to configuration
*
*/
// certificate.1 must always exist
byte[] x509Certificate;
x509Certificate = Convert.FromBase64String(ConfigurationManager.AppSettings["wsfed:certificate.1"]);
wsconfig.SigningKeys.Add(new X509SecurityKey(new X509Certificate2(x509Certificate)));
// certificate 2 may exist
if (ConfigurationManager.AppSettings["wsfed:certificate.2"] != null)
{
x509Certificate = Convert.FromBase64String(ConfigurationManager.AppSettings["wsfed:certificate.2"]);
wsconfig.SigningKeys.Add(new X509SecurityKey(new X509Certificate2(x509Certificate)));
}
// certificate 3 may exist
if (ConfigurationManager.AppSettings["wsfed:certificate.3"] != null)
{
x509Certificate = Convert.FromBase64String(ConfigurationManager.AppSettings["wsfed:certificate.3"]);
wsconfig.SigningKeys.Add(new X509SecurityKey(new X509Certificate2(x509Certificate)));
}
// Apply configuration to wsfed Auth Options
var wsoptions = new WsFederationAuthenticationOptions
{
SignInAsAuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
Configuration = wsconfig,
Wreply = ConfigurationManager.AppSettings["wsfed:Wreply"],
Wtrealm = ConfigurationManager.AppSettings["wsfed:Wtrealm"],
};
wsoptions.TokenValidationParameters.NameClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn";
// Add WdFederation middleware to Owin pipeline
app.UseWsFederationAuthentication(wsoptions);
}
Is there something else 4.0 needs to validate the signature? I assume it's talking about the signature of the token from the issuer. I didn't see how to enable ShowPII to see what key it's looking at.
I am using MVC5 with the full framework. Not core.
Update:
I tried to modify the code to use the metadata provided by the identity provider in a properties file to create the WsFederationConfiguration and I still get the same error. I'm not sure what the Signature is, or where I get it from if it's not in the idp metadata.
Update2:
Here are the changes I made to use the wsfed metadata provided by the sts in a properties file. (I have removed the actual base64 encoded metadata, but needless to say it is the same XML you get when you regest the metadata from an STS that publishes it as and endpoint. As I said above, I get the same error:
public void ConfigureAuth(IAppBuilder app)
{
WsFederationConfiguration wsconfig;
app.UseCookieAuthentication(
new CookieAuthenticationOptions
{
AuthenticationType = CookieAuthenticationDefaults.AuthenticationType
});
var metaDataDocument = System.Text.Encoding.UTF8.GetString(
Convert.FromBase64String("...c2NyaXB0b3I+"));
using (var metaDataReader = XmlReader.Create(new StringReader(metaDataDocument), SafeSettings))
{
wsconfig = (new WsFederationMetadataSerializer()).ReadMetadata(metaDataReader);
}
// Apply configuration to wsfed Auth Options
var wsoptions = new WsFederationAuthenticationOptions
{
SignInAsAuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
Configuration = wsconfig,
Wreply = ConfigurationManager.AppSettings["wsfed:Wreply"],
Wtrealm = ConfigurationManager.AppSettings["wsfed:Wtrealm"],
};
wsoptions.TokenValidationParameters.NameClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn";
// Add WdFederation middleware to Owin pipeline
app.UseWsFederationAuthentication(wsoptions);
}
I worked with some folks on the team at MS. The issue here was that our STS is using SHA1 to sign the token and the new version of weFederation doesn't support SHA1 as it is not-secure and is deprecated.
The easiest way to use WIF with owin is through the usage of the federation meta data (which lives at FederationMetadata/2007-06/FederationMetadata.xml). Then you don't need to setup anything at all which is explained in Configure claims based web applications using OWIN WsFederation middleware . The precondition is of course that your STS publishes a meaningful FederationMetaData document. The nice advantage is that your public keys needed for validation are automatically picked up by your application (and renewing them is done seamlessly).
This is IMHO that is much easier than the approach you are taking.
You can follow Manual configuration of OWIN WS-Federation Identity provider as it describes a more easy way than yours.

Implement Google as a identity provider(IDP) using Kentor Auth Service Library in MVC Application?

Hi i am using kentor auth services(The Kentor Authentication services is a library that adds SAML2P support to ASP.NET and IIS web sites, allowing the web site to act as a SAML2 Service Provider (SP) ).Right now i am using Google as a Identity Privider for testing my application (Authentication using owin midddleware).I have set Up Google Identity provider also.But When i run the application it gives me an error
"400. That’s an error.
Invalid Request, invalid idpId in request URL, check if SSO URL is configured properly on SP side. That’s all we know."
i have used SingleSignOnServiceUrl=https://accounts.google.com/o/saml2/idp?idpid=xxxxxxxxx
DiscoveryServiceUrl=https://accounts.google.com/o/saml2/idp?idpid=xxxxxxxxx
Is that above configuration is correct?
I have attached App_start configuration below.This from Kentor auth services library.
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseKentorAuthServicesAuthentication(CreateAuthServicesOptions());
}
private static KentorAuthServicesAuthenticationOptions CreateAuthServicesOptions()
{
var spOptions = CreateSPOptions();
var authServicesOptions = new KentorAuthServicesAuthenticationOptions(false)
{
SPOptions = spOptions
};
var idp = new IdentityProvider(new EntityId("~/App_Data/GoogleIDPMetadata.xml"), spOptions)
{
AllowUnsolicitedAuthnResponse = true,
Binding = Saml2BindingType.HttpRedirect,
SingleSignOnServiceUrl = new Uri("https://accounts.google.com/o/saml2/idp?idpid=xxxxxxxxx")
};
idp.SigningKeys.AddConfiguredKey(
new X509Certificate2(
HostingEnvironment.MapPath(
"~/App_Data/Kentor.AuthServices.StubIdp.cer")));
authServicesOptions.IdentityProviders.Add(idp);
// It's enough to just create the federation and associate it
// with the options. The federation will load the metadata and
// update the options with any identity providers found.
new Federation("http://example.com/Federation", true, authServicesOptions);
return authServicesOptions;
}
private static SPOptions CreateSPOptions()
{
var swedish = CultureInfo.GetCultureInfo("sv-se");
var organization = new Organization();
organization.Names.Add(new LocalizedName("Kentor", swedish));
organization.DisplayNames.Add(new LocalizedName("Kentor IT AB", swedish));
organization.Urls.Add(new LocalizedUri(new Uri("http://www.kentor.se"), swedish));
var spOptions = new SPOptions
{
EntityId = new EntityId("https://example.com/AuthServices"),
ReturnUrl = new Uri("https://example.com/Account/ExternalLoginCallback"),
DiscoveryServiceUrl = new Uri(https://accounts.google.com/o/saml2/idp?idpid=xxxxxxxxx"),
Organization = organization
};
var techContact = new ContactPerson
{
Type = ContactType.Technical
};
techContact.EmailAddresses.Add("authservices#example.com");
spOptions.Contacts.Add(techContact);
var supportContact = new ContactPerson
{
Type = ContactType.Support
};
supportContact.EmailAddresses.Add("support#example.com");
spOptions.Contacts.Add(supportContact);
var attributeConsumingService = new AttributeConsumingService("AuthServices")
{
IsDefault = true,
};
attributeConsumingService.RequestedAttributes.Add(
new RequestedAttribute("urn:someName")
{
FriendlyName = "Some Name",
IsRequired = true,
NameFormat = RequestedAttribute.AttributeNameFormatUri
});
attributeConsumingService.RequestedAttributes.Add(
new RequestedAttribute("Minimal"));
spOptions.AttributeConsumingServices.Add(attributeConsumingService);
spOptions.ServiceCertificates.Add(new X509Certificate2(
AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "/App_Data/Kentor.AuthServices.Tests.pfx"));
return spOptions;
}
Why i am getting 400 error when i redirect to google saml page? Thanks in advance
AFAIK Google offers no discovery service. Remove the DiscoveryServiceUrl from the configuration.
Also you should really clean up the configuration and not use the sample application's config.
For testing you can also use the Stub idp that is included in the project at which is available at http://stubidp.kentor.se

WebApi2 Google OAuth2 middleware error response

For user authentication with external providers such as Google, it is using specific Owin middlewares. As for example Microsoft.Owin.Security.Google. WebAPI2 template uses this to support implicit flow authentication (response_type=token). But what about Code flow?
Is it possible to implement Code flow (response_type=code)?
After debugging those OAuth providers I noticed that passing return_type=code to Google, it successfully authenticates and returns json with access and refresh tokens, then user gets signed in by api/Account/ExternalLogin endpoint but at the end of the flow I get redirected to
http://localhost:50321/?error=unsupported_response_type#.
I could not really find the flow where and why it is setting this specific error in the assembly.
Startup.Auth.cs looks like this:
public void ConfigureAuth(IAppBuilder app)
{
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
PublicClientId = "self";
var tokenTimeSpanInHours = ConfigurationManager.AppSettings["AccessTokenLifeTimeInHours"];
OAuthServerOptions = new OAuthAuthorizationServerOptions
{
Provider = new ApplicationOAuthProvider(PublicClientId),
TokenEndpointPath = new PathString("/api/token"),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(Convert.ToInt16(tokenTimeSpanInHours)),
AllowInsecureHttp = true
};
app.UseOAuthBearerTokens(OAuthServerOptions);
var googleOAuthOptions = new GoogleOAuth2AuthenticationOptions
{
AccessType = "offline",
Provider = new CustomGoogleAuthProvider(),
ClientId = ConfigurationManager.AppSettings["GoogleAccountClientId"].ToString(),
ClientSecret = ConfigurationManager.AppSettings["GoogleAccountClientSecret"].ToString()
};
googleOAuthOptions.Scope.Add("profile");
googleOAuthOptions.Scope.Add("email");
googleOAuthOptions.Scope.Add("https://www.googleapis.com/auth/gmail.send");
app.UseGoogleAuthentication(googleOAuthOptions);
}
Where is the problem then? Do I need some explicit configuration to tell that I want code flow? Is it supported?

Resources