Bean Initialization Error

I am Getting this error ->
Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2024-07-03T11:11:21.350+05:30 ERROR 11748 --- [ restartedMain] o.s.boot.SpringApplication  : Application run failed

org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'securityConfiguration': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:355) ~[spring-beans-6.1.10.jar:6.1.10]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:227) ~[spring-beans-6.1.10.jar:6.1.10]

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2024-07-03T11:11:21.350+05:30 ERROR 11748 --- [ restartedMain] o.s.boot.SpringApplication  : Application run failed

org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'securityConfiguration': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:355) ~[spring-beans-6.1.10.jar:6.1.10]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:227) ~[spring-beans-6.1.10.jar:6.1.10]

129 Replies
JavaBot
JavaBot5mo ago
This post has been reserved for your question.
Hey @Danix! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
Danix
DanixOP5mo ago
With this ->
@Configuration
public class SecurityConfiguration {

@Autowired
private UserDetailsServiceImp detailsServiceImp;

@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth.requestMatchers("/", "/signup" , "/processRegister").permitAll()
.anyRequest().authenticated())

.formLogin(login -> login.loginPage("/LoginPage").loginProcessingUrl("/LoginPage")
.defaultSuccessUrl("/").permitAll())
.logout(logout -> logout.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll());

return httpSecurity.build();
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(detailsServiceImp).passwordEncoder(encoder());
}

@Bean
PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
}
@Configuration
public class SecurityConfiguration {

@Autowired
private UserDetailsServiceImp detailsServiceImp;

@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth.requestMatchers("/", "/signup" , "/processRegister").permitAll()
.anyRequest().authenticated())

.formLogin(login -> login.loginPage("/LoginPage").loginProcessingUrl("/LoginPage")
.defaultSuccessUrl("/").permitAll())
.logout(logout -> logout.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll());

return httpSecurity.build();
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(detailsServiceImp).passwordEncoder(encoder());
}

@Bean
PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
}
i dont know why i am getting this @dan1st | Daniel can u help
Peter Rader
Peter Rader5mo ago
Are there any @PostConstruct annotated methods in the project?
Danix
DanixOP5mo ago
Yehh but they are just printing simple plain text in the console and i even removed them already @Peter Rader
Peter Rader
Peter Rader5mo ago
And the problem still exists?
Danix
DanixOP5mo ago
Yehh It's still there @dan1st | Daniel can u see this problem
Tomasm21
Tomasm215mo ago
Try to add @Lazy annotation onto UserDetailsServiceImp in security configuration.
Danix
DanixOP5mo ago
I did it but it doesn't work
dan1st
dan1st5mo ago
Can you show the full stack trace? Also please don't ping individual users for help unless they tell you it's ok
Danix
DanixOP5mo ago
dan1st
dan1st5mo ago
Can you show your UserDetailsServiceImp?
Tomasm21
Tomasm215mo ago
Can you share the project?
JavaBot
JavaBot5mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.
Danix
DanixOP5mo ago
here it is
package com.ShelfSpace.ShelfSpace.service;

import java.util.Collection;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.ShelfSpace.ShelfSpace.model.CustomUserDetails;
import com.ShelfSpace.ShelfSpace.model.User;
import com.ShelfSpace.ShelfSpace.repository.UserRepository;

import jakarta.annotation.PostConstruct;


@Service
public class UserDetailsServiceImp implements UserDetailsService{


@Autowired
private UserRepository userRepository;

@PostConstruct()
public String hii() {
System.out.println("The User Details Service is Being intialized");
return "Hi";
}

@Override
public UserDetails loadUserByUsername(String email) {

User userDetails = userRepository.findByEmail(email);
if (userDetails==null) {
throw new UsernameNotFoundException("No User Found");
}

Collection<? extends GrantedAuthority> authorities = userDetails.getRoles().stream()
.map(authRoles -> new SimpleGrantedAuthority(authRoles.getRoleName()))
.collect(Collectors.toList());

return new CustomUserDetails(userDetails.getEmail(), userDetails.getPassword(), authorities);
}

}
package com.ShelfSpace.ShelfSpace.service;

import java.util.Collection;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.ShelfSpace.ShelfSpace.model.CustomUserDetails;
import com.ShelfSpace.ShelfSpace.model.User;
import com.ShelfSpace.ShelfSpace.repository.UserRepository;

import jakarta.annotation.PostConstruct;


@Service
public class UserDetailsServiceImp implements UserDetailsService{


@Autowired
private UserRepository userRepository;

@PostConstruct()
public String hii() {
System.out.println("The User Details Service is Being intialized");
return "Hi";
}

@Override
public UserDetails loadUserByUsername(String email) {

User userDetails = userRepository.findByEmail(email);
if (userDetails==null) {
throw new UsernameNotFoundException("No User Found");
}

Collection<? extends GrantedAuthority> authorities = userDetails.getRoles().stream()
.map(authRoles -> new SimpleGrantedAuthority(authRoles.getRoleName()))
.collect(Collectors.toList());

return new CustomUserDetails(userDetails.getEmail(), userDetails.getPassword(), authorities);
}

}
the config class ->
package com.ShelfSpace.ShelfSpace.Config;


import com.ShelfSpace.ShelfSpace.service.UserDetailsServiceImp;

import jakarta.annotation.PostConstruct;

@Configuration
public class SecurityConfiguration {


private final UserDetailsServiceImp detailsServiceImp;


@Autowired
public SecurityConfiguration(UserDetailsServiceImp detailsServiceImp) {
this.detailsServiceImp = detailsServiceImp;
}

@PostConstruct()
public String hii() {
System.out.println("The Security Config is Being intialized");
return "Hi";
}

@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth.requestMatchers("/", "/signup" , "/processRegister").permitAll()
.anyRequest().authenticated())

