如何在 Spring Security 中通过 jdbc 身份验证使用自定义登录页面
Posted
技术标签:
【中文标题】如何在 Spring Security 中通过 jdbc 身份验证使用自定义登录页面【英文标题】:How to use Custom Login Page in Spring Security with jdbc authentication 【发布时间】:2020-02-23 11:41:33 【问题描述】:当我收到获取请求时,我无法打开我的自定义登录页面。我配置了 HttpSecurity,但它显示的是“登录”字符串而不是 login.jsp。
我在 pom.xml 文件中的 application.properties 和 jsp 依赖项中添加了以下代码。但无论如何它都不起作用。
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
SecurityConfig.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;
MainController.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";
login.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 页面而不是字符串。欢迎任何建议!
【问题讨论】:
@您收到异常或其他情况?您是如何尝试进入登录页面的? 不,当我使用 localhost:8080/list_users url 时,我没有遇到任何异常,它只显示登录字而不是 login.jsp 页面 【参考方案1】:你可以理解@RestController的含义
【讨论】:
谢谢先生。我需要 @Controller 而不是 RestController以上是关于如何在 Spring Security 中通过 jdbc 身份验证使用自定义登录页面的主要内容,如果未能解决你的问题,请参考以下文章
如何在spring security oauth2授权服务器中通过jwt令牌获取用户信息?
Spirng Cloud Gateway中通过Spring security + WebFlux 实现权限认证
如何通过 XML 配置仅针对特定 URL 模式在 Spring Security 4 中禁用 CSRF?
Spring 3.1 中通过 IP 地址进行身份验证:最聪明的方法是啥?