我正在尝试实施登录和注册。注册用户工作正常,但当我尝试登录时,我不断收到错误的凭据错误。以下是我的代码。我希望用户使用他们的电子邮件和密码登录,因此我真的不确定我是否遗漏了某些内容或者这是否可行,因为所有教程都显示了使用用户名和密码的登录示例。
我是新手,仍然在学习,所以我得到的任何帮助都会非常感激。
我的WebSecurityConfig类:
@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = CustomUserDetailsService.class)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
DataSource dataSource;
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/test").authenticated()
.and()
.formLogin()
.loginPage("/login")
.usernameParameter("email").passwordParameter("password")
.defaultSuccessUrl("/test")
.failureUrl("/login?error")
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/authentication/login")
.permitAll();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl tokenRepo = new JdbcTokenRepositoryImpl();
tokenRepo.setDataSource(dataSource);
return tokenRepo;
}
@Bean
public UserDetailsService userDetailsService() {
return super.userDetailsService();
}
}
CustomUserDetailsService
@Service
public class CustomUserDetailsService implements UserDetailsService{
private final UserRepository userRepository;
private final RoleRepository roleRepository;
@Autowired
public CustomUserDetailsService(UserRepository userRepository, RoleRepository roleRepository) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
}
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = userRepository.findByEmail(email);
if(user == null) {
throw new UsernameNotFoundException("User not found" + email);
}
else {
/*
List<String> userRoles = roleRepository.findRoleByUserId(user.getUserId());
return new CustomUserDetails(user, userRoles);
*/
List<Role> roles = new ArrayList<Role>();
roles.add(user.getRole());
return new CustomUserDetails(user, roles);
}
}
}
的login.html
<div th:if="${success}" class="alert alert-success" role="alert" th:text="${success}"></div>
<div th:if="${error}" class="alert alert-danger" role="alert" th:text="${error}"></div>
<form method="post" th:action="@{/login}" th:object="${user}">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input class="form-control" id="exampleInputEmail1" name="email" type="email" th:field="*{email}" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input class="form-control" id="exampleInputPassword1" name="password" type="password" th:field="*{password}" placeholder="Password">
</div>
<div class="form-group">
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="checkbox" name="remember-me"> Remember Password</label>
</div>
</div>
<button class="btn btn-primary btn-block" type="submit">Login</button>
</form>
堆栈追踪:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.10.RELEASE)
2018-02-06 10:51:09.972 INFO 7116 --- [ main] c.b.app.SpringBootcampApplication : Starting SpringBootcampApplication on localhost.localdomain with PID 7116 (started by cuteowl in /home/cuteowl/Documents/Work/JAVA SPRING PROJECT/SpringBootcamp)
2018-02-06 10:51:09.975 INFO 7116 --- [ main] c.b.app.SpringBootcampApplication : No active profile set, falling back to default profiles: default
2018-02-06 10:51:10.287 INFO 7116 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@646be2c3: startup date [Tue Feb 06 10:51:10 CET 2018]; root of context hierarchy
2018-02-06 10:51:11.704 INFO 7116 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$319d2e5a] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-02-06 10:51:12.285 INFO 7116 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-02-06 10:51:12.318 INFO 7116 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-02-06 10:51:12.320 INFO 7116 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.27
2018-02-06 10:51:12.502 INFO 7116 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-02-06 10:51:12.502 INFO 7116 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2218 ms
2018-02-06 10:51:12.743 INFO 7116 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-02-06 10:51:12.743 INFO 7116 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-02-06 10:51:12.743 INFO 7116 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-02-06 10:51:12.743 INFO 7116 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-02-06 10:51:12.745 INFO 7116 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-02-06 10:51:12.745 INFO 7116 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-02-06 10:51:13.419 INFO 7116 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-02-06 10:51:13.438 INFO 7116 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2018-02-06 10:51:13.592 INFO 7116 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2018-02-06 10:51:13.593 INFO 7116 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2018-02-06 10:51:13.594 INFO 7116 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2018-02-06 10:51:13.632 INFO 7116 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-02-06 10:51:13.739 INFO 7116 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2018-02-06 10:51:14.232 INFO 7116 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000228: Running hbm2ddl schema update
2018-02-06 10:51:14.243 INFO 7116 --- [ main] rmationExtractorJdbcDatabaseMetaDataImpl : HHH000262: Table not found: roles
2018-02-06 10:51:14.244 INFO 7116 --- [ main] rmationExtractorJdbcDatabaseMetaDataImpl : HHH000262: Table not found: roles
2018-02-06 10:51:14.412 INFO 7116 --- [ main] rmationExtractorJdbcDatabaseMetaDataImpl : HHH000262: Table not found: users
2018-02-06 10:51:14.414 INFO 7116 --- [ main] rmationExtractorJdbcDatabaseMetaDataImpl : HHH000262: Table not found: users
2018-02-06 10:51:15.429 INFO 7116 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-02-06 10:51:16.419 INFO 7116 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@54895681, org.springframework.security.web.context.SecurityContextPersistenceFilter@28daf506, org.springframework.security.web.header.HeaderWriterFilter@5a47730c, org.springframework.security.web.csrf.CsrfFilter@440ef8d, org.springframework.security.web.authentication.logout.LogoutFilter@4e48462d, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@633ddc0c, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@693f2213, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@7ac48f05, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@2dd0a0d0, org.springframework.security.web.session.SessionManagementFilter@1cde374, org.springframework.security.web.access.ExceptionTranslationFilter@46612bfc, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@3cc3f13e]
2018-02-06 10:51:16.709 INFO 7116 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@646be2c3: startup date [Tue Feb 06 10:51:10 CET 2018]; root of context hierarchy
2018-02-06 10:51:16.795 INFO 7116 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/login],methods=[GET]}" onto public java.lang.String com.bootcamp.app.controllers.LoginController.showLoginPage(org.springframework.ui.Model,com.bootcamp.app.models.User,java.util.Optional<java.lang.String>,java.util.Optional<java.lang.String>)
2018-02-06 10:51:16.797 INFO 7116 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/register],methods=[GET]}" onto public java.lang.String com.bootcamp.app.controllers.RegisterController.showRegisterPage(org.springframework.ui.Model,com.bootcamp.app.models.User)
2018-02-06 10:51:16.797 INFO 7116 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/register/new-user],methods=[POST]}" onto public java.lang.String com.bootcamp.app.controllers.RegisterController.postRegisterPage(org.springframework.ui.Model,com.bootcamp.app.models.User,org.springframework.validation.BindingResult,javax.servlet.http.HttpServletRequest)
2018-02-06 10:51:16.797 INFO 7116 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/confirm],methods=[GET]}" onto public java.lang.String com.bootcamp.app.controllers.RegisterController.showConfirmationPage(org.springframework.ui.Model,java.lang.String)
2018-02-06 10:51:16.797 INFO 7116 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/confirm],methods=[POST]}" onto public java.lang.String com.bootcamp.app.controllers.RegisterController.processConfirmationForm(org.springframework.ui.Model,java.util.Map)
2018-02-06 10:51:16.798 INFO 7116 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/test],methods=[GET]}" onto public java.lang.String com.bootcamp.app.controllers.TestController.test()
2018-02-06 10:51:16.801 INFO 7116 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-02-06 10:51:16.802 INFO 7116 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-02-06 10:51:16.841 INFO 7116 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-06 10:51:16.842 INFO 7116 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-06 10:51:16.882 INFO 7116 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-06 10:51:17.394 INFO 7116 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-02-06 10:51:17.458 INFO 7116 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-02-06 10:51:17.465 INFO 7116 --- [ main] c.b.app.SpringBootcampApplication : Started SpringBootcampApplication in 7.823 seconds (JVM running for 8.19)
2018-02-06 10:51:35.719 INFO 7116 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-02-06 10:51:35.720 INFO 7116 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-02-06 10:51:35.748 INFO 7116 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 28 ms
2018-02-06 10:51:47.792 INFO 7116 --- [nio-8080-exec-8] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
2018-02-06 10:52:46.550 WARN 7116 --- [nio-8080-exec-8] o.s.s.c.bcrypt.BCryptPasswordEncoder : Empty encoded password
答案 0 :(得分:0)
将方法configAuthentication()
更改为:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
这是spring boot对默认身份验证提供程序的期望。然后查看您是否在登录尝试时调用了您的用户详细信息服务。
另请发布您的CustomUserDetails
实施。