.formLogin(login -> login.loginPage("/Login").loginProcessingUrl("/LoginPage")
.defaultSuccessUrl("/" , true).permitAll())
.logout(logout -> logout.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll());

return httpSecurity.build();
}


@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(detailsServiceImp).passwordEncoder(encoder());
}

@PostConstruct()
public String hi() {
System.out.println("The config is Being intialized");
return "Hi";
}

@Bean
PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
}
package com.ShelfSpace.ShelfSpace.Config;


import com.ShelfSpace.ShelfSpace.service.UserDetailsServiceImp;

import jakarta.annotation.PostConstruct;

@Configuration
public class SecurityConfiguration {


private final UserDetailsServiceImp detailsServiceImp;


@Autowired
public SecurityConfiguration(UserDetailsServiceImp detailsServiceImp) {
this.detailsServiceImp = detailsServiceImp;
}

@PostConstruct()
public String hii() {
System.out.println("The Security Config is Being intialized");
return "Hi";
}

@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth.requestMatchers("/", "/signup" , "/processRegister").permitAll()
.anyRequest().authenticated())

.formLogin(login -> login.loginPage("/Login").loginProcessingUrl("/LoginPage")
.defaultSuccessUrl("/" , true).permitAll())
.logout(logout -> logout.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll());

return httpSecurity.build();
}


@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(detailsServiceImp).passwordEncoder(encoder());
}

@PostConstruct()
public String hi() {
System.out.println("The config is Being intialized");
return "Hi";
}

@Bean
PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
}
Tomasm21
Tomasm215mo ago
I mean can you zip whole project and put here so we can download and put to our IDEs to try it and resolve. Other than that can you create password encoder as a separate class bean? Like a component? Then to autowire it to the spring config. And to use it in the configureGlobal method as a password encoder. This is how I have. Because earlier I also had circular referencies. And I got rid of it as I created separate password encoder bean.
Danix
DanixOP5mo ago
Yehh but I feel I am not comfortable to put my whole project here . So if it's possible you can help me from there
JavaBot
JavaBot5mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.
Danix
DanixOP5mo ago
The problem is not still solved
JavaBot
JavaBot5mo ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
Danix
DanixOP5mo ago
@dan1st | Daniel hey can u see it
dan1st
dan1st5mo ago
Can you try without the PostConstruct there?
Danix
DanixOP5mo ago
I did it but still getting the same issue !
Danix
DanixOP5mo ago
dan1st
dan1st5mo ago
Did you remove both @PostConstruct methods?
Danix
DanixOP5mo ago
yeh i did
dan1st
dan1st5mo ago
Why did you mark configureGlobal with @Autowired?
Peter Rader
Peter Rader5mo ago
Do you use constructor-injection?
Danix
DanixOP5mo ago
should not i do that ?
dan1st
dan1st5mo ago
I'm asking why to find out kinda I don't know what it's supposed to do
Danix
DanixOP5mo ago
ok i removed it and the error is gone but i am not able to login the user it says 302 ?
dan1st
dan1st5mo ago
You still haven't said what you wanted to achieve by making it @Autowired
Danix
DanixOP5mo ago
actually i was getting error with some of the thing so one guy tells me to do that and after that a new error spawn ! but i dont know how to resolve 302 error and thats the reason why i have to do that and i am still upon that issue !
JavaBot
JavaBot5mo ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
dan1st
dan1st5mo ago
Where are you getting the 302?
Danix
DanixOP5mo ago
/LoginPage endpoint
dan1st
dan1st5mo ago
You wrote anyRequest().authenticated() before the formLogin part
Danix
DanixOP5mo ago
yehhh so how it is intrupted the user to login in even the user is in DB
dan1st
dan1st5mo ago
so you are saying all requests need to be authenticated Can you try moving that part below the formLogin part?
Danix
DanixOP5mo ago
nahh still the same
dan1st
dan1st5mo ago
Can you try adding /LoginPage to the authorizeHttpRequests matchers at the top?
Danix
DanixOP5mo ago
let me try no still the same
package com.ShelfSpace.ShelfSpace.service;

import java.util.Collection;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.ShelfSpace.ShelfSpace.model.CustomUserDetails;
import com.ShelfSpace.ShelfSpace.model.User;
import com.ShelfSpace.ShelfSpace.repository.UserRepository;


@Service
public class UserDetailsServiceImp implements UserDetailsService{


@Autowired
private UserRepository userRepository;


@Override
public UserDetails loadUserByUsername(String email) {

User userDetails = userRepository.findByEmail(email);
if (userDetails==null) {
throw new UsernameNotFoundException("No User Found");
}

Collection<? extends GrantedAuthority> authorities = userDetails.getRoles().stream()
.map(authRoles -> new SimpleGrantedAuthority(authRoles.getRoleName()))
.collect(Collectors.toList());

return new CustomUserDetails(userDetails.getEmail(), userDetails.getPassword(), authorities);
}

}
package com.ShelfSpace.ShelfSpace.service;

import java.util.Collection;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.ShelfSpace.ShelfSpace.model.CustomUserDetails;
import com.ShelfSpace.ShelfSpace.model.User;
import com.ShelfSpace.ShelfSpace.repository.UserRepository;


