html - Spring Security 自定义登录页面辅助
问题描述
我一直在尝试正确配置它,但是我遇到了一些困难,我相信这是一个我没有看到的小修复。默认的 spring 安全登录页面工作得很好,但我无法让自定义 html 呈现。它只是将获取映射“登录”作为字符串读取。任何帮助将不胜感激!
1.安全配置
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService myUserDetailsServices;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailsServices);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().
authorizeRequests()
.antMatchers("/admin").hasRole("ADMIN")
.antMatchers("/user").hasAnyRole("ADMIN", "USER")
.antMatchers("/").permitAll()
.and().formLogin()
.loginPage("/login")
.permitAll();
}
@Bean
public PasswordEncoder getPasswordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}
3.主控制器
@RestController
@CrossOrigin(origins="http://localhost:4200")
public class MainController {
private UserRepository userRepository;
private UserDetailsService myUserDetailsServices;
public MainController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@GetMapping("/")
public String home() { return ("<h1>Welcome</h1>");
}
@GetMapping("/login")
public String login() { return ("login");
}
@GetMapping("/user")
public String user() {
return ("<h1>Welcome User</h1>");
}
@GetMapping("/admin")
public String admin() {
return ("<h1>Welcome Admin</h1>");
}
@GetMapping("/all")
public @ResponseBody Iterable<User> getAllUsers() {
// This returns a JSON or XML with the users
return userRepository.findAll();
4.login.html
<html xmlns:th="http://www.thymeleaf.org" xmlns:tiles="http://www.thymeleaf.org">
<head>
<title tiles:fragment="title">Login</title>
</head>
<body>
<div tiles:fragment="content">
<form name="f" th:action="@{/login}" method="post">
<fieldset>
<legend>Please Login</legend>
<div th:if="${param.error}" class="alert alert-error">
Invalid username and password.
</div>
<div th:if="${param.logout}" class="alert alert-success">
You have been logged out.
</div>
<label for="username">Username</label>
<input type="text" id="username" name="username"/>
<label for="password">Password</label>
<input type="password" id="password" name="password"/>
<div class="form-actions">
<button type="submit" class="btn">Log in</button>
</div>
</fieldset>
</form>
</div>
</body>
</html>
解决方案
更改@RestController
为@Controller
.
推荐阅读
- arrays - 空手道:我可以迭代 Json 数组响应并执行一些条件语句吗
- c# - 从 base64 超时请求转换文件
- python - 为什么python在执行完成后会丢弃错误
- python - Google Colab - 如何比较两张照片
- node.js - 在 NodeJS 中从 XML 生成友好的 JSON
- html - HTML 中心图像和下面的文本段落
- java - Java:重写字节码以添加接口的安全性
- oracle - ORA-01407: 无法在 DB 中将字段更新为 NULL
- python - Python:错误:命令出错,退出状态为 1:python setup.py egg_info 检查日志以获取完整的命令输出
- laravel - Laravel 删除挂起的迁移执行