SpringBoot 2.1.4.RELEASE WebApp中的登录错误

时间:2019-04-19 07:31:43

标签: java spring spring-boot spring-mvc spring-security

我有一个基本的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);
        }
    }
}

我不知道为什么使用Web身份验证无法登录,总是出现错误,凭证错误? ,但是使用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 :(得分:0)

尝试为Spring安全性激活调试日志记录:

<logger name="org.springframework.security" level="debug" />
相关问题