• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Spring xml configuration for cors

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
 I 've java code but xml file pick up all easily by spring Framework (no springboot), but got an exception.
---------------------------------
Exception

org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL contained a potentially malicious String "//"
org.springframework.security.web.firewall.StrictHttpFirewall.rejectedBlacklistedUrls(StrictHttpFirewall.java:374)
org.springframework.security.web.firewall.StrictHttpFirewall.getFirewalledRequest(StrictHttpFirewall.java:336)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:194)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:354)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:267)
---------------------------------------
     I try to add cors, in vain no matter what, it does not have any constructor-ar nor property or factory:
     <beans:bean id="corsSource" class="org.springframework.web.cors.UrlBasedCorsConfigurationSource">
  <!--beans:constructor-arg name="corsConfiuration">
<beans:bean class="org.springframework.web.cors.CorsConfiguration">
<beans:property name="allowedOrigins" value="*" />
<beans:property name="allowedMethods" value="*" />
<beans:property name="allowedHeaders" value="*" />
<beans:property name="allowCredentials" value="true" />
</beans:bean>
</beans:constructor-arg-->
  </beans:bean>

Thanks ahead!
A.
 
Saloon Keeper
Posts: 28319
210
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The only info I have direct experience with is on Spring Boot, but if I'm not mistaken, CORS configuration has been deprecated because it's now built-in.

I recommend checking to be sure, but that may be why you can't configure it.
 
A. Wan
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Tim,
   That's in the latest springboot.  I added strictfirewall in vain, maybe its not for //, I don't see anything can allow //:
   <beans:bean id="allowSemicolonHttpFirewall" class="org.springframework.security.web.firewall.StrictHttpFirewall">
<!--
Allows configuring the allowSemicolon StrictHttpFirewall property to avoid errors
   like 'the request was rejected because the URL contained a potentially malicious String ";"'
   ";" in URL's come in the form http://<domain>/<path>;jsessionid=xxxx OR in static resource
   URLs (e.g to reference bundles of JS files (minified on the fly)).
   In general, proxied applications are discouraged to disclose jsessionid this way, and shall use a cookie instead.
   Some applications like though can't be modified to use cookies, hence this configuration.
-->
  <beans:property name="allowSemicolon" value="false"/>
</beans:bean>
<http-firewall ref="allowSemicolonHttpFirewall"/>
<beans:bean id="encFirewall" class="org.springframework.security.web.firewall.StrictHttpFirewall" >
<beans:property name="AllowUrlEncodedSlash" value="true"/>
   </beans:bean>

A.W.
 
Saloon Keeper
Posts: 15727
368
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It would be helpful if you could share the URL that caused the exception.
 
Tim Holloway
Saloon Keeper
Posts: 28319
210
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:It would be helpful if you could share the URL that caused the exception.


The actual error message indicates a URL request was made with a "//" in the wrong place. That can be due to sloppy typing or link formatting, but as an attack it would be an attempt to walk uphill and outside the root directory of the webapp. A variation on this is abuse of ".." in URLs.

Java's webapp (WAR) structure doesn't allow such paths, as the root of the WAR is treated at the root of the app's "filesystem" (more accurately, resource tree). But by being sensitive to such bad URLs, the Spring Security system can help alert you to potential attackers. Who might be also trying attack vectors more likely to break through the JEE app sandbox.

As I said, my exposure to Spring Security has been mostly from Spring Boot. But there isn't a special version of Spring Security unique to Spring Boot. It uses the standard Spring Security, with only a little support to link the app to Spring Security.
 
A. Wan
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Tim,

  This tin stuck with me for quite some time. I could not click on the first page to login it was blocked, I tried to use java code to configure it but was stuck with HttpSecurity saying http not found but it is a parameter to pass in not a bean:

