Spring Boot permitAll not working in WebSecurityConfigurerAdapter - java

When I POST to /api/v1/auth/register, I get a 403 response generated by the configured accessDeniedHandler. However, I'm expecting this request to be permitted as it's covered by permitAll() and precedes anyRequest().authenticated().
Requests such as GET /api/v1/reference/countries work just fine. Also, my integration tests that hit these /api/v1/auth/** endpoints also work, which suggests something to do with CORS, although the preflight request is 200.
Any idea what's wrong with this security configuration?
#Configuration
#EnableGlobalMethodSecurity(
prePostEnabled = true,
securedEnabled = true,
jsr250Enabled = true
)
#Order(1)
#RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsServiceImpl userDetailsService;
private final Config config;
private final ObjectMapper objectMapper;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.authorizeRequests()
.antMatchers(
"/api/v1/auth/register",
"/api/v1/auth/register/check",
"/api/v1/auth/register/activate",
"/api/v1/auth/password/update",
"/api/v1/auth/recover",
"/api/v1/auth/recover/check",
"/api/v1/auth/recover/reset",
"/api/v1/csrf-token",
"/api/v1/reference/**"
)
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.successHandler((request, response, authentication) -> {
response.getWriter().append("OK");
response.setStatus(HttpServletResponse.SC_OK);
})
.failureHandler((request, response, exception) -> {
response.getWriter().append("Invalid credentials or inactive account");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
})
.loginProcessingUrl("/api/v1/auth/login")
.permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/api/v1/auth/logout", "POST"))
.permitAll()
.and()
.exceptionHandling()
.accessDeniedHandler((request, response, accessDeniedException) -> {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
objectMapper.writeValue(
response.getWriter(),
ErrorResponseBody
.builder()
.code(ErrorType.ACCESS_DENIED)
.status(HttpServletResponse.SC_FORBIDDEN)
.message("Access denied")
.build()
);
})
.authenticationEntryPoint((request, response, authException) -> {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
objectMapper.writeValue(
response.getWriter(),
ErrorResponseBody
.builder()
.code(ErrorType.LOGIN_REQUIRED)
.status(HttpServletResponse.SC_UNAUTHORIZED)
.message("You are not authorized to access this resource")
.build()
);
})
.and()
.userDetailsService(userDetailsService);
if (config.isCsrfDisabled()) {
http
.csrf()
.disable();
}
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public CorsConfigurationSource corsConfigurationSource() {
final var configuration = new CorsConfiguration();
configuration.setAllowCredentials(true);
configuration.setAllowedOrigins(config.getAllowedOrigins());
configuration.setAllowedMethods(asList("GET", "POST", "PUT", "PATCH", "DELETE"));
configuration.setAllowedHeaders(Arrays.asList(HttpHeaders.AUTHORIZATION, HttpHeaders.CACHE_CONTROL, HttpHeaders.CONTENT_TYPE, HttpHeaders.ACCEPT));
final var source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", configuration);
return source;
}
}
Here's my CORS config:
#Configuration
#RequiredArgsConstructor(onConstructor = #__(#Autowired))
public class WebConfig {
private final Config config;
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
#Override
public void addCorsMappings(CorsRegistry registry) {
final var allowedOrigins = Optional
.ofNullable(config.getAllowedOrigins())
.map(origins -> origins.toArray(new String[]{}))
.orElse(new String[]{});
System.out.println("Enabling CORS for the following origins:" + Arrays.asList(allowedOrigins).toString());
registry
.addMapping("/api/**")
.allowedOrigins(allowedOrigins)
.allowCredentials(true)
.allowedMethods("*")
.allowedHeaders("*");
}
};
}
}
I'm invoking these endpoints from http://localhost:3000, which is one of the items returned by config.getAllowedOrigins().
Here's the Spring Security debug logging from the request:
2020-11-24 06:51:16.110 INFO 1 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-11-24 06:51:16.112 INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-11-24 06:51:16.158 INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 44 ms
2020-11-24 06:51:16.193 DEBUG 1 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : /api/v1/auth/register at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2020-11-24 06:51:16.200 DEBUG 1 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : /api/v1/auth/register at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2020-11-24 06:51:16.205 DEBUG 1 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
2020-11-24 06:51:16.206 DEBUG 1 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
2020-11-24 06:51:16.214 DEBUG 1 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : /api/v1/auth/register at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2020-11-24 06:51:16.217 DEBUG 1 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : /api/v1/auth/register at position 4 of 13 in additional filter chain; firing Filter: 'CorsFilter'
2020-11-24 06:51:16.286 DEBUG 1 --- [nio-8080-exec-1] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#461bbc94
2020-11-24 06:51:16.290 DEBUG 1 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2020-11-24 06:51:16.299 DEBUG 1 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2020-11-24 06:51:16.483 DEBUG 1 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /api/v1/auth/register at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2020-11-24 06:51:16.485 DEBUG 1 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /api/v1/auth/register at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2020-11-24 06:51:16.486 DEBUG 1 --- [nio-8080-exec-2] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
2020-11-24 06:51:16.487 DEBUG 1 --- [nio-8080-exec-2] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
2020-11-24 06:51:16.488 DEBUG 1 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /api/v1/auth/register at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2020-11-24 06:51:16.489 DEBUG 1 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /api/v1/auth/register at position 4 of 13 in additional filter chain; firing Filter: 'CorsFilter'
2020-11-24 06:51:16.494 DEBUG 1 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /api/v1/auth/register at position 5 of 13 in additional filter chain; firing Filter: 'CsrfFilter'
2020-11-24 06:51:16.525 DEBUG 1 --- [nio-8080-exec-2] o.s.security.web.csrf.CsrfFilter : Invalid CSRF token found for http://dev.api.example.com/api/v1/auth/register
2020-11-24 06:51:16.609 DEBUG 1 --- [nio-8080-exec-2] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#461bbc94
2020-11-24 06:51:16.610 DEBUG 1 --- [nio-8080-exec-2] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2020-11-24 06:51:16.615 DEBUG 1 --- [nio-8080-exec-2] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed

Disable CSRF using .csrf().disable() in configure(HttpSecurity http) More deatils are explained here
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
... // other configurations
}

Related

Cannot open Swagger UI in its Version 3 in my Spring Boot Example

I have a problem about opening swagger ui in my Spring Boot Example.
I get this kind of error when I access to localhost:8080/swagger-ui or localhost:8080/root-api-name:swagger-ui
Securing GET /springboot-blog-rest-api/swagger-ui
2022-07-22 01:38:58.820 DEBUG 30576 --- [nio-8080-exec-4] s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to empty SecurityContext
2022-07-22 01:38:58.820 DEBUG 30576 --- [nio-8080-exec-4] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2022-07-22 01:38:58.820 DEBUG 30576 --- [nio-8080-exec-4] o.s.s.w.a.i.FilterSecurityInterceptor : Failed to authorize filter invocation [GET /springboot-blog-rest-api/swagger-ui] with attributes [authenticated]
2022-07-22 01:38:58.820 DEBUG 30576 --- [nio-8080-exec-4] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request
2022-07-22 01:38:58.820 DEBUG 30576 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : Securing GET /error
2022-07-22 01:38:58.821 DEBUG 30576 --- [nio-8080-exec-4] s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to empty SecurityContext
2022-07-22 01:38:58.821 DEBUG 30576 --- [nio-8080-exec-4] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2022-07-22 01:38:58.821 DEBUG 30576 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : Secured GET /error
2022-07-22 01:38:58.821 DEBUG 30576 --- [nio-8080-exec-4] a.DefaultWebInvocationPrivilegeEvaluator : filter invocation [/error] denied for AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=null], Granted Authorities=[ROLE_ANONYMOUS]]
org.springframework.security.access.AccessDeniedException: Access is denied
I used springfox-swagger2 version 3 , springfox-boot-starter version 3 and lastly springfox-swagger-ui version 2.9.
How can I fix my issue?
Here is my SwaggerConfig File.
#Configuration
#EnableSwagger2
public class SwaggerConfig {
public static final String AUTHORIZATION_HEADER = "Authorization";
private ApiKey apiKey(){
return new ApiKey("JWT", AUTHORIZATION_HEADER, "header");
}
private ApiInfo apiInfo(){
return new ApiInfo(
"Spring Boot Blog REST APIs",
"Spring Boot Blog REST API Documentation",
"1",
"Terms of service",
new Contact("Name", "website-address", "Email"),
"License of API",
"API license URL",
Collections.emptyList()
);
}
#Bean
public Docket api(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.securityContexts(Arrays.asList(securityContext()))
.securitySchemes(Arrays.asList(apiKey()))
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
private SecurityContext securityContext(){
return SecurityContext.builder().securityReferences(defaultAuth()).build();
}
private List<SecurityReference> defaultAuth(){
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Arrays.asList(new SecurityReference("JWT", authorizationScopes));
}
}
Here is my SecurityConfig file
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
#Autowired
private JwtAuthenticationEntryPoint authenticationEntryPoint;
#Bean
public JwtAuthenticationFilter jwtAuthenticationFilter(){
return new JwtAuthenticationFilter();
}
#Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
#Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().antMatchers("/v2/api-docs/**",
"/swagger-ui/**","/swagger-resources/**","/swagger-ui.html","/webjars/**");
}
#Bean
protected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests((authorize) -> authorize
.antMatchers(HttpMethod.GET, "/api/v1/**").permitAll()
.antMatchers("/api/v1/auth/**").permitAll()
.anyRequest()
.authenticated()
);
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
#Bean
public AuthenticationManager authenticationManager(
AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}
Here is the answer
I can access the url through localhost:8080/swagger-ui.html
If you are using Spring Security, use the following security configuration to allow public access to Swagger UI resources:
public class SecurityConfig {
private static final String[] AUTH_WHITELIST = {
// for Swagger UI v2
"/v2/api-docs",
"/swagger-ui.html",
"/swagger-resources",
"/swagger-resources/**",
"/configuration/ui",
"/configuration/security",
"/webjars/**",
// for Swagger UI v3 (OpenAPI)
"/v3/api-docs/**",
"/swagger-ui/**"
};
#Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) {
httpSecurity
// ... other configuration settings
.antMatchers(AUTH_WHITELIST).permitAll();
// ...
}
}

Access Denied - Unable to authenticate login - spring security

I work on simple authentication app using spring security & encounter by an access denied error. I must mention that registration works perfectly & I've already created 1 record with bcrypted password but on login I'm failed to understand that what did I miss. Grateful for the help
User.java
public class User implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private String username;
private String email;
private String password;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JsonIgnore
private Set<UserRole> userRoles = new HashSet<>();
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority>authorities = new HashSet<>();
userRoles.forEach(ur -> authorities.add(new
Authority(ur.getRole().getName())));
return authorities;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
SecurityConfig
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private UserSecurityService userSecurityService;
public SecurityConfig(UserSecurityService userSecurityService) {
this.userSecurityService = userSecurityService;
}
#Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/**").permitAll()
.antMatchers("/api/auth/**").permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws
Exception {
auth.userDetailsService(userSecurityService).passwordEncoder
(passwordEncoder());
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws
Exception {return super.authenticationManagerBean();
}
}
UserSecurityService (loaduser)
#Service
public class UserSecurityService implements UserDetailsService {
private static final Logger LOG =
LoggerFactory.getLogger(UserSecurityService.class);
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
User user = userRepository.findUserByUsername(username);
if (null == user) {
LOG.warn("Username {} not found", username);
throw new UsernameNotFoundException("Username " + username + "
not found");
}
return user;
}
}
AuthController
#RestController
#RequestMapping("/api/auth")
public class AuthController {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#Autowired
private PasswordEncoder passwordEncoder;
#Autowired
private UserService userService;
#PostMapping("/register")
public ResponseEntity<User> register(#RequestBody User user) throws Exception {
return new ResponseEntity<>(userService.register(user), HttpStatus.OK);
}
#PostMapping("/login")
public ResponseEntity<String> login(#RequestBody String username, String password ) throws
Exception {
Authentication authentication = authenticationManager.authenticate(new
UsernamePasswordAuthenticationToken(
username, password
));
SecurityContextHolder.getContext().setAuthentication(authentication);
return new ResponseEntity<>("User signed -in succesfully", HttpStatus.OK);
}
}
Error
2022-01-14 14:49:13.604 INFO 24600 --- [ restartedMain]
c.kash.bankingAPI.BankingApiApplication : Starting
BankingApiApplication using Java 11.0.12 on LAPTOP-BQ48GM36 with PID
24600 (B:\spring\bankingAPI\target\classes started by The Kash in
B:\spring\bankingAPI)
2022-01-14 14:49:13.605 INFO 24600 --- [ restartedMain]
c.kash.bankingAPI.BankingApiApplication : No active profile set,
falling back to default profiles: default
2022-01-14 14:49:13.673 INFO 24600 --- [ restartedMain]
.e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults
active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-01-14 14:49:13.674 INFO 24600 --- [ restartedMain]
.e.DevToolsPropertyDefaultsPostProcessor : For additional web related
logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-01-14 14:49:14.557 INFO 24600 --- [ restartedMain]
.s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data
JPA
repositories in DEFAULT mode.
2022-01-14 14:49:14.646 INFO 24600 --- [ restartedMain]
.s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data
repository scanning in 74 ms. Found 2 JPA repository interfaces.
2022-01-14 14:49:15.876 INFO 24600 --- [ restartedMain]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with
port(s): 8088 (http)
2022-01-14 14:49:15.890 INFO 24600 --- [ restartedMain]
o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-01-14 14:49:15.890 INFO 24600 --- [ restartedMain]
org.apache.catalina.core.StandardEngine : Starting Servlet engine:
[Apache Tomcat/9.0.56]
2022-01-14 14:49:16.008 INFO 24600 --- [ restartedMain] o.a.c.c.C.
[Tomcat].[localhost].[/] : Initializing Spring embedded
WebApplicationContext
2022-01-14 14:49:16.008 INFO 24600 --- [ restartedMain]
w.s.c.ServletWebServerApplicationContext : Root
WebApplicationContext:
initialization completed in 2334 ms
2022-01-14 14:49:16.264 INFO 24600 --- [ restartedMain]
o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing
PersistenceUnitInfo [name: default]
2022-01-14 14:49:16.332 INFO 24600 --- [ restartedMain]
org.hibernate.Version : HHH000412: Hibernate ORM
core
version 5.6.3.Final
2022-01-14 14:49:16.542 INFO 24600 --- [ restartedMain]
o.hibernate.annotations.common.Version : HCANN000001: Hibernate
Commons Annotations {5.1.2.Final}
2022-01-14 14:49:16.661 INFO 24600 --- [ restartedMain]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-01-14 14:49:17.128 INFO 24600 --- [ restartedMain]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start
completed.
2022-01-14 14:49:17.145 INFO 24600 --- [ restartedMain]
org.hibernate.dialect.Dialect : HHH000400: Using dialect:
org.hibernate.dialect.MySQL57Dialect
2022-01-14 14:49:18.469 INFO 24600 --- [ restartedMain]
o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using
JtaPlatform implementation:
[org.hibernate.engine.transaction.jta.platform.internal.
NoJtaPlatform]
2022-01-14 14:49:18.478 INFO 24600 --- [ restartedMain]
j.LocalContainerEntityManagerFactoryBean : Initialized JPA
EntityManagerFactory for persistence unit 'default'
2022-01-14 14:49:19.173 WARN 24600 --- [ restartedMain]
JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is
enabled by default. Therefore, database queries may be performed
during
view rendering. Explicitly configure spring.jpa.open-in-view to
disable
this warning
2022-01-14 14:49:19.453 DEBUG 24600 --- [ restartedMain]
edFilterInvocationSecurityMetadataSource : Adding web access control
expression [permitAll] for Ant [pattern='/api/**', GET]
2022-01-14 14:49:19.455 DEBUG 24600 --- [ restartedMain]
edFilterInvocationSecurityMetadataSource : Adding web access control
expression [permitAll] for Ant [pattern='/api/auth/**']
2022-01-14 14:49:19.456 DEBUG 24600 --- [ restartedMain]
edFilterInvocationSecurityMetadataSource : Adding web access control
expression [authenticated] for any request
2022-01-14 14:49:19.468 INFO 24600 --- [ restartedMain]
o.s.s.web.DefaultSecurityFilterChain : Will secure any request
with
[org.springframework.security.web.context.request.async.
WebAsyncManagerIntegrationFilter#4b607819,
org.springframework.security.web.context.SecurityContextPersistence
Filter#146dcdcf,
org.springframework.security.web.header.HeaderWriterFilter#74f0174b,
org.springframework.security.web.authentication.logout.
LogoutFilter#839ff7f,
org.springframework.security.web.authentication.www.
BasicAuthenticationFilter#4f78b9a2,
org.springframework.security.web.savedrequest.
RequestCacheAwareFilter#7e2b3eef,
org.springframework.security.web.servletapi.SecurityContextHolder
AwareRequestFilter#1996d59a,
org.springframework.security.web.authentication.Anonymous
AuthenticationFilter#d82cd0b,
org.springframework.security.web.session.SessionManagement
Filter#47842f0b,
org.springframework.security.web.access.ExceptionTranslation
Filter#6fdc8d32, org.springframework.security.web.access.intercept.
FilterSecurityInterceptor#3619bc38]
2022-01-14 14:49:19.922 INFO 24600 --- [ restartedMain]
o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is
running
on port 35729
2022-01-14 14:49:19.959 INFO 24600 --- [ restartedMain]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s):
8088 (http) with context path ''
2022-01-14 14:49:19.970 INFO 24600 --- [ restartedMain]
c.kash.bankingAPI.BankingApiApplication : Started
BankingApiApplication
in 6.835 seconds (JVM running for 7.645)
2022-01-14 14:49:51.914 INFO 24600 --- [nio-8088-exec-2] o.a.c.c.C.
[Tomcat].[localhost].[/] : Initializing Spring
DispatcherServlet
'dispatcherServlet'
2022-01-14 14:49:51.915 INFO 24600 --- [nio-8088-exec-2]
o.s.web.servlet.DispatcherServlet : Initializing Servlet
'dispatcherServlet'
2022-01-14 14:49:51.916 INFO 24600 --- [nio-8088-exec-2]
o.s.web.servlet.DispatcherServlet : Completed initialization
in
1 ms
2022-01-14 14:49:51.931 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Securing POST /api/auth/login
2022-01-14 14:49:51.936 DEBUG 24600 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder
to
empty SecurityContext
2022-01-14 14:49:51.939 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder
to
anonymous SecurityContext
2022-01-14 14:49:51.940 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.session.SessionManagementFilter : Request requested invalid
session id 1E5E812360CC1B8291311CA85ACAC55A
2022-01-14 14:49:51.945 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.a.i.FilterSecurityInterceptor : Authorized filter
invocation
[POST /api/auth/login] with attributes [permitAll]
2022-01-14 14:49:51.946 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Secured POST
/api/auth/login
Hibernate: select user0_.id as id1_7_, user0_.email as email2_7_,
user0_.name as name3_7_, user0_.password as password4_7_,
user0_.primary_account_id as primary_6_7_, user0_.savings_account_id
as
savings_7_7_, user0_.username as username5_7_ from users user0_ where
user0_.username=?
2022-01-14 14:49:52.305 WARN 24600 --- [nio-8088-exec-2]
c.k.b.s.serviceImpl.UserSecurityService : Username {
"username": "seeshee",
"password": "12345"
} not found
2022-01-14 14:49:52.313 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.a.dao.DaoAuthenticationProvider : Failed to find user '{
"username": "seeshee",
"password": "1234"
}'
2022-01-14 14:49:52.698 WARN 24600 --- [nio-8088-exec-2]
o.a.c.util.SessionIdGeneratorBase : Creation of SecureRandom
instance for session ID generation using [SHA1PRNG] took [364]
milliseconds.
2022-01-14 14:49:52.700 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.s.HttpSessionRequestCache : Saved request
http://localhost:8088/api/auth/login to session
2022-01-14 14:49:52.701 DEBUG 24600 --- [nio-8088-exec-2]
s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using
Reque
tHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expec
edHeaderValue=XMLHttpRequest]
2022-1-14 14:49:52.701 DEBUG 24600 --- [nio-8088-exec-2]
s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using
default entry point
org.springframework.security.web.authentication.www.
BasicAuthenticationEntryPoint#691634d7
2022-01-14 14:49:52.702 DEBUG 24600 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store empty
SecurityContext
2022-01-14 14:49:52.702 DEBUG 24600 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store empty
SecurityContext
2022-01-14 14:49:52.702 DEBUG 24600 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Cleared
SecurityContextHolder
to complete request
2022-01-14 14:49:52.705 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Securing POST /error
2022-01-14 14:49:52.705 DEBUG 24600 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder
to
empty SecurityContext
2022-01-14 14:49:52.706 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder
to
anonymous SecurityContext
2022-01-14 14:49:52.706 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Secured POST /error
2022-01-14 14:49:52.721 DEBUG 24600 --- [nio-8088-exec-2]
a.DefaultWebInvocationPrivilegeEvaluator : filter invocation [/error]
denied for AnonymousAuthenticationToken [Principal=anonymousUser,
Credentials=[PROTECTED], Authenticated=true,
Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1,
SessionId=BAFE9322A4A2705325C4B6540915129E], Granted Authorities=
[ROLE_ANONYMOUS]]
org.springframework.security.access.AccessDeniedException: Access is
denied
at
org.springframework.security.access.vote.AffirmativeBased.
decide(AffirmativeBased.java:73)
~[spring-security-core-5.6.1.jar:5.6.1]
at org.springframework.security.web.access.
DefaultWebInvocationPrivilegeEvaluator.isAllowed
(DefaultWe
bInvocationPrivilegeEvaluator.java:100) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.access.
DefaultWebInvocationPrivilegeEvaluator.isAllowed
(DefaultWebInvocationPrivilegeEvaluator.java:67) ~[spring-security-
web-
5.6.1.jar:5.6.1]
at
org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter.
isAllowed
(ErrorPageSecurityFilter.java:84) ~[spring-boot-2.6.2.jar:2.6.2]
at
org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter.
doFilter
(ErrorPageSecurityFilter.java:72) ~[spring-boot-2.6.2.jar:2.6.2]
at
org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter.
doFilter
(ErrorPageSecurityFilter.java:66) ~[spring-boot-2.6.2.jar:2.6.2]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
ApplicationFilterChain.
java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~
[tomcat-embed-core-9.0.56.jar:9.0.56]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.jav
a:327) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.access.intercept.
FilterSecurityInterceptor.invoke
(FilterSecurityInterceptor.java:106) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.access.intercept.
FilterSecurityInterceptor.doFilter
(FilterSecurityInterceptor.java:81) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.access.
ExceptionTranslationFilter.doFilter
(ExceptionTranslationFilter.java:122) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.access.ExceptionTranslationFilter.
doFilter
(ExceptionTranslationFilter.java:116) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.session.SessionManagementFilter
.doFilter
(SessionManagementFilter.java:87) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.session.SessionManagementFilter.
doFilter
(SessionManagementFilter.java:81) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain
.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.authentication.
AnonymousAuthenticationFilter.doFilter
(AnonymousAuthenticationFilter.java:109) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.servletapi.
SecurityContextHolderAwareRequestFilter.
doFilter(SecurityContextHolderAwareRequestFilter.java:149) ~[spring-
security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.savedrequest.
RequestCacheAwareFilter.doFilter
(RequestCacheAwareFilter.java:63) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.authentication.logout.
LogoutFilter.doFilter
(LogoutFilter.java:103) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.authentication.logout.
LogoutFilter.doFilter
(LogoutFilter.java:89) ~[spring-security-web-5.6.1.jar:5.6.1]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(
OncePerRequestFilter.java:102)
~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.security.web.FilterChainProxy$VirtualFilter
Chain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at
org.springframework.security.web.context.SecurityContextPersistence
Filter.doFilter
(SecurityContextPersistenceFilter.java:110) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.context.SecurityContextPersistence
Filter.doFilter
(SecurityContextPersistenceFilter.java:80) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy.doFilterInternal
(FilterChainProxy.java:211) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy.doFilter
(FilterChainProxy.java:183) ~[spring-security-web-5.6.1.jar:5.6.1]
at
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate
(DelegatingFilterProxy.java:354) ~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter
(DelegatingFilterProxy.java:267) ~
[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at
org.springframework.web.filter.RequestContextFilter.doFilterInternal
(RequestContextFilter.java:100) ~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:117) ~[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.invoke
(ApplicationDispatcher.java:711) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.processRequest
(ApplicationDispatcher.java:461) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.doForward
(ApplicationDispatcher.java:385) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.forward
(ApplicationDispatcher.java:313) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.StandardHostValve.custom
(StandardHostValve.java:403) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.StandardHostValve.status
(StandardHostValve.java:249) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
[tomcat-embed-core-9.0.56.jar:9.0.56]
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run
(TaskThread.java:61) ~
[tomcat-embed-core-9.0.56.jar:9.0.56]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
2022-01-14 00:49:13.289 DEBUG 21332 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store anonymous
SecurityContext
2022-01-14 00:49:13.289 DEBUG 21332 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store anonymous
SecurityContext
2022-01-14 00:49:13.289 DEBUG 21332 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Cleared
SecurityContextHolder to complete request
Your logs say this:
2022-01-14 14:49:52.305 WARN 24600 --- [nio-8088-exec-2] c.k.b.s.serviceImpl.UserSecurityService :
Username { "username": "seeshee", "password": "12345" } not found
If we look in your code we can see the following line:
login(#RequestBody String username, String password )
This is your faulty code line, as it doesn't do what you think it does. You think it will take the json and extract the two parameters username and password and set these. But what it actually does is that the #RequestBody will take the entire body (the json) and set it to the parameter that is defined on, which is username.
So what spring is doing is that it will extract the entire json body and place it into the username string.
Then you try to use that to login, and then you get the error message posted above.
What you need to do is to create a holder class that spring can deserialize into.
public class RequestBody {
public RequestBody(String username, String password) {
this.username = username;
this.password = password;
}
// getters, setters
}
#PostMapping("/login")
public ResponseEntity<String> login(#RequestBody RequestBody requestBody ) throws Exception {
Authentication authentication = authenticationManager.authenticate(new
UsernamePasswordAuthenticationToken(
requestBody.getUsername(), requestBody.getPassword()
));
SecurityContextHolder.getContext().setAuthentication(authentication);
return new ResponseEntity<>("User signed -in succesfully", HttpStatus.OK);
}
You can read about how to use requestbody here:
Spring’s RequestBody and ResponseBody Annotation

Spring Boot URL path variable encoding

I have a Spring boot (v2.3.5.RELEASE) REST API and cannot seem to fix an encoding problem with path variables. I have tried every solution that found online but nothing helped.
Here is the Main class:
#SpringBootApplication
public class RestApplication {
public static void main(String[] args) {
SpringApplication.run(RestApplication.class, args);
}
}
The RestController (the method is never executed when sending the request to that URL):
#RestController
#RequestMapping("/mvn/packages")
public class ModuleApi {
#Autowired
ModuleApiService service;
#GetMapping(value = "/{pkg}/{pkg_ver}/modules/{namespace}/metadata", produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> getModuleMetadata(#PathVariable("pkg") String package_name,
#PathVariable("pkg_ver") String package_version,
#PathVariable("namespace") String module_namespace) {
return service.getModuleMetadata(package_name, package_version, module_namespace);
}
}
The Configuration class:
#Configuration
public class CorsConfiguration
{
#Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setForceEncoding(true);
characterEncodingFilter.setEncoding("UTF-8");
registrationBean.setFilter(characterEncodingFilter);
return registrationBean;
}
}
The application.properties:
logging.level.org.springframework.web=DEBUG
server.port=8080
server.tomcat.uri-encoding=UTF-8
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.enabled=true
server.servlet.encoding.force=true
I even added encoding to the spring-boot-maven-plugin in the pom.xml:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.6.RELEASE</version>
<configuration>
<mainClass>RestApplication</mainClass>
<jvmArguments>-Dfile.encoding=UTF8</jvmArguments>
</configuration>
</plugin>
But the result is still the same.
When sending a request to http://localhost:8080/mvn/packages/junit:junit/4.12/%2Fjunit.framework%2FAssert
i.e. mvn/packages/{pkg}/{pkg_ver}/modules/{namespace}/metadata and namespace is encoded, it returns HTTP 400 - BAD REQUEST.
However, when I try http://localhost:8080/mvn/packages/junit:junit/4.12/foo (does not need encoding/decoding), it works.
I also tried using ALLOW_ENCODED_SLASH property. Main class:
#SpringBootApplication
public class RestApplication {
public static void main(String[] args) {
System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");
SpringApplication.run(RestApplication.class, args);
}
}
But in this case it cannot resolve the request to that mapping and returns 404 - NOT FOUND:
2020-12-10 17:03:27.044 DEBUG 105120 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/mvn/packages/junit:junit/4.12/%2Fjunit.framework%2FAssert", parameters={}
2020-12-10 17:03:27.053 DEBUG 105120 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2020-12-10 17:03:27.056 DEBUG 105120 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2020-12-10 17:03:27.056 DEBUG 105120 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
2020-12-10 17:03:27.060 DEBUG 105120 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/error", parameters={}
2020-12-10 17:03:27.062 DEBUG 105120 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
2020-12-10 17:03:27.083 DEBUG 105120 --- [nio-8080-exec-1] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
2020-12-10 17:03:27.087 DEBUG 105120 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 404
Can anyone help me please?

Spring Security custom login page with multiple Thymleaf ViewResolvers

I have searched and searched and can not find anything. I working on a PoC for a corp project using spring boot, thyme leaf, spring security.
If I set login page in spring security config like
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasAnyRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage ("/login")
.permitAll().defaultSuccessUrl ("/home")
.and()
.logout()
.permitAll();
}
and in my login page (HTML) I pass:
....
<link rel="stylesheet" type="text/css" href="/styles.css" />
....
simple css file:
#test {
font-family: Arial, sans-serif;
padding-left: 1em;
background-color: /*[[${backgroundColor}]]*/ pink !important;
}
I get log:
2017-06-28 21:50:29.436 INFO 24430 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 12 ms
2017-06-28 21:50:29.436 DEBUG 24430 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Servlet 'dispatcherServlet' configured successfully
2017-06-28 21:50:29.476 DEBUG 24430 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/login]
2017-06-28 21:50:29.477 DEBUG 24430 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /login
2017-06-28 21:50:29.492 DEBUG 24430 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public java.lang.String sample.multimodule.generic.web.login.login(org.springframework.ui.Model)]
2017-06-28 21:50:29.492 DEBUG 24430 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/login] is: -1
2017-06-28 21:50:29.505 DEBUG 24430 --- [nio-8080-exec-2] o.s.w.s.v.ContentNegotiatingViewResolver : Requested media types are [text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8] based on Accept header types and producible media types [*/*])
2017-06-28 21:50:29.509 DEBUG 24430 --- [nio-8080-exec-2] o.s.w.servlet.view.BeanNameViewResolver : Found matching bean for view name 'login' - to be ignored since it does not implement View
2017-06-28 21:50:29.510 DEBUG 24430 --- [nio-8080-exec-2] o.s.w.s.v.ContentNegotiatingViewResolver : Returning [org.thymeleaf.spring4.view.ThymeleafView#5d886361] based on requested media type 'text/html'
2017-06-28 21:50:29.511 DEBUG 24430 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Rendering view [org.thymeleaf.spring4.view.ThymeleafView#5d886361] in DispatcherServlet with name 'dispatcherServlet'
2017-06-28 21:50:29.776 DEBUG 24430 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Successfully completed request
2017-06-28 21:50:29.798 DEBUG 24430 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/login]
2017-06-28 21:50:29.798 DEBUG 24430 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /login
2017-06-28 21:50:29.799 DEBUG 24430 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public java.lang.String sample.multimodule.generic.web.login.login(org.springframework.ui.Model)]
2017-06-28 21:50:29.799 DEBUG 24430 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/login] is: -1
2017-06-28 21:50:29.799 DEBUG 24430 --- [nio-8080-exec-4] o.s.w.s.v.ContentNegotiatingViewResolver : Requested media types are [text/css, */*;q=0.1] based on Accept header types and producible media types [*/*])
2017-06-28 21:50:29.800 DEBUG 24430 --- [nio-8080-exec-4] o.s.w.servlet.view.BeanNameViewResolver : Found matching bean for view name 'login' - to be ignored since it does not implement View
2017-06-28 21:50:29.800 DEBUG 24430 --- [nio-8080-exec-4] o.s.w.servlet.view.BeanNameViewResolver : No matching bean found for view name 'login.css'
2017-06-28 21:50:29.800 DEBUG 24430 --- [nio-8080-exec-4] o.s.w.s.v.ContentNegotiatingViewResolver : Returning [org.thymeleaf.spring4.view.ThymeleafView#34f7b639] based on requested media type 'text/css'
2017-06-28 21:50:29.800 DEBUG 24430 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Rendering view [org.thymeleaf.spring4.view.ThymeleafView#34f7b639] in DispatcherServlet with name 'dispatcherServlet'
2017-06-28 21:50:29.819 ERROR 24430 --- [nio-8080-exec-4] org.thymeleaf.TemplateEngine : [THYMELEAF][http-nio-8080-exec-4] Exception processing template "login [text/html]": An error happened during template parsing (template: "class path resource [templates/css/login]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/css/login]")
at org.thymeleaf.templateparser.text.AbstractTextTemplateParser.parse(AbstractTextTemplateParser.java:174) ~[thymeleaf-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.thymeleaf.templateparser.text.AbstractTextTemplateParser.parseStandalone(AbstractTextTemplateParser.java:92) ~[thymeleaf-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:666) ~[thymeleaf-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098) [thymeleaf-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072) [thymeleaf-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:335) [thymeleaf-spring4-3.0.5.RELEASE.jar:3.0.5.RELEASE]
...
...
I have ThymeleafConfig:
#Configuration
#ConditionalOnClass({SpringTemplateEngine.class})
public class ThymeleafConfig extends WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter implements ApplicationContextAware {
private ApplicationContext applicationContext;
private static final String UTF8 = "UTF-8";
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
private TemplateEngine templateEngine(ITemplateResolver templateResolver) {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver);
return engine;
}
#Bean
public ViewResolver htmlViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setOrder (0);
resolver.setTemplateEngine(templateEngine(htmlTemplateResolver ()));
resolver.setCharacterEncoding(UTF8);
resolver.setContentType("text/html");
return resolver;
}
private ITemplateResolver htmlTemplateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setOrder (0);
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("classpath:/templates/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setCacheable(false);
return resolver;
}
#Bean
public ViewResolver cssViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setOrder (10);
resolver.setTemplateEngine(templateEngine(cssTemplateResolver ()));
resolver.setCharacterEncoding(UTF8);
resolver.setContentType("text/css");
return resolver;
}
private ITemplateResolver cssTemplateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setOrder (10);
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("classpath:/templates/css/");
resolver.setSuffix("");
resolver.setTemplateMode(TemplateMode.CSS);
resolver.setCacheable(false);
return resolver;
}
#Bean
public ViewResolver jsViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setOrder (20);
resolver.setTemplateEngine(templateEngine(jsTemplateResolver ()));
resolver.setCharacterEncoding(UTF8);
resolver.setContentType("application/javascript");
return resolver;
}
private ITemplateResolver jsTemplateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setOrder (20);
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("classpath:/templates/js/");
resolver.setSuffix("");
resolver.setTemplateMode(TemplateMode.JAVASCRIPT);
resolver.setCacheable(false);
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
And a Css Controller:
#Controller
public class CssController {
#RequestMapping (value = "/styles.css")
public String mainStyles(Model model, HttpServletResponse response) {
model.addAttribute("backgroundColor", "blue");
return "styles.css";
}
}
If I remove
....formLogin().loginPage ("/home")
from Security config and get it in controller as normal, it works, and the variables are added into the css file as I expect.
Any ideas of why I get this problem when directing to /login from within Spring Security?
*note first time posting, so apologize if in proper format.
Found where the issue was, wasn't permitting access to the file when using security.
Needed to add following to security config:
...
.antMatchers ("/styles.css").permitAll ()
...

Spring boot UrlFilenameViewController not working

I am trying to route a view when I request a specific URL without any Model, so i am using the URLFileNameController to do that, below is my main class and bean declaration for the same.
#SpringBootApplication
public class WebMvcApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(CpiWebMvcApplication.class);
}
public static void main(String[] args)
{
ApplicationContext ctx =SpringApplication.run(CpiWebMvcApplication.class, args);
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames)
{
System.out.println(beanName);
}
}
}
//Bean Declaration -- declared in a separate class
#Configuration
//#ImportResource("*/**/Controller-Beans.xml")
public class BeanConfig {
#Bean
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
#Bean(name = "urlViewController")
public UrlFilenameViewController getUrlViewController() {
UrlFilenameViewController urlViewController = new UrlFilenameViewController();
urlViewController.setSuffix(".jsp");
urlViewController.setPrefix("/WEB-INF/");
urlViewController.setAlwaysUseFullPath(true);
return urlViewController;
}
#Bean
public SimpleUrlHandlerMapping getUrlHandlerMapping() {
SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
Properties mappings = new Properties();
mappings.put("*.do", getUrlViewController());
handlerMapping.setMappings(mappings);
return handlerMapping;
}
#Bean
public DispatcherServlet dispatcherServlet() {
return new DispatcherServlet();
}
/**
* Register dispatcherServlet programmatically
*
* #return ServletRegistrationBean
*/
#Bean
public ServletRegistrationBean dispatcherServletRegistration() {
ServletRegistrationBean registration = new ServletRegistrationBean(
dispatcherServlet());
registration.addUrlMappings("*.do");
registration
.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
registration.setLoadOnStartup(-1);
return registration;
}
When I run my spring boot app, I get the following:
2017-01-04 10:43:04.806 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing servlet 'dispatcherServletRegistration'
2017-01-04 10:43:04.807 INFO 24728 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServletRegistration'
2017-01-04 10:43:04.807 INFO 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServletRegistration': initialization started
2017-01-04 10:43:04.807 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Using MultipartResolver [org.springframework.web.multipart.support.StandardServletMultipartResolver#7f1abac0]
2017-01-04 10:43:04.817 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Unable to locate LocaleResolver with name 'localeResolver': using default [org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver#621cf3e7]
2017-01-04 10:43:04.830 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Unable to locate ThemeResolver with name 'themeResolver': using default [org.springframework.web.servlet.theme.FixedThemeResolver#41e31325]
2017-01-04 10:43:04.837 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Unable to locate RequestToViewNameTranslator with name 'viewNameTranslator': using default [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator#46a1a74]
2017-01-04 10:43:04.852 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Unable to locate FlashMapManager with name 'flashMapManager': using default [org.springframework.web.servlet.support.SessionFlashMapManager#56cd7abe]
2017-01-04 10:43:04.852 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Published WebApplicationContext of servlet 'dispatcherServletRegistration' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServletRegistration]
2017-01-04 10:43:04.852 INFO 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServletRegistration': initialization completed in 45 ms
2017-01-04 10:43:04.852 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Servlet 'dispatcherServletRegistration' configured successfully
2017-01-04 10:43:04.879 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServletRegistration' processing GET request for [/logout.do]
2017-01-04 10:43:04.894 DEBUG 24728 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /logout.do
2017-01-04 10:43:04.909 DEBUG 24728 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/logout.do]
2017-01-04 10:43:04.909 DEBUG 24728 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Matching patterns for request [/logout.do] are [/**]
2017-01-04 10:43:04.912 DEBUG 24728 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : URI Template variables for request [/logout.do] are {}
2017-01-04 10:43:04.912 DEBUG 24728 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapping [/logout.do] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver#720653c2]]] and 1 interceptor
2017-01-04 10:43:04.912 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/logout.do] is: -1
2017-01-04 10:43:04.917 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServletRegistration': assuming HandlerAdapter completed request handling
2017-01-04 10:43:04.917 DEBUG 24728 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Successfully completed request
The logs clearly states that my app is not able to find the view, but I am not able to understand where i am doing wrong, as when i declared a controller with a mapping, i am able to get the view.
#Controller
public class LoginPageController {
#RequestMapping("/secure/main")
//#ResponseBody
public String getLoginpage(Model model, #RequestParam(value="name", required=false, defaultValue="Uttik") String name)
{
model.addAttribute("name", name);
return "unauth";
}
}
I tried even declaring the beans in xml, still it didnt worked. Any idea where i am doing wrong?
Thanks in advance!!

Categories