无法返回login.html

时间:2019-06-19 11:35:04

标签: spring-boot thymeleaf

我尝试将thymleafspring一起使用。但是当我去/login时,我无法返回我的login.html。

这是我的控制者:

@GetMapping("/login")
public String login() {
    return "/login";//i also tried return "login" or "login.html
}

这是安全配置:

@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {


        auth
                .inMemoryAuthentication()
                .withUser("user").password(passwordEncoder().encode("password")).roles("USER")
                .and()
                .withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN");
    }

    @Override//when I comment those method, it works
    protected void configure(HttpSecurity http) throws Exception {
        http
//                .csrf().disable()//i also enabled this but still same
                .authorizeRequests()
                .antMatchers("/", "/home", "/about").permitAll()
                .antMatchers("/admin/**").hasAnyRole("ADMIN")
                .antMatchers("/user/**").hasAnyRole("USER")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }

这是login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
>
<head>
    <title>Spring Security Example </title>
</head>
<body>


<div class="container">

    <div class="row" style="margin-top:20px">
        <div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
            <form th:action="@{/login}" method="post">
                <fieldset>
                    <h1>Please Sign In</h1>

                    <div th:if="${param.error}">
                        <div class="alert alert-danger">
                            Invalid username and password.
                        </div>
                    </div>
                    <div th:if="${param.logout}">
                        <div class="alert alert-info">
                            You have been logged out.
                        </div>
                    </div>

                    <div class="form-group">
                        <input type="text" name="username" id="username" class="form-control input-lg"
                               placeholder="UserName" required="true" autofocus="true"/>
                    </div>
                    <div class="form-group">
                        <input type="password" name="password" id="password" class="form-control input-lg"
                               placeholder="Password" required="true"/>
                    </div>

                    <div class="row">
                        <div class="col-xs-6 col-sm-6 col-md-6">
                            <input type="submit" class="btn btn-lg btn-primary btn-block" value="Sign In"/>
                        </div>
                        <div class="col-xs-6 col-sm-6 col-md-6">
                        </div>
                    </div>
                </fieldset>
            </form>
        </div>
    </div>

</div>


</body>
</html>

我在代码中写为注释。

当我禁用该方法时:

protected void configure(HttpSecurity http) throws Exception {

我可以进入登录页面。

但是没有禁用,我只能在进入http://localhost:8080/login时看到字符串为login

3 个答案:

答案 0 :(得分:1)

从评论中发现;您需要使用@Controller而不是@RestController来注释控制器。这将告诉Spring返回视图。

然后return: "login";,您应该很好。

确保您的html页面位于src / main / resources或src / main / resources / templates中。

我不知道这是否会有所作为,但是在您的securityConfig中,可能在.loginPage("login")之后添加.loginProcessingUrl("/login").defaultSuccessUrl("/home", true);。我认为.permitAll()并不是必需的。

答案 1 :(得分:0)

protected void configure(HttpSecurity http)中实际发生的是,当用户尝试使用这些模式("/user/**") , ("/admin/**")(在上面的configure方法中已经提到过)访问url时,该方法将检查用户是否需要有权访问该特定网址。  对于您来说,要访问("/admin/**"),他/她应该具有管理员角色。如果当前用户试图访问该URL ("/admin/**")具有管理员角色,则将其定向到所需页面。如果用户没有管理员权限,那么他将被定向到您的登录页面,该页面在您的方法中使用.formLogin().loginPage("/login")进行了描述。因此,如果要使用现有代码访问登录页面,则必须将控制器@GetMapping("/login")中的url模式更改为该模式("/user/**") , ("/admin/**")之一。 以上是注释protected void configure(HttpSecurity http)时您的代码运行正常的原因。

答案 2 :(得分:-1)

您必须配置模板引擎

一个示例bean配置:

    @Bean
public SpringResourceTemplateResolver templateResolver(){
    // SpringResourceTemplateResolver automatically integrates with Spring's own
    // resource resolution infrastructure, which is highly recommended.
    SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
    templateResolver.setApplicationContext(this.applicationContext);
    templateResolver.setPrefix("/WEB-INF/templates/");
    templateResolver.setSuffix(".html");
    // HTML is the default value, added here for the sake of clarity.
    templateResolver.setTemplateMode(TemplateMode.HTML);
    // Template cache is true by default. Set to false if you want
    // templates to be automatically updated when modified.
    templateResolver.setCacheable(true);
    return templateResolver;
}

@Bean
public SpringTemplateEngine templateEngine(){
    // SpringTemplateEngine automatically applies SpringStandardDialect and
    // enables Spring's own MessageSource message resolution mechanisms.
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(templateResolver());
    // Enabling the SpringEL compiler with Spring 4.2.4 or newer can
    // speed up execution in most scenarios, but might be incompatible
    // with specific cases when expressions in one template are reused
    // across different data types, so this flag is "false" by default
    // for safer backwards compatibility.
    templateEngine.setEnableSpringELCompiler(true);
    return templateEngine;
}