HTTPS Secured works only on home page not the next page - spring-boot

I am deploying a spring boot webapplication in AWS EC2 instance on port 80 and the home page is displayed as Secured When I click on the link like user login or admin login the browser shows it as Not Secured.What should I do to make my whole application secured.
Below is my code which I am using from a site,I am new to spring security,Please help.
Home.html
<div class="starter-template">
<h1>Spring Boot Web Thymeleaf + Spring Security</h1>
<h2>1. Visit <a th:href="#{/admin}">Admin page (Spring Security protected, Need Admin Role)</a></h2>
<h2>2. Visit <a th:href="#{/user}">User page (Spring Security protected, Need User Role)</a></h2>
<h2>3. Visit <a th:href="#{/about}">Normal page</a></h2>
</div>
#Configuration
// http://docs.spring.io/spring-boot/docs/current/reference/html/howto-security.html
// Switch off the Spring Boot security configuration
//#EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private AccessDeniedHandler accessDeniedHandler;
// roles admin allow to access /admin/**
// roles user allow to access /user/**
// custom 403 access denied handler
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/home", "/about").permitAll()
.antMatchers("/admin/**").hasAnyRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER")
.and()
.withUser("admin").password("password").roles("ADMIN");
}
}
What am I doing wrong?Is the issue in the code or my AWS Configuration

Solved the issue by setting application.properties to the below
server.use-forward-headers=true

Related

Simple Spring Security Authentication [duplicate]