@Service
public class UserDetailsServiceImp implements UserDetailsService{


@Autowired
private UserRepository userRepository;


@Override
public UserDetails loadUserByUsername(String email) {

User userDetails = userRepository.findByEmail(email);
if (userDetails==null) {
throw new UsernameNotFoundException("No User Found");
}

Collection<? extends GrantedAuthority> authorities = userDetails.getRoles().stream()
.map(authRoles -> new SimpleGrantedAuthority(authRoles.getRoleName()))
.collect(Collectors.toList());

return new CustomUserDetails(userDetails.getEmail(), userDetails.getPassword(), authorities);
}

}
This is How the UserDetailServie is Looks Like to check for the Authenticated User
dan1st
dan1st5mo ago
what exactly redirects? GETing the /LoginPage or actually logging in?
Danix
DanixOP5mo ago
The header looks like this ->
Request URL:
http://localhost:8080/LoginPage
Request Method:
POST
Status Code:
302 Found
Remote Address:
[::1]:8080
Referrer Policy:
strict-origin-when-cross-origin
Request URL:
http://localhost:8080/LoginPage
Request Method:
POST
Status Code:
302 Found
Remote Address:
[::1]:8080
Referrer Policy:
strict-origin-when-cross-origin
..
dan1st
dan1st5mo ago
ah ok
Danix
DanixOP5mo ago
hmm did u get it ?
<div class="container register-container">
<h2 class="text-center">Login</h2>
<form th:action="@{/LoginPage}" method="post" class="register-form">
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email" required>
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-success btn-block">Submit</button>
</form>
<p class="text-center">Don't have an account? <a th:href="@{/signup}">Register</a></p>
</div>
</body>
</html>
<div class="container register-container">
<h2 class="text-center">Login</h2>
<form th:action="@{/LoginPage}" method="post" class="register-form">
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email" required>
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-success btn-block">Submit</button>
</form>
<p class="text-center">Don't have an account? <a th:href="@{/signup}">Register</a></p>
</div>
</body>
</html>
is it due to my html stuff is it the right way to config the Spring Security for login page right ? bcz after the Update i think a lot of things had been changed !
dan1st
dan1st5mo ago
Can you try putting the content and parameter of configureGlobal in the filterChain method? now it finally sent the message
Danix
DanixOP5mo ago
wdym by this can u ellaborate ?
dan1st
dan1st5mo ago
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity, AuthenticationManagerBuilder auth, PasswordEncoder encoder) throws Exception {
httpSecurity.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth.requestMatchers("/", "/signup" , "/processRegister").permitAll()
.anyRequest().authenticated())

.formLogin(login -> login.loginPage("/Login").loginProcessingUrl("/LoginPage")
.defaultSuccessUrl("/" , true).permitAll())
.logout(logout -> logout.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll());

auth.userDetailsService(detailsServiceImp).passwordEncoder(encoder);

return httpSecurity.build();
}
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity, AuthenticationManagerBuilder auth, PasswordEncoder encoder) throws Exception {
httpSecurity.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth.requestMatchers("/", "/signup" , "/processRegister").permitAll()
.anyRequest().authenticated())

.formLogin(login -> login.loginPage("/Login").loginProcessingUrl("/LoginPage")
.defaultSuccessUrl("/" , true).permitAll())
.logout(logout -> logout.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll());

auth.userDetailsService(detailsServiceImp).passwordEncoder(encoder);

return httpSecurity.build();
}
Danix
DanixOP5mo ago
The holy error i got
Danix
DanixOP5mo ago
dan1st
dan1st5mo ago
Then try that
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth.requestMatchers("/", "/signup" , "/processRegister").permitAll()
.anyRequest().authenticated())

.formLogin(login -> login.loginPage("/Login").loginProcessingUrl("/LoginPage")
.defaultSuccessUrl("/" , true).permitAll())
.logout(logout -> logout.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll());

return httpSecurity.build();
}


@Bean
public AuthenticationManager configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
return auth.userDetailsService(detailsServiceImp).passwordEncoder(encoder());
}
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth.requestMatchers("/", "/signup" , "/processRegister").permitAll()
.anyRequest().authenticated())

.formLogin(login -> login.loginPage("/Login").loginProcessingUrl("/LoginPage")
.defaultSuccessUrl("/" , true).permitAll())
.logout(logout -> logout.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll());

return httpSecurity.build();
}


