自定义登录REST端点

时间:2020-11-04 19:10:43

标签: spring spring-security

我正在尝试更改默认的POST / login春季安全性端点,以登录到POST / api / users / login

我已经尝试通过

formLogin().loginProcessingUrl("/api/users/login")

formLogin().loginPage("/api/users/login")

但是没有用。我怎么做?我找不到描述它的教程或堆栈溢出答案。我还尝试阅读Spring Security文档,但也无济于事。

我的安全配置如下:

    private final MyUserDetailsService myUserDetailsService;

    private final PasswordEncoder passwordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        //go from most restrictive url to least restrictive, from single urls to /**
        httpSecurity.csrf().disable().cors().and()
                .addFilter(new JwtAuthenticationFilter(authenticationManager()))
                .addFilter(new JwtAuthorizationFilter(authenticationManager()))
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        //to allow h2 console page
        httpSecurity.headers().frameOptions().disable();
    }

1 个答案:

答案 0 :(得分:1)

在WebSecurityConfigurerAdapter类中,可以配置应重写的方法,如下所示:

@Override
protected void configure(HttpSecurity http) throws Exception { 
   http.csrf().disable()
        .exceptionHandling()
        .authenticationEntryPoint(
                               unAuthorizedResponseAuthenticationEntryPoint)
       .and().sessionManagement()           
       .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
       .and()
       .authorizeRequests()
       .anyRequest()
       .authenticated();
    http.addFilterBefore(authenticationTokenFilter,
                          UsernamePasswordAuthenticationFilter.class);


}

@Override
public void configure(WebSecurity webSecurity) throws Exception {
    webSecurity
            .ignoring().antMatchers(HttpMethod.POST, "/api/auth/login")
            .antMatchers(HttpMethod.OPTIONS, "/**")
            .and().ignoring()
            .antMatchers(HttpMethod.GET, "/").and().ignoring();
}

}

请参见方法:

public void configure(WebSecurity webSecurity) throws Exception

行:

webSecurity.ignoring().antMatchers(HttpMethod.POST, "/api/auth/login")

在这里放置自定义身份验证API端点!

然后您可以按照以下问题中的解释进行操作 How to use custom UserDetailService in Spring OAuth2 Resource Server?