Jhipster and Spring Security - Add Authentication provider leaving active default jdbcauthentication mode - spring

I've added a custom LDAP authentication provider mechanism to my jHipster application. Without insert any configureGlobal(AuthenticationManagerBuilder auth) or configureGlobal(AuthenticationManagerBuilder auth) method to SecurityConfiguration class, but with #Component annotation on my custom AuthenticationProvider implementation, the new authentication work fine, but, I lose the default authentication with users on database.
I try to add this on securityConfiguration:
#Inject
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
super.configure(auth);
auth.authenticationProvider(aDauthenticationProvider);
}
but the result is the same, I lose the database authentication.
How could I add the default auth mechanism to the list of providers of AuthenticationManagerBuilder?
Thanks

I've found the solution, I write this if someone have my same issue.
It's sufficient to add this code line on GlobalConfigure method:
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
to add the predefined JDBC authentication method to the list of authentication providers.

Related

Using two API Key on Swagger Security Scheme with Spring Boot

Is it possible to have two API Keys on Swagger and give them different privileges in my API?
For example:
API_KEY_1 : Has access to one Post method
API_KEY_2 : Has access to all of my API
Many thanks
In terms of Spring Security, that all depends on how you authenticate the API keys in your application. Once you've set up the application to validate an API key and create a SecurityContext, your best bet would be to map to one of two different roles, one for limited access, and one for all access. For example:
#Configuration
public static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
// ...
.authorizeRequests()
.mvcMatchers(HttpMethod.POST, "/some/api").hasAnyRole("BASIC", "ADMIN")
.anyRequest().hasRole("ADMIN");
}
}
More information and examples of authorization can be found in the docs.

How to reload the Configure method of WebSecurityConfigurerAdapter when the application is up and running

I am using spring boot and in spring security we are using "WebSecurityConfigurerAdapter" and using the method
#Override
protected void configure(HttpSecurity http) throws Exception {
AuthenticationFilter authenticationFilter = new AuthenticationFilter(authenticationManager(), tokenService(), externalServiceAuthenticator());
http.addFilterBefore(authenticationFilter, BasicAuthenticationFilter.class)
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeRequests().antMatchers(externalServiceCaller.getPrivateEndPoints())
.hasAnyAuthority(externalServiceCaller.getAllAuthorities()).anyRequest().authenticated()
.and().authorizeRequests().anyRequest().anonymous()
.and().exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint())
.and().exceptionHandling().authenticationEntryPoint(forbiddenEntryPoint());
}
This is working fine for existing role and user but when we are adding more users and role at run time (After the application start) then spring security is not able to recognize new role and new user . Is there any way to call the above method again when the application is up and running.
Reload configure(HttpSecurity http) is impossible in runtime, because it's some kind of builder and it's creates some part of the spring security chain when the application is starting - if you'd like to reload the method you have to replace the spring security chain during runtime - it's not so easy and recommended way.
If you need add some user during runtime - implement custom AuthentificationProvider

Unable to Authenticate a User with an LDAP Server using LDAP User Search Query with Spring Security

LDAP Server Hierarchy as retrieved via Apache Directory Studio:
Root DSE:
DC=company,DC=com
OU=Offices
OU=Region Offices
OU=Region1 Office
OU=Users
CN=Jayesh Mulwani
WebSecurity is enabled as a part of below class:
public class LDAPSecurityConfig extends WebSecurityConfigurerAdapter{
protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.ldapAuthentication()
.contextSource().url("ldap://server-url/CN=auth_support,OU=Misc,DC=company,DC=com")
.managerDn("username").managerPassword("password")
.and()
.userSearchBase("OU=Offices,DC=company,DC=com")
.userSearchFilter("(&(objectClass=user)(cn={0}))");
}
}
Once the application is setup on tomcat, i enter the username along with its password but the authentication fails and no error is prompted.
Can someone please assist me with the approach or specify if i'm missing something here ?
I have fixed the problem by adding the below two conditions
.groupSearchFilter("(&(objectClass=group)(AccountName={0}))")
.groupSearchBase("CN=DEPT_All_Employees,OU=DepartmentSecurityGroups,OU=Resources,DC=company,DC=com")
I referred this example to fix the issue http://www.jcombat.com/spring/spring-security-ldap-authentication

Issue with the spring security tutorial on spring.io

I am trying to run the spring security application on the official website. When I try to access the context root I get the user authentication prompt even though .antMatchers("/", "/home").permitAll() allows all access to /home and /. Also the password is being set in the application in the following code
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
However I still get the Using default security password message in the logs with the password mentioned. Please could you help.
Edit:
I had made a mistake in the code, I forgot to annotate the WebSecurityConfig class with #Configuration and #EnableWebSecurity annotations.
The password which you find from log is from basic auth which is by default enabled, you can do httpBasic().disabled() to disable it, then you will not see the default password any more.
Update
I saw you are using spring-boot, which makes live much easier, try add this property: security.basic.enabled=false, it should help you to disable it..

Authentication of background tasks using Spring Boot and Spring Security

I have a background task (running with Project Reactor, but I don't think it is relevant) that I need to run in with an authenticated user to get through some #PreAuthorize annotated methods.
I'm doing something like this:
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(login, password));
SecurityContextHolder.getContext().setAuthentication(authentication);
But when I trace into the authenticationManager call, I find that it is using Spring-Boot's default InMemoryUserDetailsService, rather than my custom authentication configuration. This happens regardless of whether I run the authentication in a web request thread, or in the background thread.
I don't know if it is relevant, but I am running this code in an integration test, with these annotations (among others):
#SpringApplicationConfiguration(classes=MyAppConfiguration.class)
#WebAppConfiguration
#IntegrationTest({"server.port:0"})
In addition to this problem, my test makes an authenticated web request to my server, and that authenticates just fine. So I know at least the web portion of my system is using the correct authenication configuration.
Here is my authentication configuration:
#EnableWebMvcSecurity
#EnableGlobalMethodSecurity(jsr250Enabled=true, prePostEnabled=true)
public abstract class BaseSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public LocalUserDetailsService localUserDetailsService;
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(localUserDetailsService);
}
#Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().httpBasic()
.and()
.authorizeRequests()
.antMatchers( "/admin/**" ).hasRole( "ADMIN" )
}
It is hard to tell without your test implementatiton but it matters that you are running it in integration test
Maybe you are forgetting to add `FilterChainProxy to your mockMvc
like this mvc = MockMvcBuilders.webAppContextSetup(context)
.addFilter(springSecurityFilterChain).build();
instance of filterChainPrioxy can be #Autowired into your test class, of course this answer may not make sense, depends of your implementation of test class
---after your comment
this line :
SecurityContextHolder.getContext().setAuthentication(authentication);
assigns security constrains to current thread and does not impact threads running in background, unless your strategy is global and it is not default

Resources