@Bean
public AuthenticationManager configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
return auth.userDetailsService(detailsServiceImp).passwordEncoder(encoder());
}
Danix
DanixOP5mo ago
another error
Danix
DanixOP5mo ago
dan1st
dan1st5mo ago
You could try putting it in another class
Danix
DanixOP5mo ago
wdym
dan1st
dan1st5mo ago
@Configuration
public class AuthConfig{
@Bean
public AuthenticationManager configureGlobal(UserDetailServiceImp detailsServiceImp,AuthenticationManagerBuilder auth, PasswordEncoder encoder) throws Exception {
return auth.userDetailsService(detailsServiceImp).passwordEncoder(encoder);
}
}
@Configuration
public class AuthConfig{
@Bean
public AuthenticationManager configureGlobal(UserDetailServiceImp detailsServiceImp,AuthenticationManagerBuilder auth, PasswordEncoder encoder) throws Exception {
return auth.userDetailsService(detailsServiceImp).passwordEncoder(encoder);
}
}
or actually I think it might be ok if you change
@Bean
public AuthenticationManager configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
return auth.userDetailsService(detailsServiceImp).passwordEncoder(encoder());
}
@Bean
public AuthenticationManager configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
return auth.userDetailsService(detailsServiceImp).passwordEncoder(encoder());
}
to
@Bean
public AuthenticationManager configureGlobal(AuthenticationManagerBuilder auth, PasswordEncoder passwordEncoder) throws Exception {
return auth.userDetailsService(detailsServiceImp).passwordEncoder(passwordEncoder);
}
@Bean
public AuthenticationManager configureGlobal(AuthenticationManagerBuilder auth, PasswordEncoder passwordEncoder) throws Exception {
return auth.userDetailsService(detailsServiceImp).passwordEncoder(passwordEncoder);
}
Danix
DanixOP5mo ago
Danix
DanixOP5mo ago
i think i doesnot Help i have to do it like this
@Configuration
public class AuthConfig{

@Autowired
private UserDetailsServiceImp detailsServiceImp;

@Bean
AuthenticationManager configureGlobal(AuthenticationManagerBuilder auth, PasswordEncoder passwordEncoder) throws Exception {
return (AuthenticationManager) auth.userDetailsService(detailsServiceImp).passwordEncoder(passwordEncoder);
}
}
@Configuration
public class AuthConfig{

@Autowired
private UserDetailsServiceImp detailsServiceImp;

@Bean
AuthenticationManager configureGlobal(AuthenticationManagerBuilder auth, PasswordEncoder passwordEncoder) throws Exception {
return (AuthenticationManager) auth.userDetailsService(detailsServiceImp).passwordEncoder(passwordEncoder);
}
}
Does my other class might have some problem may be I am not sure about it but I think I really made them very well
dan1st
dan1st5mo ago
¯\_(ツ)_/¯
Danix
DanixOP5mo ago
So what do u think what's the problem here because I am stucked here from last 2 days !
dan1st
dan1st5mo ago
idk some circular dependency maybe you could try not using autowired as all/doing everything with constructor parameters and don't do things like encoder() Why?
Danix
DanixOP5mo ago
Bcz it was giving me the red line error .
Type mismatch: cannot convert from DaoAuthenticationConfigurer<AuthenticationManagerBuilder,UserDetailsServiceImp> to AuthenticationManager
Type mismatch: cannot convert from DaoAuthenticationConfigurer<AuthenticationManagerBuilder,UserDetailsServiceImp> to AuthenticationManager
like this
dan1st
dan1st5mo ago
ah yeah you need to add a .build()
Danix
DanixOP5mo ago
no there is no .build() coming there
dan1st
dan1st5mo ago
@Configuration
public class AuthConfig{

@Bean
AuthenticationManager configureGlobal(UserDetailsServiceImp detailsServiceImp, AuthenticationManagerBuilder auth, PasswordEncoder passwordEncoder) throws Exception {
return (AuthenticationManager) auth.userDetailsService(detailsServiceImp).passwordEncoder(passwordEncoder).build();
}
}
@Configuration
public class AuthConfig{

@Bean
AuthenticationManager configureGlobal(UserDetailsServiceImp detailsServiceImp, AuthenticationManagerBuilder auth, PasswordEncoder passwordEncoder) throws Exception {
return (AuthenticationManager) auth.userDetailsService(detailsServiceImp).passwordEncoder(passwordEncoder).build();
}
}
Danix
DanixOP5mo ago
No description
dan1st
dan1st5mo ago
@Configuration
public class AuthConfig{

@Bean
AuthenticationManager configureGlobal(UserDetailsServiceImp detailsServiceImp, AuthenticationManagerBuilder auth, PasswordEncoder passwordEncoder) throws Exception {
return (AuthenticationManager) auth.userDetailsService(detailsServiceImp).passwordEncoder(passwordEncoder).and().build();
}
}
@Configuration
public class AuthConfig{

@Bean
AuthenticationManager configureGlobal(UserDetailsServiceImp detailsServiceImp, AuthenticationManagerBuilder auth, PasswordEncoder passwordEncoder) throws Exception {
return (AuthenticationManager) auth.userDetailsService(detailsServiceImp).passwordEncoder(passwordEncoder).and().build();
}
}
you might even need .and().and().build()
Danix
DanixOP5mo ago
but the error is still there
dan1st
dan1st5mo ago
Where?
Danix
DanixOP5mo ago
dan1st
dan1st5mo ago
ah that error Can you show your security config again?
Danix
DanixOP5mo ago
package com.ShelfSpace.ShelfSpace.Config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.ShelfSpace.ShelfSpace.service.UserDetailsServiceImp;

@Configuration
public class SecurityConfiguration {

@Autowired
private UserDetailsServiceImp detailsServiceImp;


@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth.requestMatchers("/", "/signup" , "/processRegister").permitAll()
.anyRequest().authenticated())

.formLogin(login -> login.loginPage("/Login").loginProcessingUrl("/LoginPage")
.defaultSuccessUrl("/" , true).permitAll())
.logout(logout -> logout.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll());

return httpSecurity.build();
}




@Bean
PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
}
package com.ShelfSpace.ShelfSpace.Config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.ShelfSpace.ShelfSpace.service.UserDetailsServiceImp;

@Configuration
public class SecurityConfiguration {

@Autowired
private UserDetailsServiceImp detailsServiceImp;


@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth.requestMatchers("/", "/signup" , "/processRegister").permitAll()
.anyRequest().authenticated())

.formLogin(login -> login.loginPage("/Login").loginProcessingUrl("/LoginPage")
.defaultSuccessUrl("/" , true).permitAll())
.logout(logout -> logout.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll());

return httpSecurity.build();
}




