Error Resolving Thymeleaf Templates Files when run a jar file in Spring Boot App but runs fine locally - spring

My app works fine on local. But when I deploy to kubernetes I get this error:
Error resolving template [login], template might not exist or might not be accessible by any of the configured Template Resolvers
Controller
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(HttpServletRequest request) {
String referrer = request.getHeader("Referer");
ModelAndView modelAndView = new ModelAndView();
request.getSession().setAttribute("Referer", referrer);
modelAndView.setViewName("user/test");
return modelAndView;
}
test.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<h2>Test</h2>
</body>
</html>
WebSecurityConfig
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/**").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/reminder").permitAll()
.antMatchers("/reset").permitAll()
.antMatchers("/user/update-password").hasAnyAuthority("ADMIN", "MODERATOR", "USER")
.anyRequest().authenticated()
.and()
.formLogin().successHandler(customizeAuthenticationSuccessHandler)
.loginPage("/login").failureUrl("/login?error")
.usernameParameter("username")
.passwordParameter("password")
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling()
// .accessDeniedHandler(accessDeniedHandler)
.and()
.csrf().ignoringAntMatchers(new String[]{"/api/**"}).and();
}
/**
*
* #param web
* #throws Exception
*/
#Override
public void configure(WebSecurity web) {
web.expressionHandler(new DefaultWebSecurityExpressionHandler() {
#Override
protected SecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication, FilterInvocation fi) {
WebSecurityExpressionRoot root = (WebSecurityExpressionRoot) super.createSecurityExpressionRoot(authentication, fi);
root.setDefaultRolePrefix(""); //remove the prefix
return root;
}
}).ignoring().antMatchers(
"/resources/**",
"/static/**",
"/assets/**",
"/global_assets/**",
"/webjars/**",
"/css/**",
"/js/**",
"/img/**"
).antMatchers("/webjars/**", "/css/**", "/js/**");
}
application.properties
spring.thymeleaf.check-template-location=true
spring.thymeleaf.prefix=classpath:/templates
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
How can I solve this problem? I am using spring boot and kubernetes. It does not bring up the login page.

Related

adding a login page before swagger-ui.html using thyme leaf and spring Boot

#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.authorizeRequests()
.antMatchers("/", "/favicon.ico", "/**/*.png", "/**/*.gif", "/**/*.svg", "/**/*.jpg",/**/*.html","/**/*.css", "/**/*.js")
.permitAll()
.antMatchers("/v2/api-docs", "/configuration/ui", "/configuration/security","/webjars/**")
.permitAll().antMatchers("/swagger-resources","/swagger-resources/configuration/ui","/swagger-ui.html").hasRole("SWAG").anyRequest().authenticated()
.antMatchers("/api/all/**").permitAll().antMatchers("/api/Service/**").permitAll()
.antMatchers("/api/Service/Package/**").permitAll()
.antMatchers("api/public/customer/**").hasRole("CUSTOMER1")
.antMatchers(HttpMethod.OPTIONS).permitAll().anyRequest().authenticated().and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login?logout")
.permitAll()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.addFilterBefore(authTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider);
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER")
.and()
.withUser("manager").password("{noop}password").roles("MANAGER");
}
#Controller
public class HomeController {
#GetMapping("/")
public String root() {
return "index";
}
#GetMapping("/user")
public String userIndex() {
return "swagger-ui.html";
}
#GetMapping("/login")
public String login() {
return "login";
}
#GetMapping("/access-denied")
public String accessDenied() {
return "/error/access-denied";
}
}
so iam trying to authenticate /swagger-ui.html like a simple popup login using inmemory in order to access the api by certain users
when i do with this code i got the following output of the attached image
when i login there is no redirection for authentication
>

Ajax call after session expired not redirecting to login page - spring boot

I want to redirect to the login page if while doing an ajax call the session is expired. I'm following the instructions on this link to do that, but every time I do an ajax call with the session expired it returns the login page as part of the response instead of redirecting to the login page, this never fails and response always goes to success piece of the ajax call with readyState: 4 and status: 200 and this is giving me a jquery error because I'm expecting a list and it's returning the html code for the login page.
My code is as below:
WebSecurityConfig.java
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(URL_LOGIN, "/css/**", "/img/**").permitAll()
.antMatchers("/admin/**").hasAnyAuthority(authorizedRolesAdmin)
.antMatchers("/**").hasAnyAuthority(ArrayUtils.addAll(authorizedRolesUser, authorizedRolesAdmin))
.and()
.formLogin()
.loginPage(URL_LOGIN)
.defaultSuccessUrl("/", true)
.failureUrl(URL_LOGIN_FAILED)
.permitAll()
.and()
.logout()
.logoutSuccessUrl(URL_LOGOUT)
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage(URL_LOGIN_UNAUTHORIZED)
.authenticationEntryPoint(new AjaxAwareAuthenticationEntryPoint(URL_LOGIN))
.and()
.sessionManagement()
.maximumSessions(1)
.expiredUrl(URL_LOGOUT)
.and()
.invalidSessionUrl(URL_LOGOUT);
}
AjaxAwareAuthenticationEntryPoint.java
public class AjaxAwareAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
public AjaxAwareAuthenticationEntryPoint(String loginFormUrl) {
super(loginFormUrl);
}
#Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
String ajaxHeader = request.getHeader("X-Requested-With");
if ("XMLHttpRequest".equals(ajaxHeader)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Ajax Request Denied (Session Expired)");
} else {
super.commence(request, response, authException);
}
}
}
While debugging after session expired, I noticed that it doesn't even enter to: AjaxAwareAuthenticationEntryPoint java class commence method.
What I'm missing here?
I know, that it is probably too late for the answer, but anyway the code you've attached helped me to resolve the absolutely same issue. To be honest, I don't see any issues in your code that makes it not to enter to the AjaxAwareAuthenticationEntryPoint, only may be you have some other configs behind the scene. But anyway, let my answer be an example for everyone, who struggles with the same issue, cause for me it works fine, and returns 403 if session is expired. I am using Spring Boot v2.3.5 and this is my code:
AjaxAwareAuthenticationEntryPoint.java
public class AjaxAwareAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
public AjaxAwareAuthenticationEntryPoint(String loginFormUrl) {
super(loginFormUrl);
}
#Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
String ajaxHeader = ((HttpServletRequest) request).getHeader("X-Requested-With");
if ("XMLHttpRequest".equals(ajaxHeader)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Ajax Request Denied (Session Expired)");
} else {
super.commence(request, response, authException);
}
}
}
WebSecurityConfig.java
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private AuthenticationFailureHandler authenticationFailureHandler;
#Autowired
private AccessDeniedHandler accessDeniedHandler;
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/registration*").permitAll()
.antMatchers("/admin/**").hasAuthority("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error=true")
.defaultSuccessUrl("/admin", true)
.failureHandler(authenticationFailureHandler)
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login")
.and()
.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler)
.and()
.exceptionHandling()
.authenticationEntryPoint(new AjaxAwareAuthenticationEntryPoint("/login"));
}
}
and inside my main.js where I have some jquery ajax calls I have this:
$(document).ajaxError(function myErrorHandler(event, xhr, ajaxOptions, thrownError) {
if (xhr.status == 403) {
window.location.href ="/login";
}
});

