Programatically configure sso settings using kentor - okta

I have an MVC application (.Net Framework 4.5) which is been there for the last three years and using Forms Authentication mechanism. Now we want to integrate SSO feature with the help of Okta. Using KentorIT Authentication services I was able to integrate Okta with my mvc application. In that, all the configurations are being set in the web.config file (eg: entityId, signOnUrl etc.). Is there a way to programmatically configure these sso settings? I found that KentorAuthServicesSection is the class that we have to instantiate to do the process. Currently its reading the settings from configuration file.
public class KentorAuthServicesSection : ConfigurationSection
{
private static readonly KentorAuthServicesSection current =
(KentorAuthServicesSection)ConfigurationManager.GetSection("kentor.authServices");
}
So modifying this ConfigurationManager.GetSection("kentor.authServices") part with a custom implementation will do the job? or is there any other good approach ?

You can just use the options classes directly -- no need to customize the GetSection.
I'm assuming you are using the Mvc module. In which case you want to set the options on the AuthServicesController during application startup, e.g.
Kentor.AuthServices.Mvc.AuthServicesController.Options = myOptions;
With your own construction of these same configuration classes. For example:
var spOptions = new SPOptions
{
EntityId = new EntityId("http://localhost:57294/AuthServices"),
ReturnUrl = new Uri("http://localhost..."),
//...
};
options = new KentorAuthServicesAuthenticationOptions(false)
{
SPOptions = spOptions
};
The false in this constructor tells it not to read from the configuration system.
There is a larger example in the OWIN sample project:
https://github.com/KentorIT/authservices/blob/v0.21.1/SampleOwinApplication/App_Start/Startup.Auth.cs#L54-L82

Related

Enable by default an Actuator Endpoint in Spring Boot

I developed a small library that adds a custom endpoint for the actuator and I like to expose it by default. Spring Boot 2.7.4 only exposes by default health.
At the moment, what I am doing is registering an EnvironmentPostProcessor to add a property to include health,jwks at the last PropertySource in the environment. But it seems a little bit fragile. There are other libraries that have to export other endpoints by default (metrics, prometheus...)
This is what I am doing at the moment:
public class PoCEnvironmentPostProcessor implements EnvironmentPostProcessor {
private static final String PROPERTY_NAME = "management.endpoints.web.exposure.include";
#Override
public void postProcessEnvironment(
ConfigurableEnvironment environment,
SpringApplication application
) {
var propertySources = environment.getPropertySources();
propertySources.stream()
.filter(it -> it.containsProperty(PROPERTY_NAME))
.findFirst().ifPresentOrElse(source -> {
var property = source.getProperty(PROPERTY_NAME);
var pocSource = new MapPropertySource(PROPERTY_NAME, Map.of(PROPERTY_NAME, property + ",jwks"));
// Add the new property with more priority
propertySources.addBefore(source.getName(), pocSource);
}, () -> {
var pocSource = new MapPropertySource(PROPERTY_NAME, Map.of(PROPERTY_NAME, "health,jwks"));
propertySources.addLast(pocSource);
});
}
}
Is there any way to expose by default that allow me to add several endpoints in different libraries without playing to much with the property sources?
It’s not exactly clear to me if you’re asking how the client apps that use your library would enable specific endpoints, or if you are writing more than one library and want to expose different endpoints. I’ll answer both.
management.endpoints.web.exposure.include=comma-separated-endpoints would enable the listed endpoints without your library having to do anything. Your client apps can set this property in application.yml.
If you want to set this property by default in your library, one of the easiest ways is to put it in a property file, and load it as a #PropertySource on a #Configuration bean. I’m assuming your library is a starter and the #Configuration bean is auto-configured. If you don’t know how to create a starter, refer to this article.

How to get the value of Azure App Configuration Feature Flag with specific label from Spring boot?

I started using Azure App Configuration service and Feature Flags functionality in my project. I followed this documentation and was able to create a Spring boot project. I also created a FeatureFlagService class and autowired the FeatureManager class in it as shown below :
#Service
public class FeatureFlagService {
private FeatureManager featureManager;
public FeatureFlagService(FeatureManager featureManager) {
this.featureManager = featureManager;
}
public boolean isFeatureEnabled() {
return featureManager.isEnabledAsync("scopeid/MyFeature").block();
}
}
With this I get the value of the feature flag 'MyFeature' but with no label.
I have the same feature defined with different labels in Azure App Configuration as shown below.
I need to fetch the feature flag with specific label. How can I achieve it at runtime?
I don't see a way to do it using the FeatureManager class.
They only way to load from a label is by using spring.cloud.azure.appconfiguration.stores[0].feature-flags.label-filter, the Feature Management Library itself has no concept of a label.

How to stop generating dynamic web api?

I have downloaded template and creating sample task application.
From below reference I found Web API auto generated from my task service class.
Dynamic web api generation
So how can I stop this behaviour or make changes in this behavior.
You can easily disable an application service to expose its methods as Web API actions.
Just use [RemoteService(false)] attribute on application service class or application service interface.
[RemoteService(IsEnabled = false)]
public class UserAppService : ApplicationService, IUserAppService
{
}
for mass operation, use #aaron's method.
Comment out the lines mentioned on that page.
ASP.NET MVC 5
// Configuration.Modules.AbpWebApi().DynamicApiControllerBuilder
// .ForAll<IApplicationService>(typeof(AbpProjectNameApplicationModule).Assembly, "app")
// .Build();
https://github.com/aspnetboilerplate/module-zero-template/blob/c0d7f0433d573a8207b27f817e1d188c215f1e50/src/AbpCompanyName.AbpProjectName.WebApi/Api/AbpProjectNameWebApiModule.cs#L17-L19
ASP.NET Core
// Configuration.Modules.AbpAspNetCore()
// .CreateControllersForAppServices(
// typeof(AbpProjectNameApplicationModule).GetAssembly()
// );
https://github.com/aspnetboilerplate/module-zero-core-template/blob/bb9d5aab6e5047d6d22d49831b473c0b3329b499/aspnet-core/src/AbpCompanyName.AbpProjectName.Web.Core/AbpProjectNameWebCoreModule.cs#L44-L47

