Ошибка входа в SpringBoot 2.1.4.RELEASE WebApp - PullRequest
0 голосов
/ 19 апреля 2019

У меня есть базовое приложение SpringBoot 2.1.4.RELEASE.Использование Spring Initializer, JPA, встроенного Tomcat, механизма шаблонов Thymeleaf и пакета в качестве исполняемого файла JAR.с помощью этих методов в файле конфигурации безопасности:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserSecurityService userSecurityService;

    /** The encryption SALT. */
    private static final String SALT = "asd31*(_)nof";

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(12, new SecureRandom(SALT.getBytes()));
    }



    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .authorizeRequests()
                .antMatchers(publicMatchers()).permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login").defaultSuccessUrl("/calzadas/list")
                .failureUrl("/login?error").permitAll()
                .and()
                .logout().permitAll();
    }

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


    private String[] publicMatchers() {

         /** Public URLs. */
        final String[] PUBLIC_MATCHERS = {
                "/webjars/**",
                serverContextPath + "/css/**",
                serverContextPath + "/js/**",
                serverContextPath + "/fonts/**",
                serverContextPath + "/images/**",                
                serverContextPath ,
                "/",
                "/error/**/*",
                "/console/**",
                SignupController.USER_VALIDATION_URL_MAPPING
        };

        return PUBLIC_MATCHERS;

    }   
}

и

@Service
public class UserSecurityService implements UserDetailsService {

    /** The application logger */
    private static final Logger LOG = LoggerFactory.getLogger(UserSecurityService.class);

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {

        LOG.info("Searching user with email: " + email);

        User user = userRepository.findByEmailIgnoreCase(email);

        LOG.info("user: {} " + user);

        if (null == user) {
            LOG.warn("Username {} not found", email);
            throw new UsernameNotFoundException("Username " + email + " not found");
        }
        return user;
    }
}

на login.html:

<div th:if="${param.error}" class="alert alert-danger alert-dismissible" role="alert">
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">x</span>
                        </button>
                        <p th:text="#{login.error.message}" />
                    </div>

с другой стороны, у меня естьRestController также для проверки:

@RestController
public class AuthenticationRestController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserSecurityService userSecurityService;

    @Autowired
    private EmailService emailService;

...
    /**
     * Authenticates the user. If something is wrong, an {@link AuthenticationException} will be thrown
     */
    private void authenticate(String username, String password) {

        Objects.requireNonNull(username);
        Objects.requireNonNull(password);

        if (StringUtils.isEmpty(username)) throw new AuthenticationException();
        if (StringUtils.isEmpty(password)) throw new AuthenticationException();

        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (DisabledException e) {
            throw new AuthenticationException("User is disabled!", e);
        } catch (BadCredentialsException e) {
            throw new AuthenticationException("Bad credentials!", e);
        }
    }
}

Я не знаю, почему при веб-аутентификации я не могу войти, я всегда получаю сообщение об ошибке, Неверные учетные данные?, но с RestController я могу войти, используя те же учетные данные, и я не знаю, как выяснить, в чем разница ...

<!DOCTYPE HTML>

<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head th:replace="pradera/common/header :: common-header" />  

<link rel="stylesheet"  th:href="@{/pradera/css/login.css}"  type='text/css' /> 

<!--  for the error login message box -->
<link th:href="@{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}"  rel="stylesheet" media="screen" /> 



<body>

<div class="wrap">
    <div class="login">
        <div class="logo"><img th:src="@{pradera/images/login.png}" width="224" height="71" alt="pradera Cloud" /></div>

            <form id="loginForm" th:action="@{/login}" method="post">

            <div class="row">
                <div class="col-md-6 col-md-offset-3 text-center">
                    <div th:if="${param.error}" class="alert alert-danger alert-dismissible" role="alert">
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">x</span>
                        </button>
                        <p th:text="#{login.error.message}" />
                    </div>
                    <div th:if="${param.logout}" class="alert alert-success alert-dismissible" role="alert">
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">x</span>
                        </button>
                        <p th:text="#${param.error}" />
                    </div>
                </div>            
            </div>

            <div class="input_label"><i class="fa fa-user"></i><input type="text" id="usernameId"   name="username" th:attr="placeholder=#{login.user.placeholder}" value="ricard.olle@gmail.com" /></div>
            <div class="input_label"><i class="fa fa-key"></i><input type="password" name="password" placeholder="Password"  value="Iconofcoil100@"/></div>

            <input type="submit" value="LOGIN" />

             </form>

        <div class="forget">
             <a th:href="@{/signup?planId=1}" th:text="#{login.register.text}">Register</a><br/>
            <br/>
        </div>
         <div class="forget">
                <a th:href="@{/forgotmypassword}" th:text="#{login.forgot.password.text}" >Do you forgot your password</a><br/>
            <br/>
            <br/>
            <br/>
            <br/>
           <span><a href="http://www.ideefeandwits.com/" th:text="#{powered.by}" target="_blank">Powered By Cryptsonic.io 2018  &copy;</a></span>
        </div>

    </div>
</div>

<!-- Js zone -->
<div th:replace="pradera/common/header :: before-body-scripts" ></div> 

<script th:src="@{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script> 


<script type="text/javascript">
$( document ).ready(function() {
    $( "#usernameId" ).focus();
});
$(document).keypress(function(e) {
    if(e.which == 13) {
        $( "#loginForm" ).submit();
    }
});
</script>


</body>
</html>

и

@Repository
public interface UserRepository extends CrudRepository<User, Long> {

    /**
     * Returns a User given a username or null if not found.
     * @param username The username
     * @return a User given a username or null if not found.
     */
    User findByUsernameIgnoreCase(String username);

    /**
     * Returns a User for the given email or null if none was found.
     * @param email The user's email
     * @return a User for the given email or null if none was found.
     */
    User findByEmailIgnoreCase(String email);
..
}

иЯ вижу в журналах, что пользователь извлекается:

2019-04-21 10:56  [http-nio-2233-exec-3] INFO  i.i.b.service.UserSecurityService.loadUserByUsername(39) - user: {} com.bonanza.backend.persistence.domain.backend.User@5a3163ef

1 Ответ

0 голосов
/ 21 апреля 2019

Попробуйте активировать ведение журнала отладки для безопасности Spring:

<logger name="org.springframework.security" level="debug" />
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...