Can't navigate from index.html to any other page, when clicking the button to navigate a blank login file is downloaded. I think this problem is linked to security file because at the beginning I didn't had it but after adding it many things have been broken.
This is the html code :
Log In
And this is security file :
#Configuration
#EnableWebSecurity
public class Security extends WebSecurityConfigurerAdapter{
// https://spring.io/guides/gs/securing-web/
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/","/register","/login","/css/**", "/js/**", "/images/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
#Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder(11);
}
}
There is a login.html file in templates.
As soon as you override the default login page by specifying .loginPage(some_string), then the Spring Security default login configuration will be deactivated.
It does not matter what the value of some_string is, it is considered a custom login page even if the value is "/login".
In other words, with your current configuration, when you are overriding the default login page, Spring Security expects you to create the mapping for your custom login endpoint.
As Ratul Sharker said in the comment above, you need to add a #GetMapping("/login") that returns your custom login page.

Spring security how to allow root url without intefering with security 'below' the root

I have REST services and static pages, both delivered by my Spring Boot application.
The application action is to be reached under /myapp, while under /myapp/api there are services that are protected by a filter.
The filter expects a cookie.
#Override
protected void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/**")
.permitAll()
.and()
.addFilter(new CookieFilter(...));
}
The unprotected pages in the 'root-context (/myapp) have no cookie.
How can I configure that the static pages are 'ignored' by Spring security? While the REST endpoints below the static pages are checked by security?
When I try to configure the static pages for 'exclusion' via Web Security, all REST endpoints under /myapp/api are ignored as well
#Override
public void configure(final WebSecurity web) {
web.ignoring()
.antMatchers("/");
}
If I configure a permitAll():
#Override
protected void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/").permitAll();
http.authorizeRequests()
.antMatchers("/api/**")
.permitAll()
.and()
.addFilter(new CookieFilter(...));
}
Spring security complains that the static pages can not be checked by my security filter, so the authorization is performed.
This will make anything under /api require authentication and let everything else through.
http.authorizeRequests()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and()
.addFilter(new CookieFilter(...));

Login page needs to be prompted if user is not authorized to access specific controller or URL in spring security. How to achieve that?

I'm using spring-boot, spring-security and JSP. If I click on a button it should go to a controller if user is logged in. Otherwise, it should first ask user to login and then get back to that page. In short, user should see the page if he is logged in. How can I achieve this?
I think filters/antmatchers might be used but I am wondering how the user will get back to that particular page/controller after logging in?
Try using something like this to allow users access to certain pages and then set the default success url accordingly. You can have a home page as I use here represented by "/" and once a user logs in they are redirected to your /welcome page.
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
// Public access to login, landing, and error pages
http.authorizeRequests().antMatchers("/", "/login", "/errorpage").permitAll();
// Static resource permissions
http.authorizeRequests()
.antMatchers("/css/**", "/fonts/**", "/images/**", "/webfonts/**", "/js/**", "/webjars/**", "/messages/**")
.permitAll();
// Login specifications
http.formLogin().loginPage("/login").defaultSuccessUrl("/welcome", true);
// Logout specifications
http
.logout()
.deleteCookies("remove")
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/")
.permitAll();
}
}
Inside WebSecurityConfigurerAdapter implementation, you need to inform a formLogin and specify the loginPage.
That's just enough to Spring to use the endpoint /login this way.
If you try to access a page without logged, for example /profile, you will be redirected to /login, and after logged, you'll be redirected to /profile
And in this example, you have 3 pages accessible without authentication / ,/homeand/info`
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
...
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home", "/info" ).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
...
}

Spring Boot Security - Multiple configurations

I'm working (and struggling a little bit) on an example using spring-boot with spring security.
My system is using a web app and also provide an REST-API, so i would like to have form based security (web) and basic auth (resp api).
As the spring documentation recommend (https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity), I need to create a multi http web security configuration.
The main code works, but if I use Postman for the test of my RestApi following use-case does not work.
All GET-requests to /restapi/ working without authentication (statuscode 200)
All POST-requests to /restapi/ without the BASIC Auth Header are working (statuscode 401)
All POST-requests to /restapi/ with a correct BASIC Auth Header are work (statuscode 200)
BUT all requests with a wrong BASIC Auth header (f.e. user1/1234567) are returning the HTML-Loginpage defined in the first WebSecurityConfigurerAdapter (FormWebSecurityConfigurerAdapter)
Does anyone has an idea - what is wrong with my configuration?
#EnableWebSecurity
public class MultiHttpSecurityConfig {
#Autowired
private static RestAuthenticationAccessDeniedHandler restAccessDeniedHandler;
#Autowired
public void configureAuth(AuthenticationManagerBuilder auth) throws Exception{
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}12345678").roles("ADMIN").and()
.withUser("user").password("{noop}12345678").roles("USER");
}
#Configuration
#Order(1)
public static class RestWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/restapi/**")
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/restapi/**").permitAll()
.and()
.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic()
.and()
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(UNAUTHORIZED))
.and()
.exceptionHandling().accessDeniedHandler(restAccessDeniedHandler) ;
}
}
/*
Ensures that any request to our application requires the user to be authenticated (execpt home page)
Requests matched against "/css/**", "/img/**", "/js/**", "/index.html", "/" are fully accessible
Allows users to authenticate with HTTP Form Based authentication
Configure logout with redirect to homepage
*/
#Configuration
public static class FormWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/css/**", "/img/**", "/js/**", "/index.html", "/").permitAll()
.and()
.authorizeRequests().anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/index.html")
.permitAll();
}
}
}
I know it is a question from some time ago but I still want to share the answer for people who are struggling with this issue.
After a lot of searching I found out that the /error endpoint in spring boot 2.x is now secured by default. What I mean to say is in the past the /error was a endpoint what had no security at all (or didn't exist). The solution to this issue is quite straight forward.
antMatchers('/error').permitAll()
within your web security adapter configuration(s).
What happens if you don't do this, the security will check the endpoint against your configuration and if it cannot find this endpoint (/error) it will redirect to the standard login form, hence the 302.

Logout doesn't work with Spring Boot and Spring Security

This is my code using Spring Boot and Spring Security. The problem is when I used to logout (using Thyemleaf) the logout doesn't work for me.
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
#Autowired
private DataSource dataSource;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery("select username as principal, password as credentials,active from users where username=?")
.authoritiesByUsernameQuery("select username as principal,roles as role from users_roles where username=?")
.rolePrefix("ROLE_")
.passwordEncoder(new Md5PasswordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/login");
http
.authorizeRequests()
.antMatchers("/index1").permitAll();
http
.authorizeRequests()
.antMatchers("/user").hasRole("USER")
.and()
.logout();
http
.authorizeRequests()
.antMatchers("/adpage").hasRole("ADMIN");
http
.exceptionHandling().accessDeniedPage("/403");
http
.logout().permitAll();
}
}
Link using Thyemleaf:
<li><a th:href="#{/login?logout}">logout</a></li>
Try doing something like this.
<form th:action="#{/logout}" method="post">
<input type="submit" value="Log out"/>
</form>
Spring security logout Url is POST only. You can support Non-POST logout by changing your Java Configuration
protected void configure(HttpSecurity http) throws Exception {
http
// ...
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}
this way you can logout user using GET request
<li><a th:href="#{/logout}">logout</a></li>
Try the following instead:
http
.formLogin()
.loginPage("/login")
.failureUrl("/login?login_error=true")
.loginProcessingUrl("/j_spring_security_check") //if needed
.and()
.authorizeRequests()
.antMatchers("/index1").permitAll()
.antMatchers("/user").hasRole("USER")
.antMatchers("/adpage").hasRole("ADMIN")
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.logout()
.logoutSuccessUrl("/index") //or whatever page you want
.logoutUrl("/logout") //thinking this is what you need
.permitAll();
And your link would be:
<li><a th:href="#{/logout}">logout</a></li>

Resources