Spring Security简单登录页面无法登录

时间:2019-03-22 19:40:02

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

所以我试图在Spring Boot and Security的帮助下创建简单的登录页面。因此,我目前拥有的是自定义登录页面,以及一个用户和一个角色的内存身份验证。 问题是,当我输入正确的用户名/密码时,spirng不会将其验证为有效数据,而是再次将我重定向到登录页面,但这一次是:/login#error

在客户端,我正在使用百里香。

表单摘要:

<form th:action="@{/perform_login}" method="post">
    <input name="user" placeholder="Username" /> <br /> 
    <input name="pass" placeholder="Password" /> <br /> 
    <input type="submit" value="Login" />
</form>

配置类:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()//
            .withUser("root").password("root").roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests() //
                .antMatchers("/").hasRole("USER") //
                .antMatchers("/login*").permitAll().and() //
                .formLogin() //
                .loginPage("/login")//
                .loginProcessingUrl("/perform_login")//
                .and()//
                .logout()//
                .permitAll();
    }

}

控制器很简单

@Controller
@RequestMapping("/login")
public class LoginController {

    @GetMapping
    public String getLoginPage() {
        return "login";
    }
}

知道我在做什么错吗?

2 个答案:

答案 0 :(得分:1)

(对我而言)最简单的方法是制作一个@Bean并使用WebSecurityConfigurerAdapter并实现WebMvcConfigurer来配置所有步骤,而只需几个步骤。这是有史以来最小的例子:

@Configuration
@SpringBootApplication
public class DemoApplication implements WebMvcConfigurer {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Controller
    public class HomeController {

        @RequestMapping(value = "/", method = RequestMethod.GET)
        public String home(Model model, Authentication authentication, Principal principal) {
            if (authentication == null) {
                return "forward:/login";
            } else {
                model.addAttribute("user", principal.getName());
                return "home";
            }
        }
    }

    @Bean
    public WebSecurityConfigurerAdapter webSecurityConfig() {
        return new WebSecurityConfigurerAdapter() {
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http.csrf().disable().authorizeRequests()
                        .anyRequest().authenticated()
                        .and().formLogin().loginPage("/login")
                        .defaultSuccessUrl("/")
                        .permitAll()
                        .and().logout().permitAll();
                http.headers().frameOptions().disable();
            }

            @Override
            protected void configure(AuthenticationManagerBuilder builder) throws Exception {
                builder.authenticationProvider(new AuthenticationProvider() {
                    @Override
                    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                        String username = authentication.getName();
                        String password = authentication.getCredentials().toString();
                        if (username.equals("username") && password.equals("password")) {
                            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
                            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
                            return new UsernamePasswordAuthenticationToken(username, password, grantedAuthorities);
                        }
                        throw new AuthenticationServiceException("Invalid credentials.");
                    }

                    @Override
                    public boolean supports(Class<?> authentication) {
                        return authentication.equals(UsernamePasswordAuthenticationToken.class);
                    }
                });
            }
        };
    }

    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/login").setViewName("login");
    }
}

您说过您正在使用thymeleaf,所以可以说您的login.html格式将如下所示:

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>login example</title>
</head>
<body>
<form th:action="@{/login}" method="post">
    <input name="username" placeholder="Username"/> <br/>
    <input name="password" placeholder="Password"/> <br/>
    <input type="submit" value="Login"/>
</form>
</body>
</html>

登录后进入home.html页面:

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>home page</title>
</head>
<body>
Hello, <span th:text="${user}"></span><br>
<a href="/logout"> sign out</a>
</body>
</html>

答案 1 :(得分:-1)

我认为configure函数是错误的。如果您查看此tutorial会有所帮助。

查看您的代码,我相信有两个问题:

  1. 您允许通过身份验证的用户访问的页面错误。 尝试更改:
.antMatchers("/").hasRole("USER") //

收件人:

.antMatchers("/**").hasRole("USER") //

这意味着通过角色“ USER”进行身份验证的用户可以访问任何页面。在您的示例中,只能访问站点的根。

  1. 您应该对要设置的密码进行编码。

以下摘自上述教程:

.withUser("user1").password(passwordEncoder().encode("user1Pass")).roles("USER")

我可能错过了一些东西,所以请看一下教程。去年我第一次尝试设置Spring Security时,对我来说效果很好。

相关问题