@Bean
PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
}
dan1st
dan1st5mo ago
Can you try removing
@Autowired
private UserDetailsServiceImp detailsServiceImp;
@Autowired
private UserDetailsServiceImp detailsServiceImp;
and add an UserDetailsServiceImp detailsServiceImp argument to filterChain
Danix
DanixOP5mo ago
yeh did i t but what about the code who is in different class bcz i dont need any userImpService in filter chain now if the AuthManager is in diff class
dan1st
dan1st5mo ago
?
Danix
DanixOP5mo ago
Danix
DanixOP5mo ago
the error i go t
dan1st
dan1st5mo ago
Which Spring Boot version are you using? Are you doing anything with HttpSecurity anywhere else?
JavaBot
JavaBot5mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.
Danix
DanixOP5mo ago
No i don't think so It was not the error before changing classes ! its showing 3.3.1 Can we do anything here to resolve it ?
package com.ShelfSpace.ShelfSpace.service;

import java.util.Collection;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.event.PublicInvocationEvent;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.ShelfSpace.ShelfSpace.model.CustomUserDetails;
import com.ShelfSpace.ShelfSpace.model.User;
import com.ShelfSpace.ShelfSpace.repository.UserRepository;

import jakarta.annotation.PostConstruct;


@Service
public class UserDetailsServiceImp implements UserDetailsService{


@Autowired
private UserRepository userRepository;


@Override
public UserDetails loadUserByUsername(String email) {

User userDetails = userRepository.findByEmail(email);
if (userDetails==null) {
throw new RuntimeException("No User Found");
}

Collection<? extends GrantedAuthority> authorities = userDetails.getRoles().stream()
.map(authRoles -> new SimpleGrantedAuthority(authRoles.getRoleName()))
.collect(Collectors.toList());

System.out.println("Founded User" +userDetails.toString());
return new CustomUserDetails(userDetails.getEmail(), userDetails.getPassword(), authorities);
}



}
package com.ShelfSpace.ShelfSpace.service;

import java.util.Collection;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.event.PublicInvocationEvent;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.ShelfSpace.ShelfSpace.model.CustomUserDetails;
import com.ShelfSpace.ShelfSpace.model.User;
import com.ShelfSpace.ShelfSpace.repository.UserRepository;

import jakarta.annotation.PostConstruct;


@Service
public class UserDetailsServiceImp implements UserDetailsService{


@Autowired
private UserRepository userRepository;


@Override
public UserDetails loadUserByUsername(String email) {

User userDetails = userRepository.findByEmail(email);
if (userDetails==null) {
throw new RuntimeException("No User Found");
}

Collection<? extends GrantedAuthority> authorities = userDetails.getRoles().stream()
.map(authRoles -> new SimpleGrantedAuthority(authRoles.getRoleName()))
.collect(Collectors.toList());

System.out.println("Founded User" +userDetails.toString());
return new CustomUserDetails(userDetails.getEmail(), userDetails.getPassword(), authorities);
}



}
Now I have changed the USernameError to Runtime Error for Debug purpose and i am getting a Whole Error that no user Found But that user is in DB as well @dan1st | Daniel
Tomasm21
Tomasm215mo ago
SO, can you run your application? Still messing with authentication? I have my configuration that I can just show you. In this Spring Security implementation remove encoder() method bean. Create new class for password encoder. Like MyPasswordEncoder:
@Component
public class MyPasswordEncoder {
private PasswordEncoder passwordEncoder;

public MyPasswordEncoder() {
this.passwordEncoder = new BCryptPasswordEncoder();
}

public PasswordEncoder getPasswordEncoder() {
return passwordEncoder;
}
}
@Component
public class MyPasswordEncoder {
private PasswordEncoder passwordEncoder;

public MyPasswordEncoder() {
this.passwordEncoder = new BCryptPasswordEncoder();
}

public PasswordEncoder getPasswordEncoder() {
return passwordEncoder;
}
}
And in Spring Security configuration inject it and use in AuthenticationManagerBuilder:
@Configuration
public class SecurityConfiguration {
//....
@Autowired
MyPasswordEncoder passwordEncoder;
//...
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(detailsServiceImp).passwordEncoder(passwordEncoder.getPasswordEncoder());
}
@Configuration
public class SecurityConfiguration {
//....
@Autowired
MyPasswordEncoder passwordEncoder;
//...
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(detailsServiceImp).passwordEncoder(passwordEncoder.getPasswordEncoder());
}
Danix
DanixOP5mo ago
So I have to make a password encoder separate class ?
Tomasm21
Tomasm215mo ago
Yes Not hard And you definitely need one more bean - AuthenticationManager:
@Bean
AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
put it somewhere in Spring Configuration. For example above the configureGlobal. And have the @Autowired above the configureGlobal. It's from my experience.
Danix
DanixOP5mo ago
Should i also have to autowored the UserDetailsImpService in the Config Class ?
Tomasm21
Tomasm215mo ago
Yes definitely. This is key interface needed for the Spring Security to work with Authentication
Danix
DanixOP5mo ago
ok done let me try it
Tomasm21
Tomasm215mo ago
I had in mind UserDetailsService interface. Not your implemnetation at UserDetailsImpService
Danix
DanixOP5mo ago
ohh
Tomasm21
Tomasm215mo ago
But try also with your class that implements the UserDetailsService interface.
Danix
DanixOP5mo ago
i tried with both of them but still getting 302 error !
Tomasm21
Tomasm215mo ago
Ahh.. don't know this. I just tried to help you to solve your first problem - circular reference. As of 302... I need more info. What exactly happens? You try to login, and you get 302?
Danix
DanixOP5mo ago
so how exactly the circular referance is solved ? and why it was happening ? yehh
Tomasm21
Tomasm215mo ago
I don't quite know what exact beans were involved and depended one on another. But it turned out that PasswordEncoder encoder() bean was that bean. I had the same circular reference and I read from stack trace this place:
at com.ShelfSpace.ShelfSpace.Config.SecurityConfiguration$$SpringCGLIB$$0.encoder(<generated>) ~[classes/:na]
at com.ShelfSpace.ShelfSpace.Config.SecurityConfiguration.configureGlobal(SecurityConfiguration.java:51) ~[classes/:na]
at com.ShelfSpace.ShelfSpace.Config.SecurityConfiguration$$SpringCGLIB$$0.encoder(<generated>) ~[classes/:na]
at com.ShelfSpace.ShelfSpace.Config.SecurityConfiguration.configureGlobal(SecurityConfiguration.java:51) ~[classes/:na]
that is the path to your project class methods.
Danix
DanixOP5mo ago
ok but how can i reslove this 302 thing This is my classs where user is authenticated
package com.ShelfSpace.ShelfSpace.service;

