Tomasm21
Tomasm21
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 1/16/2025 in #java-help
How to define 3 authentication ways config - httpBasic, userDetailsService, JsonLoginFilter()
Ok I will try
24 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 1/16/2025 in #java-help
How to define 3 authentication ways config - httpBasic, userDetailsService, JsonLoginFilter()
These problems are not new.
24 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 1/16/2025 in #java-help
How to define 3 authentication ways config - httpBasic, userDetailsService, JsonLoginFilter()
There should be a way.
24 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 1/16/2025 in #java-help
How to define 3 authentication ways config - httpBasic, userDetailsService, JsonLoginFilter()
But would it mean that if I will qualify the databaseProvider bean and then in postman I will try to autheticate using Basic Auth then what happens next? Due to qualifiers it will always try to athenticate me using databaseProvider instead of the inMemoryProvider. And perhaps I won't be able to auntheticate.
24 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 1/16/2025 in #java-help
How to define 3 authentication ways config - httpBasic, userDetailsService, JsonLoginFilter()
JsonLoginFilter():
public class JsonLoginFilter extends UsernamePasswordAuthenticationFilter {
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (request.getContentType() != null && request.getContentType().equals("application/json")) {
try {
// Parse the raw JSON request body
ObjectMapper objectMapper = new ObjectMapper();
@SuppressWarnings("unchecked")
Map<String, String> credentials = objectMapper.readValue(request.getInputStream(), Map.class);
String username = credentials.get("username");
String password = credentials.get("password");

// Create the authentication token with the username and password
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
} catch (IOException e) {
throw new BadCredentialsException("Failed to parse JSON request", e);
}
}

// Fall back to the default form login behavior
return super.attemptAuthentication(request, response);
}
}
public class JsonLoginFilter extends UsernamePasswordAuthenticationFilter {
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (request.getContentType() != null && request.getContentType().equals("application/json")) {
try {
// Parse the raw JSON request body
ObjectMapper objectMapper = new ObjectMapper();
@SuppressWarnings("unchecked")
Map<String, String> credentials = objectMapper.readValue(request.getInputStream(), Map.class);
String username = credentials.get("username");
String password = credentials.get("password");

// Create the authentication token with the username and password
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
} catch (IOException e) {
throw new BadCredentialsException("Failed to parse JSON request", e);
}
}

// Fall back to the default form login behavior
return super.attemptAuthentication(request, response);
}
}
24 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 1/16/2025 in #java-help
How to define 3 authentication ways config - httpBasic, userDetailsService, JsonLoginFilter()
I want to have all three ways to authenticate. Did I defined it wrong in my SecurityConfiguration ? How should it be defined? Why Spring doesn't accept my changed AuthenticationManager with two DaoAuthenticationProvider providers that each provides different way to authenticate? One for in memory db and another using real MySql db.
24 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 1/16/2025 in #java-help
How to define 3 authentication ways config - httpBasic, userDetailsService, JsonLoginFilter()
24 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 1/16/2025 in #java-help
How to define 3 authentication ways config - httpBasic, userDetailsService, JsonLoginFilter()
As a result I can't authenticate in either way. I get an exception:
24 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 1/16/2025 in #java-help
How to define 3 authentication ways config - httpBasic, userDetailsService, JsonLoginFilter()
Problem:
Found 2 UserDetailsService beans, with names [userDetailsServicImp, inMemoryUserDetailsManager]. Global Authentication Manager will not use a UserDetailsService for username/password login. Consider publishing a single UserDetailsService bean.
Found 2 UserDetailsService beans, with names [userDetailsServicImp, inMemoryUserDetailsManager]. Global Authentication Manager will not use a UserDetailsService for username/password login. Consider publishing a single UserDetailsService bean.
and
No authenticationProviders and no parentAuthenticationManager defined. Returning null.
No authenticationProviders and no parentAuthenticationManager defined. Returning null.
24 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 1/16/2025 in #java-help
How to define 3 authentication ways config - httpBasic, userDetailsService, JsonLoginFilter()
24 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 1/16/2025 in #java-help
How to define 3 authentication ways config - httpBasic, userDetailsService, JsonLoginFilter()
It executes well but in console I get:
24 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 1/16/2025 in #java-help
How to define 3 authentication ways config - httpBasic, userDetailsService, JsonLoginFilter()
@Bean
public AuthenticationManager authenticationManager() {
DaoAuthenticationProvider inMemoryProvider = new DaoAuthenticationProvider();
inMemoryProvider.setUserDetailsService(inMemoryUserDetailsManager());
inMemoryProvider.setPasswordEncoder(passwordEncoder.passwordEncoder());

DaoAuthenticationProvider databaseProvider = new DaoAuthenticationProvider();
databaseProvider.setUserDetailsService(userDetailsService);
databaseProvider.setPasswordEncoder(passwordEncoder.passwordEncoder());

// Combine both providers in a custom AuthenticationManager
return new ProviderManager(List.of(inMemoryProvider, databaseProvider));
}

@Bean
public InMemoryUserDetailsManager inMemoryUserDetailsManager() {
// Create two in-memory users
UserDetails user = User.withUsername("user")
.password(passwordEncoder.passwordEncoder().encode("userpass"))
.roles("USER")
.build();

UserDetails admin = User.withUsername("admin")
.password(passwordEncoder.passwordEncoder().encode("adminpass"))
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
}
@Bean
public AuthenticationManager authenticationManager() {
DaoAuthenticationProvider inMemoryProvider = new DaoAuthenticationProvider();
inMemoryProvider.setUserDetailsService(inMemoryUserDetailsManager());
inMemoryProvider.setPasswordEncoder(passwordEncoder.passwordEncoder());

DaoAuthenticationProvider databaseProvider = new DaoAuthenticationProvider();
databaseProvider.setUserDetailsService(userDetailsService);
databaseProvider.setPasswordEncoder(passwordEncoder.passwordEncoder());

// Combine both providers in a custom AuthenticationManager
return new ProviderManager(List.of(inMemoryProvider, databaseProvider));
}

@Bean
public InMemoryUserDetailsManager inMemoryUserDetailsManager() {
// Create two in-memory users
UserDetails user = User.withUsername("user")
.password(passwordEncoder.passwordEncoder().encode("userpass"))
.roles("USER")
.build();

UserDetails admin = User.withUsername("admin")
.password(passwordEncoder.passwordEncoder().encode("adminpass"))
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
}
24 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 1/16/2025 in #java-help
How to define 3 authentication ways config - httpBasic, userDetailsService, JsonLoginFilter()
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

@Autowired
private UserDetailsServicImp userDetailsService;

@Autowired
private CustomAuthenticationFailureHandler customFailureHandler;

@Autowired
private EncoderConfig passwordEncoder;

@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/**").permitAll()
.anyRequest().authenticated())
.formLogin(formLogin -> formLogin
.loginPage("/login")
.defaultSuccessUrl("/hi", true)
.failureHandler(customFailureHandler)
//.failureUrl("/login?error=true")
.permitAll())
.httpBasic(Customizer.withDefaults())
.logout(logout -> logout
.logoutUrl("/logout")
.logoutSuccessHandler((request, response, authentication) -> {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json");
response.getWriter().write("{\"message\": \"Logout successful\"}");
})
.invalidateHttpSession(true)
.clearAuthentication(true)
.permitAll())
.addFilterBefore(new JsonLoginFilter(), UsernamePasswordAuthenticationFilter.class);
httpSecurity.authenticationManager(authenticationManager());
return httpSecurity.build();
}
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

@Autowired
private UserDetailsServicImp userDetailsService;

@Autowired
private CustomAuthenticationFailureHandler customFailureHandler;

@Autowired
private EncoderConfig passwordEncoder;

@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/**").permitAll()
.anyRequest().authenticated())
.formLogin(formLogin -> formLogin
.loginPage("/login")
.defaultSuccessUrl("/hi", true)
.failureHandler(customFailureHandler)
//.failureUrl("/login?error=true")
.permitAll())
.httpBasic(Customizer.withDefaults())
.logout(logout -> logout
.logoutUrl("/logout")
.logoutSuccessHandler((request, response, authentication) -> {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json");
response.getWriter().write("{\"message\": \"Logout successful\"}");
})
.invalidateHttpSession(true)
.clearAuthentication(true)
.permitAll())
.addFilterBefore(new JsonLoginFilter(), UsernamePasswordAuthenticationFilter.class);
httpSecurity.authenticationManager(authenticationManager());
return httpSecurity.build();
}
24 replies
JCHJava Community | Help. Code. Learn.
Created by Maxxx005 on 1/16/2025 in #java-help
production vs development
You're welcome.
271 replies
JCHJava Community | Help. Code. Learn.
Created by Maxxx005 on 1/16/2025 in #java-help
production vs development
And yes I never used flyway, but I heard many recommendations of it for production. Either investigate deeply why currently the table is not created or go with flyway.
271 replies
JCHJava Community | Help. Code. Learn.
Created by Maxxx005 on 1/16/2025 in #java-help
production vs development
Sometimes, ddl-auto=update only runs during application startup if there are changes detected in the entity mappings. If there is any issue with the entity itself (like missing annotations or improper configuration), Hibernate might not attempt to create the new table. Double-check your entity class to ensure the table and field mappings are correct. Enable detailed logging for Hibernate to see if it is trying to update the schema and to check for any errors related to schema validation or creation.
logging.level.org.hibernate.tool.hbm2ddl=DEBUG
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.tool.hbm2ddl=DEBUG
logging.level.org.hibernate.SQL=DEBUG
Does it create the table in development but not production?
271 replies
JCHJava Community | Help. Code. Learn.
Created by Maxxx005 on 1/16/2025 in #java-help
production vs development
# JPA Configuration
spring.jpa.hibernate.ddl-auto=update
# JPA Configuration
spring.jpa.hibernate.ddl-auto=update
?
271 replies
JCHJava Community | Help. Code. Learn.
Created by circle on 11/16/2024 in #java-help
ResponseEntity incorrectly maps values
I reported it to Springdoc issues on github.
49 replies
JCHJava Community | Help. Code. Learn.
Created by circle on 11/16/2024 in #java-help
ResponseEntity incorrectly maps values
The problem is in front-end. For unknown reason Swagger shows variant ids wrong. But in response body numbers are correct.
49 replies
JCHJava Community | Help. Code. Learn.
Created by circle on 11/16/2024 in #java-help
ResponseEntity incorrectly maps values
When I debugged like you then in service method ProductDto is with correct variant ids for both loading Variants eagerly or lazily.
49 replies