Spring Boot自定义登录页面

4

我正在尝试为我的Bootstrap应用程序添加自定义登录页面。我正在遵循这个教程。但是我无法让它与我的自定义登录页面一起工作。

这是我的pom.xml:

...
 <dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-commons</artifactId>
 </dependency>
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
 </dependency>
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <scope>test</scope>
</dependency>
...

MvcConfig.java

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/index.html");

        registry.addViewController("/login").setViewName("login");
    }

}

FrontendApp.java:

import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;

import ch.qos.logback.classic.Logger;

 @SpringBootApplication
 @Import(value = MvcConfig.class)
 public class FrontendApp {

      private static Logger logger = (Logger) LoggerFactory.getLogger(FrontendApp.class);

      public static void main(String[] args) {

          SpringApplication app = new SpringApplication(FrontendApp.class);
          app.run(args);
     }

}

SecurityConfiguration.java

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;

    @Autowired
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
         auth.authenticationProvider(this.customAuthenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
         http
            .authorizeRequests()
            .antMatchers("/css/**").permitAll()
            .antMatchers("/resources/**").permitAll()
            .antMatchers("**").permitAll()
            .antMatchers("/login").permitAll()
        .anyRequest().authenticated().and()
        .formLogin()
        .loginPage("/login");
    }

}

我打开了所有的URL,以便检查是否可以看到“/login”。 CustomAuthenticationProvider.java

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {    

    private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationProvider.class);


    public CustomAuthenticationProvider() {
        logger.info("*** CustomAuthenticationProvider created");
    }

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

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        if(authentication.getName().equals("karan")  && authentication.getCredentials().equals("saman")) {
            List<GrantedAuthority> grantedAuths = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
            grantedAuths.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            return new UsernamePasswordAuthenticationToken(authentication.getName(), authentication.getCredentials(), grantedAuths);
         } else {
              return null;
         }
    }

}

当我尝试访问 localhost:8080/login 时,会出现以下错误:
Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.
There was an unexpected error (type=Internal Server Error, status=500).
Error resolving template "login", template might not exist or might not be accessible by any of the configured Template Resolvers

然而,当我尝试访问localhost:8080/时,它会成功重定向到我在MvcConfig.java中指定的index.html。

这是我的login.html代码:

   <html xmlns="http://www.w3.org/1999/xhtml" 
         xmlns:th="http://www.thymeleaf.org" 
         xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
         xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">

<head>
    <meta charset="utf-8" />
    <title>k</title> 
</head>

我将我的login.html文件复制到了/src/main/resources/templates、/src/main/webapp/ 和 /src/main/webapp/templates下,但仍然无法使用!


您的视图控制器配置必须拦截“登录”请求并重定向到不存在的“登录”页面,因此出现了错误。这将绕过thymeleaf视图解析器。您是否尝试从MvcConfig中删除以下行:registry.addViewController("/login").setViewName("login"); - Finbarr O'B
@FinbarrO'Brien 是的,我试过了。事实上,我尝试添加其他东西,比如login1,并将相应的login1.html放在模板中,但是我对那一个也得到了相同的错误。 - D3GAN
你是将应用程序构建为war文件还是可执行的jar文件? - Finbarr O'B
@FinbarrO'Brien 我正在使用嵌入式Tomcat,并将其构建为可执行的jar文件。 - D3GAN
1个回答

0

好的,这只是pom.xml中的一个简单错误。

<!--<resources>-->
        <!--<resource>-->
            <!--<directory>src/main/resources</directory>-->
            <!--<includes>-->
                <!--<include>*</include>-->
            <!--</includes>-->
            <!--<filtering>true</filtering>-->
        <!--</resource>-->
    <!--</resources>-->

我将这些(如您所见)从pom文件中注释掉后,它完美地工作了。至少上述代码可能对其他人有用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接