Spring BOOT安全性:自定义登录页面从不进行身份验证

时间:2018-08-16 18:53:09

标签: java spring spring-boot spring-security

我正在使用Spring Boot开发一个Web应用程序。我已经使用了Spring Boot安全性。

如果我使用spring boot默认登录页面,则身份验证会按预期工作

但是它不适用于自定义登录页面

如果在websecurity.java中配置http端点时使用自定义登录页面,我将重定向到登录页面

在下面共享示例代码和我的诊断。

@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@EnableJpaRepositories(basePackageClasses = UserRepository.class)
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/resources/**").permitAll()
                .anyRequest().authenticated()
                .and().formLogin().loginPage("/loginPage")
                .permitAll();

    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(getPasswordEncoder());
    }

    private PasswordEncoder getPasswordEncoder() {
        return new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return charSequence.toString();
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return true;
            }
        };
    }
}

控制器:

@Controller
@EnableAutoConfiguration
@ComponentScan("com.shopping.service")
public class ShoppingController {

    @Autowired
    private ShoppingService service;

    @RequestMapping("/")
    public String index() {
        return "";
    }

    @RequestMapping("/loginPage")
    public String welcome(Map<String, Object> model) {
        return "login";
    }

    @RequestMapping(value = "/register")
    public String register(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @RequestMapping(value = "/submitRegistration", method = RequestMethod.POST)
    public String submitRegistration(@ModelAttribute User user) {
        User saved = service.save(user);
        System.out.println(saved);
        return "login";
    }

    @RequestMapping("/home")
    public String home() {
        return "home";
    }
}

login.html:

<form th:action="@{/loginPage}" method="post" th:object="${object}">
    <div class="form-group">
<label for="username">Email address:</label>
<input type="email" name="username" class="form-control" id="username">
   </div>
    <div class="form-group">
        <label for="password">Password:</label>
        <input type="password" name="password" class="form-control" id="password">
    </div>
    <div class="checkbox">
        <label><input type="checkbox"> Remember me</label>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
    <a href="/register" class="btn btn-default">Register</a>
</form>

UserDetailsS​​ervice,用于使用Crud Repo从数据库进行用户身份验证

public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepo;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        Optional<User> optionalUser = userRepo.findByEmail(userName);
        optionalUser.orElseThrow(() -> new UsernameNotFoundException("User Name not found"));
        UserDetailsImpl userDetails = optionalUser.map(user -> new UserDetailsImpl(user)).get();
        return userDetails;
    }

}

public class UserDetailsImpl extends User implements UserDetails {

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

    public UserDetailsImpl(User user) {
        this.setEmail(user.getEmail());
        this.setAge(user.getAge());
        this.setName(user.getName());
        this.setId(user.getId());
        this.setPassword(user.getPassword());
    }

    @Override
    public String getPassword() {
        return super.getPassword();
    }

    @Override
    public String getUsername() {
        return super.getEmail();
    }

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

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

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

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

}

1 个答案:

答案 0 :(得分:1)

您需要指定用户名的ID /名称和密码参数。

默认值为usernamepassword,但是您使用emailpassword

您可以在安全配置中更改默认设置:

//...
and().formLogin()
    .loginPage("/loginPage")
    .usernameParameter("email").passwordParameter("password")
//...

请注意,您只需要更改与默认设置不同的一种,我只想显示两种方法。

编辑1

第二个错误是表单操作,它必须是loginPage("/loginPage")方法指定的错误,因此在这种情况下:th:action="@{/loginPage}"

另外,密码标签的for属性错误(在这种情况下,必须为password)。

我对此进行了测试,现在对我有用。

编辑2

Spring安全性无法像您想象的那样起作用。它会拦截表单的操作URL,并将您重定向到您尝试登录之前访问的页面。如果要更改此页面,可以使用successForwardUrl()

在您的示例中:

//...
and().formLogin()
    .loginPage("/loginPage")
    .successForwardUrl("/home")
//...