import java.util.Collection;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.event.PublicInvocationEvent;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.ShelfSpace.ShelfSpace.model.CustomUserDetails;
import com.ShelfSpace.ShelfSpace.model.User;
import com.ShelfSpace.ShelfSpace.repository.UserRepository;

import jakarta.annotation.PostConstruct;


@Service
public class UserDetailsServiceImp implements UserDetailsService{


@Autowired
private UserRepository userRepository;


@Override
public UserDetails loadUserByUsername(String email) {

User userDetails = userRepository.findByEmail(email);
if (userDetails==null) {
throw new RuntimeException("No User Found");
}

Collection<? extends GrantedAuthority> authorities = userDetails.getRoles().stream()
.map(authRoles -> new SimpleGrantedAuthority(authRoles.getRoleName()))
.collect(Collectors.toList());

System.out.println("Founded User" +userDetails.toString());
return new CustomUserDetails(userDetails.getEmail(), userDetails.getPassword(), authorities);
}



}
package com.ShelfSpace.ShelfSpace.service;

import java.util.Collection;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.event.PublicInvocationEvent;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.ShelfSpace.ShelfSpace.model.CustomUserDetails;
import com.ShelfSpace.ShelfSpace.model.User;
import com.ShelfSpace.ShelfSpace.repository.UserRepository;

import jakarta.annotation.PostConstruct;


@Service
public class UserDetailsServiceImp implements UserDetailsService{


@Autowired
private UserRepository userRepository;


@Override
public UserDetails loadUserByUsername(String email) {

User userDetails = userRepository.findByEmail(email);
if (userDetails==null) {
throw new RuntimeException("No User Found");
}

Collection<? extends GrantedAuthority> authorities = userDetails.getRoles().stream()
.map(authRoles -> new SimpleGrantedAuthority(authRoles.getRoleName()))
.collect(Collectors.toList());

System.out.println("Founded User" +userDetails.toString());
return new CustomUserDetails(userDetails.getEmail(), userDetails.getPassword(), authorities);
}



}
Tomasm21
Tomasm215mo ago
I am trying to find out. You should too. I never had this.
Danix
DanixOP5mo ago
and this is where user is added
package com.ShelfSpace.ShelfSpace.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.ShelfSpace.ShelfSpace.UserDao.UserInfoDao;
import com.ShelfSpace.ShelfSpace.model.User;
import com.ShelfSpace.ShelfSpace.model.UserRole;
import com.ShelfSpace.ShelfSpace.repository.RoleRepository;
import com.ShelfSpace.ShelfSpace.repository.UserRepository;

import jakarta.transaction.Transactional;

@Service
public class UserService implements UserInfoDao {

private UserRepository userRepository;
private RoleRepository roleRepository;
private PasswordEncoder passwordEncoder;

@Autowired
public UserService(UserRepository userRepository, RoleRepository roleRepository , PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
this.passwordEncoder = passwordEncoder;
}

@Transactional
@Override
public User addUser(User user) {
if (user.getRoles() == null || user.getRoles().isEmpty()) {
List<UserRole> roles = roleRepository.findByRoleName("USER");
user.setRoles(roles);
user.setPassword(passwordEncoder.encode(user.getPassword()));

}

user.getRoles().forEach(userRole -> {
userRole.setRegisteredUser(List.of(user));
});

userRepository.save(user);
return user;
}


}
package com.ShelfSpace.ShelfSpace.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.ShelfSpace.ShelfSpace.UserDao.UserInfoDao;
import com.ShelfSpace.ShelfSpace.model.User;
import com.ShelfSpace.ShelfSpace.model.UserRole;
import com.ShelfSpace.ShelfSpace.repository.RoleRepository;
import com.ShelfSpace.ShelfSpace.repository.UserRepository;

import jakarta.transaction.Transactional;

@Service
public class UserService implements UserInfoDao {

private UserRepository userRepository;
private RoleRepository roleRepository;
private PasswordEncoder passwordEncoder;

@Autowired
public UserService(UserRepository userRepository, RoleRepository roleRepository , PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
this.passwordEncoder = passwordEncoder;
}

@Transactional
@Override
public User addUser(User user) {
if (user.getRoles() == null || user.getRoles().isEmpty()) {
List<UserRole> roles = roleRepository.findByRoleName("USER");
user.setRoles(roles);
user.setPassword(passwordEncoder.encode(user.getPassword()));

}

user.getRoles().forEach(userRole -> {
userRole.setRegisteredUser(List.of(user));
});

userRepository.save(user);
return user;
}


}
so normally what u do ? The Custom UserDeatails
package com.ShelfSpace.ShelfSpace.model;

import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import lombok.Data;

@Data
public class CustomUserDetails implements UserDetails {

/**
*
*/
private static final long serialVersionUID = 1L;
private final String email;
private final String password;
private final Collection<? extends GrantedAuthority> authorities;


public CustomUserDetails(String email, String password, Collection<? extends GrantedAuthority> authorities) {

this.email = email;
this.password = password;
this.authorities = authorities;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
// TODO Auto-generated method stub
return authorities;
}

@Override
public String getPassword() {
// TODO Auto-generated method stub
return password;
}

@Override
public String getUsername() {
// TODO Auto-generated method stub
return email;
}

}
package com.ShelfSpace.ShelfSpace.model;

import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import lombok.Data;

@Data
public class CustomUserDetails implements UserDetails {

/**
*
*/
private static final long serialVersionUID = 1L;
private final String email;
private final String password;
private final Collection<? extends GrantedAuthority> authorities;


public CustomUserDetails(String email, String password, Collection<? extends GrantedAuthority> authorities) {

this.email = email;
this.password = password;
this.authorities = authorities;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
// TODO Auto-generated method stub
return authorities;
}

@Override
public String getPassword() {
// TODO Auto-generated method stub
return password;
}

@Override
public String getUsername() {
// TODO Auto-generated method stub
return email;
}

}
is it due to the .defaultSuccessUrl ?
Tomasm21
Tomasm215mo ago
I don't know. If you would give your project I would try to resolve it. I would start searching the Internet under what circumstances this is returned. To give or not to give it's up to you.
Danix
DanixOP5mo ago
i will show u every class what u need me to show to u bcz for this project me and my friends are working on it so i also have to take permission from them as well ! hope u understand
Tomasm21
Tomasm215mo ago
.defaultSuccessUrl("/", true) means that under successful login a user is redirected to /
Danix
DanixOP5mo ago
yess
Tomasm21
Tomasm215mo ago
Your login page should send credentials to http://localhost:8080/LoginPage
Danix
DanixOP5mo ago
yess
<body>
<div class="container register-container">
<h2 class="text-center">Login</h2>
<form th:action="@{/LoginPage}" method="post" class="register-form">
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email" required>
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-success btn-block">Submit</button>
</form>
<p class="text-center">Don't have an account? <a th:href="@{/signup}">Register</a></p>
</div>
</body>
</html>
<body>
<div class="container register-container">
<h2 class="text-center">Login</h2>
<form th:action="@{/LoginPage}" method="post" class="register-form">
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email" required>
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-success btn-block">Submit</button>
</form>
<p class="text-center">Don't have an account? <a th:href="@{/signup}">Register</a></p>
</div>
</body>
</html>
Tomasm21
Tomasm215mo ago
thymeleaf
Danix
DanixOP5mo ago
yess
Tomasm21
Tomasm215mo ago
I use React.js. Or test endpoints with swagger or Postman
Danix
DanixOP5mo ago
oh
Tomasm21
Tomasm215mo ago
Ensure that the login page URL ("/Login") and the login processing URL ("/LoginPage") are correctly mapped and handled in your application.
Danix
DanixOP5mo ago
package com.ShelfSpace.ShelfSpace.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import com.ShelfSpace.ShelfSpace.model.User;
import com.ShelfSpace.ShelfSpace.model.UserInfo;
import com.ShelfSpace.ShelfSpace.service.UserService;

import jakarta.validation.Valid;

@Controller
public class ShelfBookController {


@Autowired
private UserService userService;

@GetMapping("/")
public String homePage() {
return "home";
}

@GetMapping("/Login")
public String loginPage() {
return "login";
}


@GetMapping("/signup")
public String registerPage(org.springframework.ui.Model model) {
model.addAttribute(new UserInfo());
return "signup";
}

@PostMapping("/processRegister")
public String processRegister(@Valid @ModelAttribute("userInfo") UserInfo userInfo , BindingResult bindingResult , org.springframework.ui.Model model) {
if (bindingResult.hasErrors()) {
return"signup";
}
User user = new User(userInfo.getName() , userInfo.getEmail() , userInfo.getPassword());
model.addAttribute("userInfo" , user);
userService.addUser(user);
return "success";
}


}
package com.ShelfSpace.ShelfSpace.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import com.ShelfSpace.ShelfSpace.model.User;
import com.ShelfSpace.ShelfSpace.model.UserInfo;
import com.ShelfSpace.ShelfSpace.service.UserService;

import jakarta.validation.Valid;