@Line   public SecurityFilterChain filterChain(HttpSecurity http) throws Exception

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 Logger logger = LogManager.getLogger(SecurityConfig.class);
 
 private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
 
 @Bean
 public UserDetailsService getUserDetailsServiceImpl() {
   return (UserDetailsService)new UserServiceImpl();
 }
 
 @Bean
 public DaoAuthenticationProvider provider() {
   DaoAuthenticationProvider daoautpro = new DaoAuthenticationProvider();
   daoautpro.setUserDetailsService(getUserDetailsServiceImpl());
   daoautpro.setPasswordEncoder((PasswordEncoder)this.encoder);
   return daoautpro;
 }
 
 protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   auth.userDetailsService(getUserDetailsServiceImpl()).passwordEncoder((PasswordEncoder)this.encoder);
 }
 
 public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/process-login*", "/customLogin*",  "/favicon.ico", "/register", "/search/**", "/secure/sub", "/recover*", "/signup*", "/styles/**",
"/webForm", "/reset-password", "/change-password", "/handlePasswordReset", "/userlogin", "/blogs", "/terms", "/error", "/.well-known/**").permitAll()
.anyRequest().authenticated()
.and().formLogin().loginPage("/customLogin") //in order to use custom loginPage
.successHandler(authenticationSuccessHandler()) //new AdPlatformAuthenticationSuccessHandler()) new CustomAuthenticationSuccessHandler())
//.loginProcessingUrl("login") no use here
.defaultSuccessUrl("/", true)
.failureHandler(new CustomAuthenticationFailureHandler()) //authenticationFailureHandler())
.failureForwardUrl("/login?error=true")
.and().logout() //.logoutUrl("/log-out")
.permitAll();
//.httpBasic(withDefaults());
return http.build();
 }
 
 CorsConfigurationSource corsConfigurationSource() {
   this.logger.log(Level.WARN, "cors configure?!");
   CorsConfiguration configuration = new CorsConfiguration();
   configuration.setAllowedOrigins(Arrays.asList(new String[] { "*" }));
   configuration.setAllowedMethods(Arrays.asList(new String[] { "*" }));
   configuration.setAllowedHeaders(Arrays.asList(new String[] { "*" }));
   configuration.setAllowCredentials(Boolean.valueOf(true));
   UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
   source.registerCorsConfiguration("/**", configuration);
   return (CorsConfigurationSource)source;
 }

}

A.W.
 
A. Wan
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
 I cannot wire up pages that do not use spring security such as register, which uses EntityManager, it's null when I autowire it in a persistent context.

Thanks,
A.W.
 
Tim Holloway
Saloon Keeper
Posts: 28319
210
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I use Spring JPA, so it may be different.

My older stuff get its EntityManager like this:


My newer stuff is based on @Repository templates and the EntityManager is not visible there, since all the code gets automatically generated.
 
A. Wan
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have it. No @Autowired? How does Spring know it, and does persistence context automatically get Entity Manager from Spring Configuration?

Here is what in my applicationContext:
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
   <property name="packagesToScan"
               value="com.*, net.*" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
</bean>
</property>
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

<bean id="transactionManager"
         class="org.springframework.orm.jpa.JpaTransactionManager">
         <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!--spring could not find it in another applicationContext-databse.xml file-->
   <bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/MYDB" />
<property name="username" value="XXX" />
<property name="password" value="YYY" />
</bean>
<!-- may only need tx:annotation, not the above -->
   <tx:annotation-driven/>

Thanks,
A.
 
Tim Holloway
Saloon Keeper
Posts: 28319
210
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please use Code tags when posting formatted text. Code tags not only make Java code easier to read, they also work on XML, SQL, and many other text forms.

The @EntityManager tag takes care of injection. It's part of Spring Data for JPA and Spring Data automatically handles a lot of the low-level work required to manage a persistent object environment so you don't need to spend a lot of time coding (and debugging!) often-repeated functions like transaction management.

As long as the classes using the EntityManager have been tagged and are part of the annotation scan path, Spring Data will set it up properly.
 
A. Wan
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How do I debug it, do I need to declare EntityBean in applicationContext.xml?

Would I need to initiate it in a main class, such as:

public static void main(String[] args) {
       // TODO Auto-generated method stub
       Sample s = new Sample();
       s.persist();
   }

Thanks,
A.W.
 
A. Wan
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is there a persistent unit or logic ?!
 
Tim Holloway
Saloon Keeper
Posts: 28319
210
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you set up Spring Data, you annotate your Entity Beans using the "@Entity" annotation on their class definition. Spring Data will automatically configure them as long as the director(ies) they live in are part of the declared annotation scan path.
 
Tim Holloway
Saloon Keeper
Posts: 28319
210
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here's how I do it for a test setup:

Some of this may be out of date, but this worked last time I used it.

My Entity bean classes are in /src/main/java/com/mousetech/app123/persistence/model, because that's what I told packagesToScan to search.

My DAOs, incidentally are in /src/main/java/com/mousetech/app123/persistence/dao. Their annotations are picked up by the following:

The component-scan looks in subdirrectories (including the dao and service dicretories).
 
A. Wan
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Tim,
 I add persistence.xml in META-INF or under WEB-INF (also in web.xml), but it keep complaining about my persistence.xml saying it couldn't find element persistence:

 <?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemalocation="https://jakarta.ee/xml/ns/persistence
https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd" version="3.0">
   <!-- Define persistence unit -->
   <persistence-unit name="my-persistence-unit">
   </persistence-unit>
</persistence>

My web app lib contains bot jakarta persistence API 3 and javax persistence API 2.2, jakarta transaction API 2, not sure what cause it?

Thanks,
A.W.
 
Tim Holloway
Saloon Keeper
Posts: 28319
210
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

A. Wan wrote:My web app lib contains bot jakarta persistence API 3 and javax persistence API 2.2, jakarta transaction API 2, not sure what cause it?



I think you can see what calls for what from the Maven command line like this:

The popular IDES have ways of showing the dependency hierarchy as well. Dependency conflicts are the "DLL Hell" of Java, so these tools are very useful.
 
When it is used for evil, then watch out! When it is used for good, then things are much nicer. Like this tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic