首页 > 解决方案 > 通过 POST /login API 实现 Spring Security 登录

问题描述

我正在创建一个具有自己的登录/注册视图/页面的应用程序/网页。

我的后端服务使用 Java 并使用 Spring Security 来管理用户的身份验证。

基本目标是(来自应用程序):-

  1. 通过/registerAPI 注册用户。(注册页面已经在客户端)
  2. 显示登录页面(已经在客户端)。
  3. 点击/loginapi 以使用提供的用户名和密码对用户进行身份验证。(在 JSON POST 请求中提供)
  4. 成功后,返回一个 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 和教程,但似乎没有人回答这种情况。

如何做到这一点?

标签: javaspringspring-bootspring-security

解决方案


loginProcessingUrl("/path")是告诉 Spring 安全性处理凭据的路径。请注意,这不会将请求传递给您的 Controller 方法。

要显示自己的登录页面而不是默认页面,您应该做的是使用loginPage("/login"). 这是返回 HTML 页面的 GET 请求。

您可能对AuthenticationSuccessHandler 感兴趣。

参考这个例子


推荐阅读