Thymeleaf downloads login blank file instead navigate to login.html (Springboot) - spring-boot

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.

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 redirecting custom login page to itself - Too Many Redirects

I'm currently developing a custom login-page for my Spring Boot Application but I just can't get it to work. Using the default one works fine but as soon as I try to use my custom file, it just repeatedly redirects me until my Browser give up.
Other posts suggest permitting access to the login-path to erveryone but this also doesn't seem to work.
Here is my code:
WebSecurityConfig
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
And Controller for login-page
#Controller
public class WebController {
#GetMapping("/login")
public String login () {
return "login";
}
}
Any ideas what I'm missing?
You are probably using a lot of CSS and JS file link links, according to your code Spring Boot must first authenticate all the links, which is why it redirects to your login page many times.
add following code to bypass security authentication of resource link
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers("/bower_components/**", "/dist/**", "/plugins/**"); //write your resource directory name
}

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 Security - Authentication issue

I am working on a web application & have opted to use spring Security. The idea is for the user to be authenticated to see the Home Page, if the user is not authenticated they are redirected to the login page. This login page also displays a link to a registration form, This part is working correctly.
However, I have encountered an issue when attempting to allow users to sign up via the registration link. The link to the registration form cannot be accessed if the user if not authenticated ("showRegistrationForm")
Can anyone provide insight to why this is occuring? I have Included the code snippet from my SecurityConfig below
#Override
protected void configure(HttpSecurity http) throws Exception {
//Restrict Access based on the Intercepted Servlet Request
http.authorizeRequests()
.antMatchers("/resources/**", "/register").permitAll()
.anyRequest().authenticated()
.antMatchers("/").hasRole("EMPLOYEE")
.antMatchers("/showForm/**").hasAnyRole("EMPLOYEE","MANAGER", "ADMIN")
.antMatchers("/save/**").hasAnyRole("MANAGER", "ADMIN")
.antMatchers("/delete/**").hasRole("ADMIN")
.and()
.formLogin()
// Show the custom form created for the below request mappings
.loginPage("/showSonyaLoginPage")
.loginProcessingUrl("/authenticateTheUser")
// No need to be logged in to see the login page
.permitAll()
.and()
// No need to be logged in to see the logout button.
.logout().permitAll()
.and()
.exceptionHandling().accessDeniedPage("/access-denied");
}
Change the code like below:
#Override
protected void configure(HttpSecurity http) throws Exception {
// Restrict Access based on the Intercepted Servlet Request
http.authorizeRequests()
.antMatchers("/showRegistrationForm/").permitAll()
.anyRequest().authenticated()
.antMatchers("/").hasRole("EMPLOYEE")
.antMatchers("/resources/").permitAll()
.antMatchers("/showForm/**").hasAnyRole("EMPLOYEE","MANAGER", "ADMIN")
.antMatchers("/save/**").hasAnyRole("MANAGER", "ADMIN")
.antMatchers("/delete/**").hasRole("ADMIN")
.and()
.formLogin()
// Show the custom form created for the below request mappings
.loginPage("/showSonyaLoginPage")
.loginProcessingUrl("/authenticateTheUser")
// No need to be logged in to see the login page
.permitAll()
.and()
// No need to be logged in to see the logout button.
.logout().permitAll()
.and()
.exceptionHandling().accessDeniedPage("/access-denied");
}
Moved down the below code:
anyRequest().authenticated()

Spring Boot 2 Security downloading font file upon login

I've setup a spring boot 2 application with a login form, however, when you login, instead of redirecting to /admin like it's supposed to, it downloads a font file referenced by the stylesheet via an #import.
Here is my security setup;
#Configuration
#EnableWebSecurity()
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
UserService userService;
#Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
// These pages don't require the user to be logged in
http.authorizeRequests()
.antMatchers("/", "/login", "/logout", "/report/**").permitAll()
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
.anyRequest().authenticated();
// When the user has logged in as XX.
// But access a page that requires role YY,
// AccessDeniedException will be thrown.
http.authorizeRequests().and().exceptionHandling().accessDeniedPage("/403");
// Config for Login Form
http.authorizeRequests().and().formLogin()//
// Submit URL of login page.
.loginProcessingUrl("/j_spring_security_check") // Submit URL
.loginPage("/login")//
.defaultSuccessUrl("/admin")//
.failureUrl("/login?error=true")//
.usernameParameter("username")//
.passwordParameter("password")
// Config for Logout Page
.and().logout().logoutUrl("/logout").logoutSuccessUrl("/login?logout=true");
}
}
Where am I going wrong? From what I can see, I'm enabling access to Spring resources that are stored in the static folder.
I figured this one out, I read the code that allows access to resources and noticed it said 'atCommonLocations', and guess this adds access to folders such as css, js, img, images etc. I had fonts in a folder labelled webfonts, so I updated my security configuration;
http.authorizeRequests()
.antMatchers("/", "/login", "/logout", "/report/**", "/webfonts/**").permitAll()
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
.anyRequest().authenticated();

Resources