Spring boot application properties load process change programatically to improve security

I have spring boot micro-service with database credentials define in the application properties.
spring.datasource.url=<<url>>
spring.datasource.username=<<username>>
spring.datasource.password=<<password>>
We do not use spring data source to create the connection manually. Only Spring create the database connection with JPA.(org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration)
We only provide the application properties, but spring create the connections automatically to use with the database connection pool.
Our requirement to enhance the security without using db properties in clear text. Two possible methods.
Encrypt the database credentials
Use the AWS secret manager. (then get the credential with the application load)
For the option1, jasypt can be used, since we are just providing the properties only and do not want to create the data source manually, how to do to understand by the spring framework is the problem. If better I can get some working sample or methods.
Regarding the option-2,
first we need to define secretName.
use the secertName and get the database credentials from AWS secret manager.
update the application.properties programatically to understand by spring framework. (I need to know this step)
I need to use either option1 and option2. Mentioned the issues with each option.
What you could do is use environment variables for your properties. You can use them like this:
spring.datasource.url=${SECRET_URL}
You could then retrieve these and start your Spring process using a ProcessBuilder. (Or set the variables any other way)
I have found the solution for my problem.
We need to define org.springframework.context.ApplicationListenerin spring.factories file. It should define the required application context listener like below.
org.springframework.context.ApplicationListener=com.sample.PropsLoader
PropsLoader class is like this.
public class PropsLoader implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
#Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ConfigurableEnvironment environment = event.getEnvironment();
String appEnv = environment.getProperty("application.env");
//set new properties based on the application environment.
// calling other methods and depends on the enviornment and get the required value set
Properties props = new Properties();
props.put("new_property", "value");
environment.getPropertySources().addFirst(new PropertiesPropertySource("props", props));
}
}
spring.factories file should define under the resources package and META-INF
folder.
This will set the application context with new properties before loading any other beans.

NServiceBus and ApiController

i try to configure my NServiceBus for a WebApi. I've tried this one: https://coderkarl.wordpress.com/2012/03/16/injecting-nservicebus-into-asp-net-webapi/
The Problem is the Syntax has been changed in the newest NServiceBus-Versin. I can't use the Functions for the Configure-Class because they will be removed in further Versions. The new way to configure the Bus is using the BusConfiguration-Class but i have no idea how.
Here is the older Code:
public static Configure ForWebApi(this Configure configure)
{
// Register our http controller activator with NSB
configure.Configurer.RegisterSingleton(typeof(IHttpControllerActivator),
new NSBHttpControllerActivator());
// Find every http controller class so that we can register it
var controllers = Configure.TypesToScan
.Where(t => typeof(IHttpController).IsAssignableFrom(t));
// Register each http controller class with the NServiceBus container
foreach (Type type in controllers)
configure.Configurer.ConfigureComponent(type, ComponentCallModelEnum.Singlecall);
// Set the WebApi dependency resolver to use our resolver
GlobalConfiguration.Configuration.ServiceResolver.SetResolver(new NServiceBusResolverAdapter(configure.Builder));
// Required by the fluent configuration semantics
return configure;
}
And Application_Start():
AreaRegistration.RegisterAllAreas();
// Use LocalDB for Entity Framework by default
Database.DefaultConnectionFactory = new SqlConnectionFactory("Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
BundleTable.Bundles.RegisterTemplateBundles();
Configure.WithWeb()
.DefaultBuilder()
.ForWebApi() // <------ here is the line that registers it
.Log4Net()
.XmlSerializer()
.MsmqTransport()
.IsTransactional(false)
.PurgeOnStartup(false)
.UnicastBus()
.ImpersonateSender(false)
.CreateBus()
.Start();
Does someone has managed it for the NServiceBus Version 5?
As wlabaj says, the documentation on the particular website says it all. Almost.
We use AutoFac so we don't need any direct reference to IBus or ISendOnlyBus and therefor we do this
ContainerBuilder builder = new ContainerBuilder();
var container = builder.Build();
configuration.UseContainer<AutofacBuilder>(x => x.ExistingLifetimeScope(container));
What we do in WebAPI and ASP.NET applications is this
NServiceBus.Bus.CreateSendOnly(configuration);
Because it's not a good practice to expect reply messages to come back after sending them.
Here you can see 3.0 vs 4.0 vs 5.0 configuration syntax. At the top of the page you have a link to download code samples.
The examples are for ASP .NET though, so you'll need to tweak it slightly for WebAPI. Let me know if you need further help with that.
ForWebApi was never a part of NServiceBus, this was an extension method from the sample that was used to configure NServiceBus dependency resolver to instantiate controllers. The way how it was done is shown here.
There is no need to use NServiceBus resolver since it is just a wrapper around another container. By default it uses Autofac, so you can just use Autofac to work for you in the whole application.
Autofac WebAPI integration is properly described in the documentation.
NServiceBus documentation has a page about using your own container.
This is a very well known setup that you can easily implement.

Resources