Spring Security总是302

时间:2017-07-18 20:31:18

标签: spring spring-boot spring-security

我正在尝试将Spring Security放在Spring Boot项目中,但是当我尝试登录时,服务器总是返回302.

package it.expenses.expenses;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers( "/getHomePage").permitAll()
                .anyRequest().fullyAuthenticated()
                .and()
                .formLogin()
                .loginPage("/getLoginPage")
                .loginProcessingUrl("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .defaultSuccessUrl("/getHomePage")
                .permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/", "/resources/static/**").permitAll()
                .anyRequest().authenticated();


    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/script/**");
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }
}

实际上控制器只需返回模板。

这是登录页面

  <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <title> Spring Boot MVC Security using Thymeleaf </title>
    <link rel="stylesheet" href="/css/styles.css"/>
</head>
<body>
<h3> Spring Boot MVC Security using Thymeleaf </h3>
<p th:if="${param.error}" class="error">
    Bad Credentials
</p>
<form action="login" method="POST">
    User Name : <input type="text" name="username"/> <br/><br/>
    Password: <input type="password" name="password"/> <br/><br/>
    <input type="submit" value="Login"/>
</form>
</body>
</html>

UserDetailService:

@Service
public class UserDetailsServiceImpl implements UserDetailsService{

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String userName)
            throws UsernameNotFoundException {
        Users user = userDao.getActiveUser(userName);
        GrantedAuthority authority = new SimpleGrantedAuthority(user.getRole());
        UserDetails userDetails = new User(user.getUsername(),
                user.getPassword(), Arrays.asList(authority));
        return userDetails;
    }
}

这是项目https://github.com/StefanoPisano/expenses

1 个答案:

答案 0 :(得分:1)

您的安全配置有效,但我无法看到的是您在Users表中保存的记录。

示例

+--------+---------+--------------------------------------------------------------+------+----------+
| idUser | enabled | password                                                     | role | username |
+--------+---------+--------------------------------------------------------------+------+----------+
|      1 |       1 | password                                                     | USER | user     |
|      2 |       1 | $2a$10$eriuZaZsEWKB3wcpPMyexe4Ywe1AX9u148nrLmTTEIq6ORdLNiyp6 | USER | user2    |
+--------+---------+--------------------------------------------------------------+------+----------+

由于您已启用密码编码:

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
   BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
   auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}

您必须将编码密码存储在Users表中(而不是纯文本密码)

上面的示例数据显示useruser2具有相同的密码(一个纯文本,另一个编码)。如果user尝试登录,您将获得BadCredentialsException,因为BCryptPasswordEncoder需要编码密码