首页 > 解决方案 > 如何在 Spring Security 中通过 jdbc 身份验证使用自定义登录页面

问题描述

当我收到获取请求时,我无法打开我的自定义登录页面。我配置了 HttpSecurity,但它显示的是“登录”字符串而不是 login.jsp。

我在 pom.xml 文件中的 application.properties 和 jsp 依赖项中添加了以下代码。但无论如何它都不起作用。

spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp

安全配置.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Bean
    @ConfigurationProperties("spring.datasource")
    public DataSource ds(){
        return DataSourceBuilder.create().build();
    }

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

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.jdbcAuthentication().dataSource(dataSource)
                .authoritiesByUsernameQuery("select username, role from myusers where username = ?")
                .usersByUsernameQuery("select username, password, 1 as enabled from myusers where username = ?");
    }

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/jsp/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

}

主控制器.java

@RestController
public class MainController {


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

    @RequestMapping("/list_users")
    public String showUsers(){
        return "This is the list of users";
    }

    @RequestMapping("addUser")
    public String addUser(){

        return "User is added successfully";
    }

}



登录.jsp

<h1><center>Give your login details</center></h1>
<form method="post" action="check_password">
    User name:<input type="text" name="username"><br>
    Password:<input type="password" name="password"><br>
    Submit <input type="submit" value="Submit">
</form>


我想打开我的自定义 login.jsp 页面而不是字符串。欢迎任何建议!

标签: spring-bootjspspring-security

解决方案


你可以理解@RestController的含义


推荐阅读