java - SpringSecurity 自定义登录功能不适用于 SpringBoot 和 REST api
问题描述
我尝试使用自定义登录页面实现登录功能,但不幸的是它不起作用..我也找不到原因..可能我不完全了解 SpringSecurity 机制。看起来提交按钮什么都不做。我的代码如下。我会很乐意提供帮助的。
登录.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>test login page</h1>
<form name="login" action="/login" method="post">
User: <input type="text" name="username"/>
Password: <input type="password" name="password"/>
<input name="submit" type="submit" value="LOGIN"/>
<hr>
<button id="loginAsGuest">Login as a guest</button>
</form>
</body>
</html>
WebSecurityConfig.java:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}admin").roles("ADMIN")
.and()
.withUser("userguest").password("{noop}userguest").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/").hasAnyRole("ADMIN")
.antMatchers("/").hasAnyRole("USER")
.antMatchers("/login*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login.html")
.defaultSuccessUrl("/bookmarks-app/index.html", true)
.failureUrl("/login.html")
.and()
.logout().permitAll().logoutRequestMatcher(new AntPathRequestMatcher("/logout")
);
}
}
解决方案
只是指出一些事情。
hasAnyRole支持多个角色,所以你可以这样写.antMatchers("/**").hasAnyRole("ADMIN", "USER")
如果你放 /** 每个休息服务都会触发角色检查,如果你只放 / 只有 /rest 服务会触发检查。
删除 .antMatchers("/login*").permitAll()
并替换.loginPage("/login.html")
为.loginPage("/login").permitAll()
最后,您的配置将如下所示:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/**").hasAnyRole("ADMIN", "USER")
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login.html").permitAll().loginProcessingUrl("/perform_login")
//No need to add a LoginController.
// Needed because if you don't put this, when you call the POST to login you will be redirected to the login.html page.
.defaultSuccessUrl("/bookmarks-app/index.html", true)
.failureUrl("/login.html").permitAll()
.and()
.logout().permitAll().logoutRequestMatcher(new AntPathRequestMatcher("/logout")
);
}
如果您的登录页面在资源中,请不要忘记正确配置 ResourceHandler。
资料来源:
https://docs.spring.io/spring-security/site/docs/4.1.3.RELEASE/guides/html5/form-javaconfig.html
推荐阅读
- python - Python:删除列中的相似字符串
- laravel - Laravel 哨兵设置环境
- python - 为什么`list.extend()`在结果列表中交错`None`s?
- c# - Azure Web App Service 支持哪些适用于 .NET 核心的图像大小调整库?
- css - 如何解决这个 z-index 错误?
- html - 文本跳转到下一行的 CSS 表格填充问题
- jquery - 单击外部后在输入字段中输入时删除美元符号需要在jQuery中显示美元符号
- haskell - 如何使用 concatMap 将列表理解转换为版本?
- symfony - 我正在使用 Nelmio_cors,但我收到 POST 请求的 500 错误,即使我收到了对 GET 请求启用 CORS 的响应
- docker - 无法在 Google-Colab 中启动 docker