TemplateInputeException while trying to serve frontend on my Spring Boot App - spring

Controller Class:
#Controller
public class FirstRestController {
#GetMapping("/")
public String budget() {
return "budget";
}
Security Config:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.antMatchers("/api/auth/**").permitAll()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
package structure image
I try to build a frontend for my web application. I'm using the Controller to serve my html Pages. But they are not rendering proberly. I always get a 404 not found Exception.
Now I tried it with Thymeleaf. But i always catch the TemplateInputeException. Thymeleaf is configured in my Pom.xml. I don't know where to debug this. I can't find a typo. So I think it's a bigger configuration I missed. Do I have to configure my resource folder somewhere? How can I server my html frontend pages in the app?
I tried to reinstall Thymeleaf. I already restarted IntelliJ. It tried to use the RequestMapping annotation. I renamed the static folder to public. I tried different paths.

Related

How to secure only swagger UI page " swagger-ui/index.html#/ " and all other API end points should not be authenticated in Spring boot

I have a requirement where I just need to secure the Swagger UI page. All other endpoints I have written in the application should not be authenticated.
For this, I am using the Spring security starter. I have the Security Config for Spring boot in place. I am trying to authenticate ("/v2/api-docs") because this is where we see all the endpoints in Swagger UI. And also I am trying to permit ("/calculator-controller/callCalculatorServiceUsingPOST") which I see in browser URL when I click on my end point Try it now button and also permitting ("/calculate") which is in my controller. To be safer, I have tried to permit all possible combinations, but no luck.
What Am I missing ???
#Configuration #EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.authorizeRequests()
.antMatchers("/v2/api-docs").authenticated()
.antMatchers("/calculator-
controller/callCalculatorServiceUsingPOST",
"calculator-controller/**", "/calculate")
.permitAll()
.and()
.httpBasic();
}
}

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
}

Spring security redirect to static resources after authentication

Good morning,
I am writing an application using Spring security (latest version) and Spring MVC (latest version).
After securying everything was ok, the form and the controller, together with Spring security configuration worked well and the login was always successful.
Then I added a custom css and some images to display a better graphic, here it came the problem:
everytime I login I am first redirected to the login.css file rather than the homepage, although the login is successful I first see a blank page with the url of the css.
Spring Security configuration
#Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
//configure security for pages
.antMatchers(new String[]{"/login", "/accessDenied"}).permitAll()
.antMatchers("/**").access("hasAnyRole('admin', 'operatore')")
.anyRequest().authenticated()
//creates login form
.and().formLogin().loginPage("/login").loginProcessingUrl("/login")
.defaultSuccessUrl("/home").failureUrl("/accessDenied")
.usernameParameter("id_utente").passwordParameter("password")
//catches exceptions http 403 response
.and().exceptionHandling().accessDeniedPage("/accessDenied");
http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}
Static resources are under the path /static/css and /static/images.
I read this problem comes from the fact that Spring security redirects you to the last requested url after login, as to resolve the issue I tried using
#Override
public void configure(WebSecurity web)
{
web.ignoring().antMatchers("/static/**");
}
but it didn't work.
Are there any way to solve this problem?
EDIT
I already tried using
#Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
//configure security for pages
.antMatchers("/static/**").permitAll()
.antMatchers(new String[]{"/login", "/accessDenied"}).permitAll()
.antMatchers("/**").access("hasAnyRole('admin', 'operatore')")
.anyRequest().authenticated()
//creates login form
.and().formLogin().loginPage("/login").loginProcessingUrl("/login")
.defaultSuccessUrl("/home").failureUrl("/accessDenied")
.usernameParameter("id_utente").passwordParameter("password")
//catches exceptions http 403 response
.and().exceptionHandling().accessDeniedPage("/accessDenied");
http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}
But I am anyhow redirected after a successufl login to a 404 page with url "http://localhost:8080/static/css/login.css". In the login page the static resources are corretcly served as the style is how I expect it to be.
EDIT #2
I Edited as Eleftheria Stein-Kousathana said, but it keeps redirecting to the css (showing the code inside this time) instead of the homepage.
The project structure is:
Resource handler is added this way:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
and updated configuration is:
#Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
//configure security for pages
.antMatchers("/css/**", "/images/**").permitAll()
.antMatchers(new String[]{"/login", "/accessDenied"}).permitAll()
.antMatchers("/**").access("hasAnyRole('admin', 'operatore')")
.anyRequest().authenticated()
//creates login form
.and().formLogin().loginPage("/login").loginProcessingUrl("/login")
.defaultSuccessUrl("/home").failureUrl("/accessDenied")
.usernameParameter("id_utente").passwordParameter("password")
//catches exceptions http 403 response
.and().exceptionHandling().accessDeniedPage("/accessDenied");
http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}
Inside login page the css is linked this way:
<link rel="stylesheet" href="<c:url value="/static/css/login.css" />">
With the new antMatchers the result is not a 404 but the code inside the css. By the way, the linked css is not served anymore as style is not displayed correctly if I use the new configuration and "/static/css/login.css" or "/css/login.css", none of the two link work.
Since static/css and static/images are under the static directory, they will be served at /css and /images respectively.
You can permit all requests to those resources in your HTTP security configuration.
http.authorizeRequests()
.antMatchers("/css/**", "/images/**").permitAll()
// ...

