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:springbankingAPItargetclasses started by The Kash in B:springbankingAPI) 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
Advertisement
Answer
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: