url was not normalized error when using intellij but not when using STS - intellij-idea

The developed website works fine on remote server and local machine (when using STS IDE) , recently I started use Intellij IDEA (I created a duplicate of the website code with no any changes ), I started getting the URL was not normalized error.
Does intellij handles Spring security somehow differently than STS ? or what could be the cause?
I don't want use custom httpfirewal .
#EnableGlobalMethodSecurity(prePostEnabled=true)
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider())
.jdbcAuthentication()
.usersByUsernameQuery(usersQuery)
.authoritiesByUsernameQuery(rolesQuery)
.dataSource(dataSource);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// URLs matching for access rights
http.authorizeRequests()
.antMatchers( "/", "/contact","/register").permitAll()
.antMatchers("/accounts").hasAnyAuthority("SUPER_USER","ADMIN_USER")
.anyRequest().authenticated()
.and()
// form login
.csrf().disable().formLogin()
.loginPage("/index")
.failureUrl("/index?error=true")
.defaultSuccessUrl("/user")
.usernameParameter("email")
.passwordParameter("password")
.and()
// logout
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").and()
.exceptionHandling()
.accessDeniedPage("/access-denied");
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
}
and this is from the properties :
# Spring MVC view prefix.
spring.mvc.view.prefix=/templates/
# Spring MVC view suffix.
spring.mvc.view.suffix=.html
the error is :
org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL was not normalized.
P.S: I'm using JDK8 ,Spring Boot 2,Spring Security ,thymeleaf,intellij U 2019.2

org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL was not normalized.
Which IDE to use should not have any differences for running the same source codes on the embeddable server configured by springboot. This error happens when the HTTP requests that send to server is not normalised which the URL contains character sequences like ./, /../ , // or /. So I doubt that it is due to you are using different URL to browse the app. For example, you are accidentally adding a '/' in the URL such as http://127.0.0.1:8080/app//index.html
You can change to use a less secure HttpFirewall to avoid such checking by :
#Override
public void configure(WebSecurity web) throws Exception {
web.httpFirewall(new DefaultHttpFirewall());
//another configuration .....
}
P.S. Though it is called DefaultHttpFirewall , it is not the default HttpFirewall used by Spring Security since 4.2.4 which is less secured than the actual default StrictHttpFirewall

Related

Spring Security With Custom Login Flow

I am trying to add spring with spring security in an existing Struts based application. It is a Partial migration. All the new development should happen in Spring.
So what I want is,
User access a Secured URL
If the user is not authenticated Spring Should redirect to a specific URL (This will be a Struts URL)
After Old Struts Module does its work of authenticating the user, It saves an Object in HTTP Session which depicts the authenticated User.
Spring Should get this Object from Session and Authenticated the User.
Redirect the User to the requested Secured URL
I have tried to used formlogin().loginpage(<Struts_URL>). Also in the Struts code after authentication, I have updated the Spring's SecurityContext.
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
#Override
protected void configure(HttpSecurity pHttp) throws Exception
{
pHttp.antMatcher("/**").authorizeRequests()
.anyRequest().authenticated()
.and().formLogin().loginPage("/<Struts_Login_Entry>.do");
}
...
#Override
public void configure(WebSecurity pWeb) throws Exception
{
// All the Strtus URL has .do suffix so excluding it
pWeb.ignoring().antMatchers("/*.do", "/portal/**");
}
}
After Authentication in Struts
...
MyUserDetails lUserDetails = new MyUserDetails(pUserName, pRole);
Authentication auth = new UsernamePasswordAuthenticationToken(lUserDetails, null, lUserDetails.getAuthorities());
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(auth);
...
The User is getting redirected to Struts page when he accesses any Spring URL But this happens even if the user is authenticated.
I am not so familiar with Spring Security, any suggestion or help?

Bluemix force HTTPS on Spring Boot application

I have a Spring Boot application that is pushed on Bluemix as a CF app.
It works efficiently with the http protocol. However if i tried to force https, I get a 502 error.
I have:
#Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.requiresChannel().anyRequest().requiresSecure();
//http.csrf().disable();
}
}
And I have an application.properties file with those entries:
server.ssl.key-store = classpath:**.jks
server.ssl.key-store-password = *******
server.ssl.key-password = ******
server.tomcat.remote_ip_header=x-forwarded-for
server.tomcat.protocol_header=x-forwarded-proto
I am aware that Bluemix performs SSL termination; in fact it sets correctly x-forwarded-proto and x-forwarded-for. I looked for solutions like 1 and 2 but without any luck.
I then tried with the following solution, as suggested in this article but a received a redirect loop insted:
#Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory(){
return new TomcatEmbeddedServletContainerFactory() {
#Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
}
What did I miss in my approach? Many thanks for any tips/suggestions you may provide me
For the sake of the community, it would be good to see Rob's comment accepted as the answer. Rob, feel free to add your own answer if you would rather see that accepted instead.
Tomcat is not detecting the x-forwarded headers as being a trusted proxy. Try setting server.tomcat.internal-proxies=.* and logging.level.org.apache.catalina.valves=DEBUG

