java - 通过 POST /login API 实现 Spring Security 登录
问题描述
我正在创建一个具有自己的登录/注册视图/页面的应用程序/网页。
我的后端服务使用 Java 并使用 Spring Security 来管理用户的身份验证。
基本目标是(来自应用程序):-
- 通过
/register
API 注册用户。(注册页面已经在客户端) - 显示登录页面(已经在客户端)。
- 点击
/login
api 以使用提供的用户名和密码对用户进行身份验证。(在 JSON POST 请求中提供) - 成功后,返回一个 cookie 用于下一个操作/api 调用以验证登录用户。
登录和注册 API 都是公开的。
这是我的春季安全配置
//all imports
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private PasswordEncoder passwordEncoder;
@Autowired
public SecurityConfig(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login", "/register").permitAll() //to allow these urls
.anyRequest().authenticated().and()
// dont want Spring's Login page to get rendered
.formLogin().loginProcessingUrl("/login").and().rememberMe();
}
@Override
@Bean
protected UserDetailsService userDetailsService() {
//for HTTP Basic Auth - but needs to be removed to implement Cookie based authentications
UserDetails userDetails = User.builder().
username("admin").
password(passwordEncoder.encode("admin")).
roles("ADMIN").
build();
return new InMemoryUserDetailsManager(userDetails);
}
}
我担心的是,loginProcessingUrl()
它不会将我的 URLhttps://<domain>/login
请求重定向到它的映射控制器方法,该方法在内部从 DB 获取用户并进行验证。POST api也https://<domain>/register
不起作用,它每次都要求登录。
浏览了所有 Spring DOC 和教程,但似乎没有人回答这种情况。
如何做到这一点?
解决方案
loginProcessingUrl("/path")
是告诉 Spring 安全性处理凭据的路径。请注意,这不会将请求传递给您的 Controller 方法。
要显示自己的登录页面而不是默认页面,您应该做的是使用loginPage("/login")
. 这是返回 HTML 页面的 GET 请求。
您可能对AuthenticationSuccessHandler 感兴趣。
参考这个例子
推荐阅读
- python - 如何在函数中使用 end="" with?
- tfs - TFS 2018 将 SharePoint 用于什么用途?
- r - diffinv 函数输出不是我想的那样
- python - 使用 sqlalchemy 的动态数据过滤器,它适用于给定值,但不适用于 NULL(None) 值
- flutter - 关于flutter的provider中出现的错误
- java - 运行 junit 时不支持的 major.minor 版本 52.0
- wordpress - 如何使用盐和密钥解密密码
- python - 在 python 中压缩和合并图像
- java - SimpleDateFormat.parse(date_string) 生成上一个日期
- pdf - PDF的大小使用python-multipart打破FastAPI?