Spring Boot 2.0.0.BUILD-SNAPSHOT redirect not working

The following code is working as expected without any issue in Spring Boot 1.5.3 but not in 2.0.0-BUILD-SNAPSHOT.
Can any one tell me how to call redirect in Spring Boot 2.0.0?
Main class:
#SpringBootApplication
public class SpringBootExampleApplication {
public static void main(String[] args) {
// TODO: Auto-generated method stub
SpringApplication.run(SpringBootExampleApplication.class, args);
}
}
Controller:
#RequestMapping(value = "/validateUser", method = RequestMethod.POST)
public String forawar(Model model) {
// Validate before authentication
return "redirect:/login";
}
WebSecurityConfigurerAdapter:
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// httpSecurity.httpBasic().and().authorizeRequests().anyRequest().authenticated().and().csrf().disable();
httpSecurity
.authorizeRequests()
.antMatchers("/", "/index", "/validateUser").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/loginError")
.defaultSuccessUrl("/dashBoardHome")
.permitAll()
.and()
.csrf().disable()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/index")
.permitAll();
}

Spring security only allowed oauth login

In my project, i just want to allow oauth login. my spring security config as follow:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login.html", "/oauth/**", "/sign**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().disable()
.httpBasic().disable()[enter image description here][1]
.exceptionHandling().accessDeniedPage("/login.html")
.and()
.apply(new SpringSocialConfigurer());
}
The problem is the access denied page not working. I want to get login.html content as follow:
login.html
in fact i got 403 page as follow:
403
How to solve this problem?
I solve this problem, the code as follow:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login.html", "/oauth/**", "/sign**").permitAll()
.anyRequest()
.authenticated()
.and()
.exceptionHandling()
.defaultAuthenticationEntryPointFor(new HttpForbiddenEntryPoint(), AnyRequestMatcher.INSTANCE)
.and()
.logout()
.logoutUrl("/logout.html")
.clearAuthentication(true)
.logoutSuccessUrl("/login.html")
.and()
.apply(new SpringSocialConfigurer());
}
The entry point:
public class HttpForbiddenEntryPoint implements AuthenticationEntryPoint {
private String redirect_url = "/login.html";
#Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.sendRedirect(redirect_url);
}
public String getRedirect_url() {
return redirect_url;
}
public void setRedirect_url(String redirect_url) {
this.redirect_url = redirect_url;
}
}

Spring Security Thymleaf static resources don't load

I'm using SpringMVC with Thymleaf and Spring-Security.
I want to load a page using Thymleaf template and I can load my static resources.
I want to load for example a picture located in : static/img/theme/logo.png from template.html
Here is what I have : result
template.html :
<body>
<div layout:fragment="content">
img src="../static/img/theme/logo.png" alt="Logo">
<h1>Hello</h1>
</div>
</body>
MvcConfig.java
#Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/index").setViewName("index");
registry.addViewController("/template").setViewName("template");
registry.addViewController("/layout").setViewName("layout");
registry.addViewController("/login").setViewName("login");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
WebSecurityConfig :
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//List of all free pages
private static final String[] pagesFree = {
"/home",
"/template",
"/layout",
//Thymleaf directory
"/css/**",
"/js/**",
"/img/**",
"/fonts/**",
"/ico/**",
"/twitter/**",
"/"
};
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(pagesFree).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("u").password("u").roles("USER");
}
}
Source Code tree
In your security configuration you would declare something like this:
/** Public URLs. */
private static final String[] PUBLIC_MATCHERS = {
"/webjars/**",
"/css/**",
"/js/**",
"/images/**",
"/"
};
Then something like this:
#Override
protected void configure(HttpSecurity http) throws Exception {
List<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
if (activeProfiles.contains("dev")) {
http.csrf().disable();
http.headers().frameOptions().disable();
}
http
.authorizeRequests()
.antMatchers(PUBLIC_MATCHERS).permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").defaultSuccessUrl("/payload")
.failureUrl("/login?error").permitAll()
.and()
.logout().permitAll();
}
And in your Thymeleaf template you'd declare something like this:
<img class="featurette-image pull-left" th:src="#{/images/browser-icon-firefox.png}" />
A working copy of your project can be found here.

Resources