How to redirect using spring security session time out?

I'm using spring boot 2.2.0.M2 spring security this package version is 5.2.0, my project fronted is done in vuejs 2.6.10
What I want to archive seems very simple, when spring security session is time out i want to redirect ( force browser ) to go to URL http://localhost:8080/
What I was trying till now is:
I have created configuration class:
#Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter
{
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.formLogin()
.loginPage("/")
.defaultSuccessUrl("/admin#/timetable")
.permitAll()
.and().logout()
.logoutSuccessUrl("/")
.permitAll()
.and()
.sessionManagement()
.maximumSessions(1)
.expiredUrl("/")
.expiredSessionStrategy(event -> event.getResponse().sendRedirect("/"));
// this supoose to work right?
}
}
and in my application.properties I have added for testing purpouses:
# Server
server.servlet.session.timeout=1m
And after one minute nothing happens.
So I thought that maybe something is wrong and session is not timeout so I've run my application in debug mode and I putted break point in
package org.springframework.security.web.session;
...
public class HttpSessionEventPublisher implements HttpSessionListener
{
...
public void sessionDestroyed(HttpSessionEvent event) {
//my break point
}
}
And after one minute I'm in, debugger stopped in sessionDestroyed method so session is no longer exist.
About my UI, I'm using vuejs embedded in thyme leaf page:
So my question is do You know how to force browser to reload my application or redirect to http://localhost:8080/ when spring security session is expired (timeout) ?

Spring Boot+Thymeleaf doesn't resolve login.html

I have basically copied the tutorial to use Spring Web Security with Spring Boot and Thymeleaf. https://spring.io/guides/gs/securing-web/
For configuration:
#Configuration
public class WebConfig implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.addViewController("/").setViewName("home");
}}
For security in public class WebSec extends WebSecurityConfigurerAdapter:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.antMatchers("/users*").hasRole("ADMIN")
.antMatchers("/users/*").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.logout().permitAll();
}
All html files are under
/src/main/resources/templates
Now, home.html is found nicely. However whenever anything requires the login page, the login.html in the same folder is not found and the error is:
Error resolving template "login", template might not exist or might not be accessible by any of the configured Template Resolvers
I'm not sure how to proceed from here.
Solution: Do not call your template files the same as your routes. The problem can be solved by naming the file login_template.html or something. Or even better, change the line:
registry.addViewController("/login").setViewName("login");
to just
registry.addViewController("/login");
I found a hint to this behaviour in the javadocs for ViewControllerRegistration.setViewName.

Resources