Enabling Spring OAuth2 ResourceServer disables UsernamePasswordAuthenticationFilter

I have the following in my WebSecurityConfigurerAdaptor:
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login.jsp").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling()
.accessDeniedPage("/login.jsp?authorization_error=true")
.and()
.csrf()
.disable()
.formLogin()
.loginProcessingUrl("/login")
.loginPage("/login.jsp")
.failureUrl("/login.jsp?authentication_error=true");
}
I have an OAuth2 client (written in PHP) and can be redirected to /login before getting a valid access token.
Then I try to enable my ResourceServerConfigurerAdapter:
#Configuration
#EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
#Override
public void configure(ResourceServerSecurityConfigurer resources)
throws Exception {
resources.resourceId("myResource").stateless(false);
}
#Override
public void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers()
.antMatchers("/me")
.and()
.authorizeRequests()
.antMatchers("/me").access("#oauth2.hasScope('email')");
}
}
Once the ResourceServer is enabled, the UsernamePasswordAuthenticationFilter is never invoked, and going to /login returns the HTTP 404 error.
I read the sample Spring OAuth2 application sparklr2 and tonr2 many times but I cannot figure out what is wrong with my code.
It is a very difficult bug to track down.
My code initially used Spring Security version 4.0.2.RELEASE and Spring version 4.2.2.RELEASE. Once I changed my maven pom.xml to use Spring Security version 3.2.8.RELEASE and Spring version 4.1.8.RELEASE, my code works.
It may have to do with the following bug:
resource server security custom request matching ignored

How to get past the Authentication Required Spring-boot Security

I have put in the password which is "root" and it keeps popping back up. How can I suppress this or get rid of it. I am using spring boot and spring security.
application.properties
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springbootpractice
spring.datasource.username=root
spring.jpa.database = MYSQL
spring.jpa.show-sql = true
# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: update
entitymanager.packagesToScan: /
I am using intellij 14 if that matters.
----Update 1-----
#Configuration
#EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/index").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/index")
.permitAll()
.and()
.logout()
.permitAll();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/index").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/index")
.permitAll()
.and()
.logout()
.permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
This class has to be in a parent package of all other packages:
WebSecurityConfig.
Also in application.properties set:
security.basic.enabled=false
ACV's answer is probably the easiest way to turn off the authentication completely by adding security.basic.enabled=false to the application.properties file which is usually located under src/main/resources folder.
or you just type in the password :)
1. use default password
When you run your spring application, there is usually a whole bunch of logging printed, which people usually don't read. The password is actually generated and printed to the screen at the startup. and the username is simply user. If you are testing using a browser and it probably only need you enter it once and caches it, so once for all, you should be securely logged in without authenticating every time.
(however, every time you restart your app, it will generate a new password)
2. customize your password
Add the following properties to your application.properties if you want to customize your username and password:
security.user.name=myuser
security.user.password=mypassword
And here is how it looks like with your own username and password
Reference:
Spring Boot Features - Security
Monitoring and Management over HTTP
You can bypass this spring boot security mechanism. See an example below for this:
#SpringBootApplication
#EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class})
public class SampleSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(SampleSpringBootApplication.class, args);
}
}
When Spring Security is in the classpath, Spring Boot by default secures all your pages with Basic authentication. That's why you are being asked for userid and password.
You will need to configure the security. To do so, commonly people would extend a WebSecurityConfigurerAdapter, like this:
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
...
Refer this Spring Security guide for more details.
Here was the issues
(1) .loginPage("/index") was saying my login page was at index, however I just wanted to use spring's default login page.
(2) had to to move the security package inside the demo package (the main package). Thanks to #Sanjay for suggesting that. I tried to use #ComponantScan but it could not get it to work.

How secure Rest-API by token

i use spring data rest 2.1 and would like secure my rest api, what is the best way to secure the api by token. I would have an process like the following steps. Is it also possible to change the base url from / to /api , but my controllers like 'home' would also display the jsp side from /home but not from /api/..
User go to login site
User login and get an token from server
User go to dashboard site and js do ajax call and set HTTP-Header Field 'X_AUTH_TOKEN' with token
You could configure base URI for you API using RepositoryRestConfiguration. Something like this:
#Configuration
public static class RepositoryConfig extends
RepositoryRestMvcConfiguration {
#Override
protected void configureRepositoryRestConfiguration(
RepositoryRestConfiguration config) {
try {
config.setBaseUri(new URI("/api"));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
You could add security using Spring-Security or if you like a simple custom solution use Spring Interceptor