@Controller
public class ShelfBookController {


@Autowired
private UserService userService;

@GetMapping("/")
public String homePage() {
return "home";
}

@GetMapping("/Login")
public String loginPage() {
return "login";
}


@GetMapping("/signup")
public String registerPage(org.springframework.ui.Model model) {
model.addAttribute(new UserInfo());
return "signup";
}

@PostMapping("/processRegister")
public String processRegister(@Valid @ModelAttribute("userInfo") UserInfo userInfo , BindingResult bindingResult , org.springframework.ui.Model model) {
if (bindingResult.hasErrors()) {
return"signup";
}
User user = new User(userInfo.getName() , userInfo.getEmail() , userInfo.getPassword());
model.addAttribute("userInfo" , user);
userService.addUser(user);
return "success";
}


}
The Controller
Tomasm21
Tomasm215mo ago
Try to add one more method in controller:
@GetMapping("/LoginPage")
public String loginProcessingPage() {
return "redirect:/";
}
@GetMapping("/LoginPage")
public String loginProcessingPage() {
return "redirect:/";
}
Danix
DanixOP5mo ago
nothing happens i dont know what to do know !!!!! The Hibernate Query is working but how it is not finding the user ??? Hibernate: select u1_0.email,u1_0.name,u1_0.password from registered_user u1_0 where u1_0.email=?
Tomasm21
Tomasm215mo ago
Not sure. it should. Does Founded User is printed in Spring console when you login from webpage?
Danix
DanixOP5mo ago
No
Danix
DanixOP5mo ago
The console i got after clicking login and try to login the user
Tomasm21
Tomasm215mo ago
Is UserDetailsServiceImp reached? Try this:
@Override
public UserDetails loadUserByUsername(String email) {
System.out.println("Loading user by email: ", email);
User userDetails = userRepository.findByEmail(email);
if (userDetails==null) {
throw new RuntimeException("No User Found");
}

Collection<? extends GrantedAuthority> authorities = userDetails.getRoles().stream()
.map(authRoles -> new SimpleGrantedAuthority(authRoles.getRoleName()))
.collect(Collectors.toList());

System.out.println("Founded User" +userDetails.toString());
return new CustomUserDetails(userDetails.getEmail(), userDetails.getPassword(), authorities);
}
@Override
public UserDetails loadUserByUsername(String email) {
System.out.println("Loading user by email: ", email);
User userDetails = userRepository.findByEmail(email);
if (userDetails==null) {
throw new RuntimeException("No User Found");
}

Collection<? extends GrantedAuthority> authorities = userDetails.getRoles().stream()
.map(authRoles -> new SimpleGrantedAuthority(authRoles.getRoleName()))
.collect(Collectors.toList());

System.out.println("Founded User" +userDetails.toString());
return new CustomUserDetails(userDetails.getEmail(), userDetails.getPassword(), authorities);
}
Danix
DanixOP5mo ago
The UserDetailsServiceImp Reached thats why the error we got in the console
Tomasm21
Tomasm215mo ago
You add exisiting user username and password but No User found? That's why you get 302 redirect Do you really have the user in the database?
Danix
DanixOP5mo ago
yehh The console
Loading user by email: Hibernate: select u1_0.email,u1_0.name,u1_0.password from registered_user u1_0 where u1_0.email=?
2024-07-05T13:40:23.332+05:30 ERROR 15996 --- [nio-8080-exec-6] w.a.UsernamePasswordAuthenticationFilter : An internal error occurred while trying to authenticate the user.
Loading user by email: Hibernate: select u1_0.email,u1_0.name,u1_0.password from registered_user u1_0 where u1_0.email=?
2024-07-05T13:40:23.332+05:30 ERROR 15996 --- [nio-8080-exec-6] w.a.UsernamePasswordAuthenticationFilter : An internal error occurred while trying to authenticate the user.
Tomasm21
Tomasm215mo ago
Can you show how your user look in databse?
Tomasm21
Tomasm215mo ago
Mine looks like this:
No description
Tomasm21
Tomasm215mo ago
I can select a user by email Does your user has id?
Danix
DanixOP5mo ago
is it possible to show the code by live streaming if u dont mind its really help to understand the problem
Tomasm21
Tomasm215mo ago
what's your user entity class?
Danix
DanixOP5mo ago
yeh
Tomasm21
Tomasm215mo ago
yes you can call and share screen
Danix
DanixOP5mo ago
ohh let me
JavaBot
JavaBot5mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.
Tomasm21
Tomasm215mo ago
Dan, I have found why that @Autowired is necessary. In order Spring Boot Security would be able to join itself PasswordEncoder. Because if not then we get such exception:
Tomasm21
Tomasm215mo ago
When UserDetailsService interface implemetation is this:
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;

@Override
@Transactional
public UserDetails loadUserByUsername(String email) {
System.out.printf("Loading user by email: %s\n", email);

User userDetails = userRepository.findByEmail(email);
if (userDetails == null) {
throw new RuntimeException("No User Found");
}

Collection<? extends GrantedAuthority> authorities = userDetails.getRoles().stream()
.map(authRoles -> new SimpleGrantedAuthority(authRoles.getRoleName())).collect(Collectors.toList());

System.out.println("FOUND USER:\n" + "Name: " + userDetails.getName() + ", Email: " + userDetails.getEmail()
+ ", password: " + userDetails.getPassword());
return new org.springframework.security.core.userdetails.User(
userDetails.getEmail(),
userDetails.getPassword(),
authorities
);
}
}
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;

@Override
@Transactional
public UserDetails loadUserByUsername(String email) {
System.out.printf("Loading user by email: %s\n", email);

User userDetails = userRepository.findByEmail(email);
if (userDetails == null) {
throw new RuntimeException("No User Found");
}

Collection<? extends GrantedAuthority> authorities = userDetails.getRoles().stream()
.map(authRoles -> new SimpleGrantedAuthority(authRoles.getRoleName())).collect(Collectors.toList());

System.out.println("FOUND USER:\n" + "Name: " + userDetails.getName() + ", Email: " + userDetails.getEmail()
+ ", password: " + userDetails.getPassword());
return new org.springframework.security.core.userdetails.User(
userDetails.getEmail(),
userDetails.getPassword(),
authorities
);
}
}
And if we add @Autowired on that:
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder.getPasswordEncoder());
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder.getPasswordEncoder());
}
method then there is no that exception and password is encoded. Authentication gets password needed to be with PasswordEncoder
JavaBot
JavaBot5mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.
Want results from more Discord servers?
Add your server