An internal error occurred while trying to authenticate the user

I'm using spring Boot MVC Security with JPA Hibernate with Thymeleaf template engine. I'm trying to create a user login with some users already stored in the DB(MySQL). Whenever I use correct crede...

I’m using spring Boot MVC Security with JPA Hibernate with Thymeleaf template engine.
I’m trying to create a user login with some users already stored in the DB(MySQL).
Whenever I use correct credentials, its okay. Also when I use a correct username with the wrong password, it works as it should displaying an error message.
But when I give a non-existing username that’s not on the table(users) or leave the field blank, I have an error:

ERROR 11759 — [nio-8080-exec-5]
w.a.UsernamePasswordAuthenticationFilter : An internal error occurred
while trying to authenticate the user.»

Below are my codes that could be useful:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailServiceConfig myAppUserDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/home/**").hasAnyRole("ADMIN","USER")
                .and().formLogin()  //login configuration
                .loginPage("/login")
                .loginProcessingUrl("/app-login")
                .usernameParameter("app_username")
                .passwordParameter("app_password")
                .defaultSuccessUrl("/home")
                .and().logout()    //logout configuration
                .logoutUrl("/app-logout")
                .logoutSuccessUrl("/login")
                .and().exceptionHandling() //exception handling configuration
                .accessDeniedPage("/error");
    }
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        auth.userDetailsService(myAppUserDetailsService).passwordEncoder(passwordEncoder);
    }
}

Controller:

@Controller
@RequestMapping("/")
public class HomeController {
    @Autowired
    private UserInfoService userInfoService;
    @GetMapping("login")
    public ModelAndView login() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("login");
        return mav;
    }
    @GetMapping("home")
    public ModelAndView getAllUserArticles() {
        ModelAndView mav = new ModelAndView();
        mav.addObject("userArticles", userInfoService.getAllUserArticles());
        mav.setViewName("articles");
        return mav;
    }
    @GetMapping("error")
    public ModelAndView error() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("error");
        return mav;
    }
}

UserDetailsService

public class UserDetailServiceConfig implements UserDetailsService {
    @Autowired
    private UserInfoDao userInfoDAO;

    @Override
    public UserDetails loadUserByUsername(String userName)
            throws UsernameNotFoundException {
        UserInfo activeUserInfo = userInfoDAO.getActiveUser(userName);
        GrantedAuthority authority = new SimpleGrantedAuthority(activeUserInfo.getRole());
        UserDetails userDetails = (UserDetails)new User(activeUserInfo.getUserName(),
                activeUserInfo.getPassword(), Arrays.asList(authority));
        return userDetails;
    }
}

Error:

    ERROR 12337 --- [nio-8080-exec-5] w.a.UsernamePasswordAuthenticationFilter : An internal error occurred while trying to authenticate the user.

org.springframework.security.authentication.InternalAuthenticationServiceException: A granted authority textual representation is required
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:126) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:144) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:124) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:347) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:263) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]
Caused by: java.lang.IllegalArgumentException: A granted authority textual representation is required
    at org.springframework.util.Assert.hasText(Assert.java:181) ~[spring-core-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.security.core.authority.SimpleGrantedAuthority.<init>(SimpleGrantedAuthority.java:38) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at com.example.sample.configuration.UserDetailServiceConfig.loadUserByUsername(UserDetailServiceConfig.java:25) ~[classes/:na]
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    ... 45 common frames omitted

Здравствуйте. Помогите, пожалуйста, решить проблему.
Пытаюсь написать spring-security приложение для входа пользователей. Вся информация о них находится в mySQL.

Но вот какая проблема. При поптыке входа (видимо на стадии чтения данных из базы)
выбрасывается следующее

17:54:05,965 ERROR [org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter] (default task-17) An internal error occurred while trying to authenticate the user.: org.springframework.security.authentication.InternalAuthenticationServiceException: Could not open Hibernate Session for transaction; nested exception is java.lang.NoClassDefFoundError: org/hibernate/engine/transaction/spi/TransactionContext
	at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:126)
	at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:144)
	at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
	at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199)
	at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
	at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:121)
	at 
org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114)
	... 63 more
Caused by: java.lang.NoClassDefFoundError: org/hibernate/engine/transaction/spi/TransactionContext
	at org.springframework.orm.hibernate4.HibernateTransactionManager.isSameConnectionForEntireSession(HibernateTransactionManager.java:711)
	at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:445)
	... 71 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.engine.transaction.spi.TransactionContext from [Module "deployment.new-1.0-SNAPSHOT.war:main" from Service Module Loader]
	at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
	at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)
	at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)
	at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)
	... 73 more

Хибернейт настроен так

@Configuration
@EnableTransactionManagement
@ComponentScan({"operator.configuration"})
@PropertySource(value = {"classpath:application.properties"})
public class HibernateConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[]{"operator"});
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        return properties;
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(s);
        return txManager;
    }
}

Что не так?

UPD2

Caused by: java.lang.ClassCastException: org.springframework.orm.hibernate5.SessionHolder cannot be cast to org.springframework.orm.jpa.EntityManagerHolder
	at org.springframework.orm.jpa.EntityManagerFactoryUtils.doGetTransactionalEntityManager(EntityManagerFactoryUtils.java:221)
	at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:255)
	at com.sun.proxy.$Proxy166.createQuery(Unknown Source)
	at operator.dao.implementation.UserDAOImpl.getUserByEMAil(UserDAOImpl.java:55)
	at operator.services.implementation.UserServiceImpl.getUserByEMAil(UserServiceImpl.java:113)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
	at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
	at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
	at com.sun.proxy.$Proxy171.getUserByEMAil(Unknown Source)
	at operator.security.CustomUserDetailsService.loadUserByUsername(CustomUserDetailsService.java:28)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
	at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
	at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
	at com.sun.proxy.$Proxy176.loadUserByUsername(Unknown Source)
	at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114)
	... 63 more

На чтение 2 мин Обновлено 15.01.2023

Spring Security не понимаю, как работает?

Приветствую уважаемые форумчане.

У меня вопрос такого рода:

Подскажите пожалуйста, вот в Spring Security есть метод loadUserByUsername

как мы видим, мы передаем в userdetails.User параметры для аутентификации. На основе этих параметров, Spring Security нас авторизует. А что если запрашиваемого пользователя не существует? Тогда что делать? как Spring-у сообщить что такого пользователя нет?

Вот тут я что то не могу понять. Или я что то не так делаю?

  • Вопрос задан более двух лет назад
  • 230 просмотров

А что если запрашиваемого пользователя не существует? Тогда что делать? как Spring-у сообщить что такого пользователя нет?

Это вспомогательный хороший ответ, но пока не то что я ищу.

Смотрите. Я пытаюсь получить пользователя из базы данных вот таким методом

Я если честно, то я не знаю, правильно ли я делаю или нет. Дело в том, что когда я пытаюсь получить пользователя и если он есть, то всё замечательно, а если пользователя нет, то выскакивает ошибка

Вы можете из репозитория получить Optional пользователя

Ну а дальше, если ничего не найдено, то orElseThrow(new UsernameNotFoundException) ну или выполнить любое другое действие.

azerphoenix, Я так сделал. Просто сразу что то не допёр

Источник

Ошибка при входе пользователя, но не выкидывает

03.05.2016, 19:06. Показов 1373. Ответов 2


[http-apr-8080-exec-10] ERROR org.springframework.security.web.authentication.Us ernamePasswordAuthenticationFilter — An internal error occurred while trying to authenticate the user.
org.springframework.security.authentication.Intern alAuthenticationServiceException
at org.springframework.security.authentication.dao.Da oAuthenticationProvider.retrieveUser(DaoAuthentica tionProvider.java:126)
at org.springframework.security.authentication.dao.Ab stractUserDetailsAuthenticationProvider.authentica te(AbstractUserDetailsAuthenticationProvider.java: 143)
at org.springframework.security.authentication.Provid erManager.authenticate(ProviderManager.java:167)
at org.springframework.security.authentication.Provid erManager.authenticate(ProviderManager.java:192)
at org.springframework.security.web.authentication.Us ernamePasswordAuthenticationFilter.attemptAuthenti cation(UsernamePasswordAuthenticationFilter.java:9 3)
at org.springframework.security.web.authentication.Ab stractAuthenticationProcessingFilter.doFilter(Abst ractAuthenticationProcessingFilter.java:217)
at org.springframework.security.web.FilterChainProxy$ VirtualFilterChain.doFilter(FilterChainProxy.java: 330)
at org.springframework.security.web.authentication.lo gout.LogoutFilter.doFilter(LogoutFilter.java:120)
at org.springframework.security.web.FilterChainProxy$ VirtualFilterChain.doFilter(FilterChainProxy.java: 330)
at org.springframework.security.web.header.HeaderWrit erFilter.doFilterInternal(HeaderWriterFilter.java: 64)
at org.springframework.web.filter.OncePerRequestFilte r.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$ VirtualFilterChain.doFilter(FilterChainProxy.java: 330)
at org.springframework.security.web.context.SecurityC ontextPersistenceFilter.doFilter(SecurityContextPe rsistenceFilter.java:91)
at org.springframework.security.web.FilterChainProxy$ VirtualFilterChain.doFilter(FilterChainProxy.java: 330)
at org.springframework.security.web.context.request.a sync.WebAsyncManagerIntegrationFilter.doFilterInte rnal(WebAsyncManagerIntegrationFilter.java:53)
at org.springframework.web.filter.OncePerRequestFilte r.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$ VirtualFilterChain.doFilter(FilterChainProxy.java: 330)
at org.springframework.security.web.FilterChainProxy. doFilterInternal(FilterChainProxy.java:213)
at org.springframework.security.web.FilterChainProxy. doFilter(FilterChainProxy.java:176)
at org.springframework.web.filter.DelegatingFilterPro xy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterPro xy.doFilter(DelegatingFilterProxy.java:262)
at org.apache.catalina.core.ApplicationFilterChain.in ternalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.do Filter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invo ke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invo ke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBas e.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke( StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke (ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve. invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invok e(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.servic e(CoyoteAdapter.java:521)
at org.apache.coyote.http11.AbstractHttp11Processor.p rocess(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnect ionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.AprEndpoint$SocketProce ssor.doRun(AprEndpoint.java:2500)
at org.apache.tomcat.util.net.AprEndpoint$SocketProce ssor.run(AprEndpoint.java:2489)
at java.util.concurrent.ThreadPoolExecutor.runWorker( ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$Wrapping Runnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at com.service.impl.CustomUserDetailsService.loadUser ByUsername(CustomUserDetailsService.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Native MethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(De legatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.aop.support.AopUtils.invokeJoi npointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethod Invocation.invokeJoinpoint(ReflectiveMethodInvocat ion.java:190)
at org.springframework.aop.framework.ReflectiveMethod Invocation.proceed(ReflectiveMethodInvocation.java :157)
at org.springframework.transaction.interceptor.Transa ctionInterceptor$1.proceedWithInvocation(Transacti onInterceptor.java:99)
at org.springframework.transaction.interceptor.Transa ctionAspectSupport.invokeWithinTransaction(Transac tionAspectSupport.java:281)
at org.springframework.transaction.interceptor.Transa ctionInterceptor.invoke(TransactionInterceptor.jav a:96)
at org.springframework.aop.framework.ReflectiveMethod Invocation.proceed(ReflectiveMethodInvocation.java :179)
at org.springframework.aop.framework.JdkDynamicAopPro xy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy41.loadUserByUsername(Unknown Source)
at org.springframework.security.authentication.dao.Da oAuthenticationProvider.retrieveUser(DaoAuthentica tionProvider.java:114)
… 38 more

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



The error code «data 52e» suggests an invalid credential being used to connect to the LDAP server. See the list of codes below:

52e invalid credentials
530 not permitted to logon at this time
531 not permitted to logon at this workstation
532 password expired
533
534 account disabled
The user has not been granted the requested logon type at this machine
701 account expired
773 user must reset password
775 user account locked

1) Check if the user dn, base dn and password are correct. To check this please download JXplorer to connect to the LDAP Server using the configuration set in the js.externalAuth.properties file. To download Jxplorer:

http://jxplorer.org/downloads/users.html

Once you download the application connect using the details of the js.externalAuth.properties

Example
LDAP Base URL = ldap://1.2.3.4:389
LDAP Search Base DN = ou=UserAccounts,dc=test,dc=ca,dc=com
LDAP User DN = cn=usertest1,ou=Services,ou=UserAccounts,dc=test,dc=ca,dc=com

If you are able to log into the LDAP Server then it means the credentials are OK. If any errors, please check with the LDAP Administrator the correct details.

2) Update js.externalAuth.properties file with the correct details to log into LDAP Server

3) Restart Apache Tomcat Services

4) Log into JasperReports with the LDAP Server credentials

Теги:  spring boot

An internal error occurred while trying to authenticate the user.

Бэк -код ошибки только что изменил переднюю часть ошибки
Проверьте, что я написал

быстро написано в начале и напрямую стало Resultmap = «java.lang.long»


Интеллектуальная рекомендация

указатель-события: нет; решить проблему сбоя клика

На работе сделал выпадающий список. Фон стрелки вниз добавляется к form-select :: after, но при нажатии стрелки событие раскрывающегося списка не может быть запущено. Так что добавьтеpointer-events: n…

Как идея соединяет MySQL?

1. Открытая идея 2. Справа есть база данных, щелкните 3. Нажмите » +» 4. Продолжайте нажимать 5. Выберите MySQL 6. Введите, где находится база данных, имя пользователя, пароль, тестовое соед…

CSRF и SSRF

Введение в уязвимости CSRF CSRF (подделка межсайтовых запросов, подделка межсайтовых запросов) относится к использованию недействительной идентификационной информации жертвы (файлы cookie, сеансы и т….

Разработка управления приложениями

Получить всю информацию о приложении PackageManager Android управляет пакетами приложений через PackageManager, и мы можем использовать его для получения информации о приложениях на текущем устройстве…

Вам также может понравиться

Анализ исходного кода пула потоков -jdk1.8

openjdk адрес загрузки http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/tags Логические шаги пула потоков, с которыми поставляется Java, — это, в основном, следующие шаги: Реализация псевдокода Отправить ис…

Используйте инструменты в макете XML:

В макете, если некоторые фиксированные значения атрибута не установлены, некоторое представление не будет видно, когда будет видна макет. Все, что мы можем увидеть эффект предварительного просмотра, к…

Войдите в JVM

1. Введение в JVM 1.1 Концепция JVM Введение в виртуальную машину: JVM (аббревиатура от Java Virtual Machine. Java Virtual Machine.), JVM — это настраиваемый компьютер, которого на самом деле не сущес…

пользователи Linux и группы пользователей

Пользователь категория Профиль пользователь Root (Root пользователя) Команда Советы Упорядочить #, имеет самую высокую задачу разрешения любого разрешения файла недействительно для корневого пользоват…

Котлин Базовый — класс и атрибуты

Давайте напишем простой JavaBean класса Student в Java, только с одним свойством, имя. Тот же класс в Котлин это: PUBLIC в Котлин является видимость по умолчанию, поэтому его можно опустить. Этот вид …

Статьи по теме

  • [NPM] Error occurred while trying to proxy request
  • tomcat — An attempt was made to authenticate the locked user
  • org.postgresql.util.PSQLException: An I/O error occurred while sending to the backend.
  • An error occurred while collecting items to be installed
  • fatal error C1001: An internal error has occurred in the compiler
  • bundle install There was an error while trying to write to
  • java.lang.RuntimeException: An error occurred while executing doInBackground()
  • An error occurred while calling z:org.apache.spark.api.python.PythonRDD.collectAndServe.
  • An error occurred while collecting items to be installed session context was:(profile=DefaultProfile
  • eclipse—————- An error occurred while collecting items to be installed session context was

популярные статьи

  • Кордова копировать плагин Кордова-плагин-буфер обмена
  • О дизайне Android и его значении
  • Режим программных компонентов
  • npm
  • Vue Mobile Phone Picture Component Component
  • 0,96-дюймовый OLED-дисплей Изображение
  • Информация о контенте автоматически развернута, а мышь останавливается
  • Концепция Spring и система анализа псевдонимов исходного кода (2)
  • Re -Learning Record от входа в тюрьму [7]
  • Камень-ножницы для бумаги (машинный тест)

рекомендованная статья

  • Данные сайта веб-сайта бизнес-аналитика Python Reptile
  • KVM виртуальная машина примечания конфигурации
  • 2020-07-27 Комиксы Упаковка и скачать CRAC
  • В Windows, Maven частные службы Nexus строительства и эксплуатации
  • Разделение чтения-записи конфигурации Springboot (Mybatis)
  • Работа шесть
  • Luogu p3238 [hnoi2014] дорожная блокировка
  • Установка системы Windows System —- Windows7 Enterprise Edition Невозможно установить Net.framework4.52-4.6 Версия Win7 Solutions …
  • Fiber Optic Cable vs Wireless: Which One Would You Prefer
  • Stateful Future Transformation

Связанные теги

  • I/O error
  • postgresql в исключении запроса
  • 32767
  • fatal error c1001
  • ruby
  • gem
  • bundle
  • permission
  • Большие данные
  • hadoop

I have created UserDetailsServiceImpl. Here I get the user name and the role of this user. But I couldn’t understand what the problem was. I’ve tried the sql query in the database.


SecurityConfig.java

@EnableWebSecurity
@ComponentScan("com")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Bean
public BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
};

@Autowired
protected void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}


@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/login", "/", "/veteriner").permitAll().antMatchers("/**")
            .hasRole("ADMIN").and().formLogin().loginPage("/login").defaultSuccessUrl("/login/login-status-success")
            .failureUrl("/login/login-status-error").permitAll().usernameParameter("username")
            .passwordParameter("password").and().logout().logoutSuccessUrl("/logout-success")
            .invalidateHttpSession(true).permitAll().and().csrf();
}

LoginController.java

 @Controller
 @RequestMapping(value = "/login", method = RequestMethod.GET)
 public class LoginController {

 @GetMapping
 public ModelAndView home() throws Exception {
    ModelAndView mv = new ModelAndView();
    mv.setViewName("login");
    return mv;
}

@RequestMapping(path="/login-status-error",method = RequestMethod.GET)
@ResponseBody
public ModelAndView erorLogin() throws Exception {
    ModelAndView mv = new ModelAndView();
    mv.setViewName("main");
    return mv;
}

@RequestMapping(path="/login-status-succes",method = RequestMethod.GET)
@ResponseBody
public ModelAndView succesLogin() throws Exception {
    ModelAndView mv = new ModelAndView();
    mv.setViewName("veteriner");
    return mv;
}

}


@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

@Autowired
private UserService userService;

@Transactional(readOnly = true)
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    com.model.User user = userService.findByUsername(username);
    if (user == null) {
        throw new UsernameNotFoundException("User not found.");
    }

    User securityUser = new User(user.getUsername(), user.getPassword(), true, true, true, true,
            buildUserAuthority(user.getUserRoles()));
    return securityUser;
}

private List<GrantedAuthority> buildUserAuthority(List<User_role> userRoles) {
    Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

    for (User_role userRole : userRoles) {
        setAuths.add(new SimpleGrantedAuthority(userRole.getRole().getRoleName()));
    }

    List<GrantedAuthority> results = new ArrayList<GrantedAuthority>(setAuths);
    return results;
}

select user0_.id as id1_6_, user0_.email as email2_6_, user0_.password as password3_6_, user0_.username as username4_6_ from public.»User» user0_ where user0_.username=?
16:37:16.930 [http-nio-8186-exec-12] ERROR org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter — An internal error occurred while trying to authenticate the user.
org.springframework.security.authentication.InternalAuthenticationServiceException: java.util.ArrayList cannot be cast to com.model.User
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:123) ~[spring-security-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:144) ~[spring-security-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:175) ~[spring-security-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:200) ~[spring-security-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94) ~[spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:124) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:9.0.16]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:9.0.16]
at org.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:71) [log4j-web-2.11.1.jar:2.11.1]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:9.0.16]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:9.0.16]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200) [catalina.jar:9.0.16]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [catalina.jar:9.0.16]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [catalina.jar:9.0.16]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [catalina.jar:9.0.16]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [catalina.jar:9.0.16]
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668) [catalina.jar:9.0.16]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [catalina.jar:9.0.16]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [catalina.jar:9.0.16]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-coyote.jar:9.0.16]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-coyote.jar:9.0.16]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834) [tomcat-coyote.jar:9.0.16]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415) [tomcat-coyote.jar:9.0.16]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-coyote.jar:9.0.16]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [?:1.8.0_202]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [?:1.8.0_202]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-util.jar:9.0.16]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_202]
Caused by: java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.model.User
at com.dao.UserDaoImpl.findByUsername(UserDaoImpl.java:23) ~[classes/:?]
at com.service.UserServiceImpl.findByUsername(UserServiceImpl.java:26) ~[classes/:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_202]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_202]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_202]
at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.8.0_202]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294) ~[spring-tx-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at com.sun.proxy.$Proxy238.findByUsername(Unknown Source) ~[?:?]
at com.service.UserDetailsServiceImpl.loadUserByUsername(UserDetailsServiceImpl.java:29) ~[classes/:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_202]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_202]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_202]
at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.8.0_202]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294) ~[spring-tx-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at com.sun.proxy.$Proxy239.loadUserByUsername(Unknown Source) ~[?:?]
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:108) ~[spring-security-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
… 45 more


Я расширяю UsernamePasswordAuthenticationFilter, чтобы добавить настраиваемое поле для сохранения в сеансе.

public class AuthFilter extends UsernamePasswordAuthenticationFilter {

@Override
public Authentication attemptAuthentication(HttpServletRequest request,
        HttpServletResponse response) throws AuthenticationException {
    //String dbValue = request.getParameter("dbParam");
    //request.getSession().setAttribute("dbValue", dbValue);
    System.out.println("attempting to authentificate");
    while (request.getAttributeNames().hasMoreElements()) {
        String e = (String) request.getAttributeNames().nextElement();
        System.out.println("param name : " + e + " and param value : " + request.getAttribute(e));
    }

    return super.attemptAuthentication(request, response);
    }
}

И мой WebSecurityConfig

@Configuration
@EnableWebMvcSecurity
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;


@Bean
public AuthFilter customUsernamePasswordAuthenticationFilter()
        throws Exception {
    AuthFilter customUsernamePasswordAuthenticationFilter = new AuthFilter();
    customUsernamePasswordAuthenticationFilter
            .setAuthenticationManager(authenticationManagerBean());
   return customUsernamePasswordAuthenticationFilter;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.addFilterAfter(customUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

    http.exceptionHandling().accessDeniedPage("/403").and()
            .authorizeRequests().antMatchers("/login", "/public/**").permitAll()
            .antMatchers("/users/**").hasAuthority("ADMIN")
            .anyRequest()
            .authenticated().and().formLogin().loginPage("/login")
            .defaultSuccessUrl("/index").permitAll().and().logout()
            .permitAll();


    http.sessionManagement().maximumSessions(1)
            .expiredUrl("/login?expired").and()
            .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
            .invalidSessionUrl("/");
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws  Exception {
    auth.eraseCredentials(false)
    .userDetailsService(userDetailsService);
}

Фильтр сопоставления: ‘customUsernamePasswordAuthenticationFilter’ в: [/ *]

Поэтому я точно знаю, что фильтр добавлен правильно, но я никогда не могу распечатать, что внутри, поэтому он не вызывается при аутентификации.

Я использую Thymeleaf и не использую конфигурацию xml.

Как м. Дейнум предложил, я изменил свой UsernamePasswordAuthenticationFilter на AbstractAuthenticationProcessingFilter, названный super(new AntPathRequestMatcher("/login","POST"));
Изменил addFilterAfter на addFilterBefore и немного кода, и это сработало!

2 ответа

Лучший ответ

Предполагая, что вы используете последнюю версию Spring Boot (1.2.3), вы используете Spring Security 3.2.7. Эта версия отображает UsernamePasswordAuthenticationFilter на /j_spring_security_check. Однако при использовании конфигурации на основе Java это значение изменяется на /login.

Ваш по-прежнему сопоставлен со старым URL. Чтобы исправить это расширение, AbstractAuthenticationProcessingFilter добавьте конструктор без аргументов по умолчанию, который вызывает суперконструктор, который принимает RequestMatcher. Недостатком этого является то, что если вам все еще требуется (или вы хотите расширить) функциональные возможности UsernamePasswordAuthenticationFilter, вам придется его продублировать.

public AuthFilter() {
    super(new AntPathRequestMatcher("/login","POST"));
}

Другое решение — по-прежнему расширять UsernamePasswordAuthenticationFilter и вызывать setRequiresAuthenticationRequestMatcher оттуда.

public AuthFilter() {
    super();
    setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login","POST"));
}

Или вы вызываете этот метод из своего фабричного метода.

@Bean
public AuthFilter customUsernamePasswordAuthenticationFilter()
    throws Exception {
    AuthFilter customUsernamePasswordAuthenticationFilter = new AuthFilter();
    customUsernamePasswordAuthenticationFilter
        .setAuthenticationManager(authenticationManagerBean());
    customUsernamePasswordAuthenticationFilter
        .setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login","POST"));
    return customUsernamePasswordAuthenticationFilter;
}

Есть еще одна проблема с вашей конфигурацией: ваш фильтр никогда не будет выполнен, потому что он выполняется после значения по умолчанию UsernamePasswordAuthenticationFilter и аутентификация уже произошла, ваш фильтр никогда не будет выполняться. Убедитесь, что он выполняется до фильтра по умолчанию.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.addFilterBefore(customUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    ...
}


10

M. Deinum
18 Май 2015 в 05:10

Чтобы ваша настраиваемая реализация UsernamePasswordAuthenticationFilter работала, добавьте .loginProcessingUrl («/ dologin») в HttpSecurity в вашем WebSecurityConfig, здесь «/ dologin» — это значение атрибута действия элемента формы html:

@Override
//@Order(Ordered.HIGHEST_PRECEDENCE)
public void configure(HttpSecurity http) throws Exception { // @formatter:off
    http
        ...
        ...
        .formLogin().loginPage("/login")
   -->  .loginProcessingUrl("/dologin") <-- add here
        ...
   -->  .addFilterBefore(new AuthFilter(authenticationManagerBean()),UsernamePasswordAuthenticationFilter.class)
 }

Затем необходимо предоставить настраиваемую реализацию UsernamePasswordAuthenticationFilter:

public class AuthFilter extends UsernamePasswordAuthenticationFilter {

   AuthenticationManager authenticationManager;

   private boolean continueChainBeforeSuccessfulAuthentication = false;


   public AuthFilter( AuthenticationManager authenticationManager){
      this.authenticationManager = authenticationManager;
      //idk why I have to do this, otherwise it's null
      super.setAuthenticationManager(authenticationManager);
   }

    public AuthFilter() {}

   private SessionAuthenticationStrategy sessionStrategy = new NullAuthenticatedSessionStrategy();
   //path to which this filter will intercept
   RequestMatcher customFilterUrl = new AntPathRequestMatcher("/dologin"); <--

  //dofilter method is copied from AbstractAuthenticationProcessingFilter
  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
      HttpServletRequest request = (HttpServletRequest)req;
      HttpServletResponse response = (HttpServletResponse)res;
      //if no match then go to next filter
      if (!customFilterUrl.matches(request)) {
         chain.doFilter(request, response);
      } else {

        Authentication authResult;
        try {
            authResult = this.attemptAuthentication(request, response);
            if (authResult == null) {
                return;
            }

            this.sessionStrategy.onAuthentication(authResult, request, response);
        } catch (InternalAuthenticationServiceException var8) {
            this.logger.error("An internal error occurred while trying to authenticate the user.", var8);
            this.unsuccessfulAuthentication(request, response, var8);
            return;
        } catch (AuthenticationException var9) {
            this.unsuccessfulAuthentication(request, response, var9);
            return;
        }

        if (this.continueChainBeforeSuccessfulAuthentication) {
            chain.doFilter(request, response);
        }

        successfulAuthentication(request, response, chain, authResult);
    }
}

@Override
public Authentication attemptAuthentication(HttpServletRequest request, 
 HttpServletResponse response)
        throws AuthenticationException {

    System.out.println("Your prints"); <--

    return super.attemptAuthentication(request,response);
  }
}


1

S.Step
27 Сен 2019 в 07:37

Попробуйте добавить FetchType.EAGER в свойство ролей объекта пользователя.

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "users_roles", 
    joinColumns = @JoinColumn(name = "user_id"), 
    inverseJoinColumns = @JoinColumn(name = "role_id")
)
private Set<Role> roles;

Обновление: альтернативный рефакторинг с включенными привилегиями

Класс полномочий вместо класса роли

@Entity
@Table(name = "authority")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Authority implements GrantedAuthority {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToMany
    @JoinTable(
            name = "authorities_privileges",
            joinColumns = @JoinColumn(
                    name = "authority_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(
                    name = "privilege_id", referencedColumnName = "id"))
    private Collection<Privilege> privileges;

    public Authority() {
        super();
    }

    public Authority(final String name) {
        super();
        this.name = name;
    }

    public Authority(String name,
                     Collection<Privilege> privileges) {
        this.name = name;
        this.privileges = privileges;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Collection<Privilege> getPrivileges() {
        return privileges;
    }

    public void setPrivileges(Collection<Privilege> privileges) {
        this.privileges = privileges;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (obj.toString().equals(this.name)) {
            return true;
        }

        if (getClass() != obj.getClass()) {
            return false;
        }

        final Authority auth = (Authority) obj;
        if (this.name != null && this.name.equals(auth.name)) {
            return true;
        }

        return false;
    }

    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        builder.append("Role [name = ").append(name).append("]").append("[id = ").append(id).append("]");
        return builder.toString();
    }

    @Override
    @JsonIgnore
    public String getAuthority() {
        return name;
    }
}

Класс привилегий (необязательно)

@Entity
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Privilege {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    private String name;

    public Privilege() {
        super();
    }

    public Privilege(final String name) {
        super();
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Класс пользователя

@Entity
@Table(name = "user_account")
public class User implements UserDetails {

    @Id
    @Column(unique = true, nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "username")
    private String username;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "email")
    private String email;

    @JsonIgnore
    @Column(name = "password", length = 60)
    private String password;

    @Column(name = "enabled")
    private boolean enabled;

    @Column(name = "last_password_reset_date")
    private Timestamp lastPasswordResetDate;

    @Column(name = "is_using_2FA")
    private boolean isUsing2FA;

    @JsonIgnore
    @Column(name = "secret", length = 60)
    private String secret;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "user_authority",
            joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "authority_id", referencedColumnName = "id"))
    private Collection<Authority> authorities;

    public User() {
        this.secret = UUID.randomUUID().toString();
        this.enabled = false;
    }

    public User(Long id,
                String username, String firstName, String lastName,
                String email, String password,
                boolean enabled, Timestamp lastPasswordResetDate,
                boolean isUsing2FA, String secret,
                Collection<Authority> authorities) {
        this.id = id;
        this.username = username;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.password = password;
        this.enabled = enabled;
        this.lastPasswordResetDate = lastPasswordResetDate;
        this.isUsing2FA = isUsing2FA;
        this.secret = secret;
        this.authorities = authorities;
    }

    public Long getId() {
        return id;
    }

    public void setId(final Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(final String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(final String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(final String username) {
        this.email = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(final String password) {
        Date date = new Date();
        this.lastPasswordResetDate = new Timestamp(date.getTime());
        this.password = password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public boolean isUsing2FA() {
        return isUsing2FA;
    }

    public void setUsing2FA(boolean isUsing2FA) {
        this.isUsing2FA = isUsing2FA;
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public Timestamp getLastPasswordResetDate() {
        return lastPasswordResetDate;
    }

    public void setLastPasswordResetDate(Timestamp lastPasswordResetDate) {
        this.lastPasswordResetDate = lastPasswordResetDate;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = (prime * result) + ((username == null) ? 0 : username.hashCode());
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final User user = (User) obj;
        if (!username.equals(user.username)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        builder.append("User [id = ").append(id).append(", firstName = ").append(firstName).append(", lastName = ").append(lastName).append(", email = ").append(email).append(", password = ").append(password).append(", enabled = ").append(enabled).append(", isUsing2FA = ")
                .append(isUsing2FA).append(", secret = ").append(secret).append(", roles = ").append(authorities).append("]");
        return builder.toString();
    }
}

UserBuilder Класс

public class UserBuilder {
    private Long bId;
    private String bUsername;
    private String bFirstName;
    private String bLastName;
    private String bEmail;
    private String bPassword;
    private boolean bEnabled;
    private Timestamp bLastPasswordResetDate;
    private boolean bIsUsing2FA;
    private String bSecret;

    private Collection<Authority> bAuthorities;

    public UserBuilder() {
    }

    public UserBuilder(Long bId,
                       String bUsername, String bFirstName, String bLastName,
                       String bEmail, String bPassword, boolean bEnabled,
                       Timestamp bLastPasswordResetDate, boolean bIsUsing2FA, String bSecret,
                       Collection<Authority> authorities) {
        this.bId = bId;
        this.bUsername = bUsername;
        this.bFirstName = bFirstName;
        this.bLastName = bLastName;
        this.bEmail = bEmail;
        this.bPassword = bPassword;
        this.bEnabled = bEnabled;
        this.bLastPasswordResetDate = bLastPasswordResetDate;
        this.bIsUsing2FA = bIsUsing2FA;
        this.bSecret = bSecret;
        this.bAuthorities = bAuthorities;
    }

    public UserBuilder(User user) {
        this.bId = user.getId();
        this.bUsername = user.getUsername();
        this.bFirstName = user.getFirstName();
        this.bLastName = user.getLastName();
        this.bEmail = user.getEmail();
        this.bPassword = user.getPassword();
        this.bEnabled = user.isEnabled();
        this.bLastPasswordResetDate = user.getLastPasswordResetDate();
        this.bIsUsing2FA = user.isUsing2FA();
        this.bSecret = user.getSecret();
    }

    public User createUser() {
        return new User(bId,
                bUsername,
                bFirstName,
                bLastName,
                bEmail,
                bPassword,
                bEnabled,
                bLastPasswordResetDate,
                bIsUsing2FA,
                bSecret,
                bAuthorities
        );
    }


    public UserBuilder bId(Long bId) {
        this.bId = bId;
        return this;
    }

    public UserBuilder bUsername(String bUsername) {
        this.bUsername = bUsername;
        return this;
    }

    public UserBuilder bFirstName(String bFirstName) {
        this.bFirstName = bFirstName;
        return this;
    }

    public UserBuilder bLastName(String bLastName) {
        this.bLastName = bLastName;
        return this;
    }

    public UserBuilder bEmail(String bEmail) {
        this.bEmail = bEmail;
        return this;
    }

    public UserBuilder bPassword(String bPassword) {
        Date date = new Date();
        this.bLastPasswordResetDate = new Timestamp(date.getTime());
        this.bPassword = bPassword;
        return this;
    }

    public UserBuilder bEnabled(boolean bEnabled) {
        this.bEnabled = bEnabled;
        return this;
    }

    public UserBuilder bLastPasswordResetDate(Timestamp bLastPasswordResetDate) {
        this.bLastPasswordResetDate = bLastPasswordResetDate;
        return this;
    }

    public UserBuilder bIsUsing2FA(boolean bIsUsing2FA) {
        this.bIsUsing2FA = bIsUsing2FA;
        return this;
    }

    public UserBuilder bSecret(String bSecret) {
        this.bSecret = bSecret;
        return this;
    }

    public UserBuilder bAuthorities(Collection<Authority> bAuthorities) {
        this.bAuthorities = bAuthorities;
        return this;
    }
}

CustomUserDetailsService — класс

@Service("userDetailsService")
@Transactional
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @SuppressWarnings("unchecked")
    @Override
    public UserDetails loadUserByUsername(final String identity) throws UsernameNotFoundException {
        try {
            final User user = Optional.ofNullable(userRepository.findByEmail(identity)).orElseGet(() -> userRepository.findByUsername(identity));

            if (user == null) {
                throw new UsernameNotFoundException("No user found with username: " + identity);
            }

            //Collection<Authority> authorities = getAuthorities((Collection<Authority>) user.getAuthorities());
            Collection<Authority> authorities = getAuthorities((Collection<Authority>) user.getAuthorities());

            return new UserBuilder(user).bAuthorities(authorities).createUser();

        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    }

    private final Collection<Authority> getAuthorities(final Collection<Authority> authorityList) {
        return getGrantedAuthorities(getAuthorityList(authorityList));
    }

    private final List<String> getAuthorityList(final Collection<Authority> authorityList) {
        final List<String> authorities = new ArrayList<String>();

        for (final Authority authority : authorityList) {
            authorities.add(authority.getName());

            if (authority.getPrivileges() == null || authority.getPrivileges().isEmpty()) continue;

            // Add all Privileges as Authorities
            for (final Privilege item : authority.getPrivileges()) {
                authorities.add(item.getName());
            }
        }

        return authorities;
    }

    private final Collection<Authority> getGrantedAuthorities(final List<String> authorityList) {
        final List<Authority> grantedAuthorities = new ArrayList<Authority>();
        for (final String authority : authorityList) {
            grantedAuthorities.add(new Authority(authority));
        }
        return grantedAuthorities;
    }
}

Репо

public interface PrivilegeRepository extends JpaRepository<Privilege, Long> {

    Privilege findByName(String name);

    @Override
    void delete(Privilege privilege);

}

public interface RoleRepository extends JpaRepository<Authority, Long> {

    Authority findByName(String name);

    @Override
    void delete(Authority role);

}

public interface UserRepository extends JpaRepository<User, Long> {
    User findByEmail(String email);

    User findByUsername(String username);

    @Override
    void delete(User user);
}

Класс SetupDataLoader (необязательно)

@Component
public class SetupDataLoader implements ApplicationListener<ContextRefreshedEvent> {

    private boolean alreadySetup = false;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private PrivilegeRepository privilegeRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    BeerRepository beerRepository;

    @Override
    @Transactional
    public void onApplicationEvent(final ContextRefreshedEvent event) {
        if (alreadySetup) {
            return;
        }

        // == create initial privileges
        final Privilege userReadPrivilege = createPrivilegeIfNotFound("USER_READ_PRIVILEGE");
        final Privilege userWritePrivilege = createPrivilegeIfNotFound("USER_WRITE_PRIVILEGE");
        final Privilege beerReadPrivilege = createPrivilegeIfNotFound("BEER_READ_PRIVILEGE");
        final Privilege beerWritePrivilege = createPrivilegeIfNotFound("BEER_WRITE_PRIVILEGE");
        final Privilege passwordPrivilege = createPrivilegeIfNotFound("CHANGE_PASSWORD_PRIVILEGE");

        // == create initial roles
        final List<Privilege> adminPrivileges = new ArrayList<Privilege>(Arrays.asList(beerReadPrivilege, beerWritePrivilege, userReadPrivilege, userWritePrivilege, passwordPrivilege));
        final List<Privilege> userPrivileges = new ArrayList<Privilege>(Arrays.asList(beerReadPrivilege, beerWritePrivilege));
        final Authority adminAuthority = createRoleIfNotFound("ROLE_ADMIN", adminPrivileges);
        createRoleIfNotFound("ROLE_USER", userPrivileges);

        // == create initial user
        createUserIfNotFound("rdurden",
                "rdurden@example.com",
                "Rupert",
                "Durden",
                "ILikeBeer2!",
                new ArrayList<Authority>(Arrays.asList(adminAuthority)));

        alreadySetup = true;
    }

    @Transactional
    Privilege createPrivilegeIfNotFound(final String name) {
        Privilege privilege = privilegeRepository.findByName(name);
        if (privilege == null) {
            privilege = new Privilege(name);
            privilege = privilegeRepository.save(privilege);
        }
        return privilege;
    }

    @Transactional
    Authority createRoleIfNotFound(final String name, final Collection<Privilege> privileges) {
        Authority authority = roleRepository.findByName(name);
        if (authority == null) {
            authority = new Authority(name);
        }
        authority.setPrivileges(privileges);
        authority = roleRepository.save(authority);
        return authority;
    }

    @Transactional
    User createUserIfNotFound(final String username, final String email, final String firstName, final String lastName, final String password, final Collection<Authority> authorities) {
        User user = Optional.ofNullable(userRepository.findByEmail(email)).orElseGet(() -> userRepository.findByUsername(username));

        if (user != null) return user;

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, -1);
        Date lastMonthDate = cal.getTime();
        Timestamp lastMonthTimestamp = new Timestamp(lastMonthDate.getTime());

        user = new UserBuilder()
                .bAuthorities(authorities)
                .bUsername(username)
                .bFirstName(firstName)
                .bLastName(lastName)
                .bEmail(email)
                .bPassword(passwordEncoder.encode(password))
                .bIsUsing2FA(false)
                .bEnabled(true)
                .bLastPasswordResetDate(lastMonthTimestamp)
                .createUser();

        user = userRepository.save(user);
        return user;
    }
}

Понравилась статья? Поделить с друзьями:
  • An internal error occurred while attempting to perform this command holographic displays
  • An unexpected error has occurred while processing target service response перевод
  • An internal error occurred while attempting to perform this command essentials что делать
  • An unexpected error has occurred vegas pro
  • An internal error occurred while attempting to perform this command deluxemenus