Spring Security:仅当尚未通过表单登录进行身份验证时,才对REST api进行身份验证

时间:2020-08-17 13:46:20

标签: java spring spring-boot spring-security

全部

我有一个带有MVC和REST端点的spring boot应用程序。 Web应用程序的用户使用基于表单的身份验证(下面的第一配置)登录。还公开了将由外部应用程序调用的REST终结点-这些终结点使用JWT(下面的第二种配置)进行了身份验证。

用户登录后,我想调用REST端点(/ api / **)而不通过JWT进行身份验证,因为用户已经通过基于表单的auth登录。因此,我基本上只想在用户未通过身份验证的情况下使用JWT身份验证(SecurityContext没有身份验证)。我不确定如何实现。

非常感谢您的帮助。

谢谢

    @Configuration
    @Order(1)
    public static class UserRole1ConfigAdapter extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {

            http
                    .requestMatcher(new NegatedRequestMatcher(new AntPathRequestMatcher("/api/**")))
                    .authorizeRequests()
                    .antMatchers("/userrole1/**")
                        .hasRole(Role.USERROLE1.name())
                        .and()
                    .formLogin()
                        .loginPage("/userrole1/login")
                        .permitAll()
                        .loginProcessingUrl("/userrole1/login")
                        .defaultSuccessUrl("/userrole1/dashboard")
                        .and()
                    .logout()
                        .logoutUrl("/userrole1/logout")
                        .logoutSuccessUrl("/userrole1/login")
                        .invalidateHttpSession(true)
                        .deleteCookies("JSESSIONID")
                        .permitAll();
        }
    }
    @Configuration
    @Order(2)
    public static class RestConfigAdapter extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {

            http
                    .authorizeRequests()
                    .antMatchers("/api/register")
                        .permitAll()
                    .antMatchers("/api/userrole1/**")
                        .hasRole(Role.USERROLE1.name())
                    .antMatchers("/api/userrole2/**")
                        .hasRole(Role.USERROLE2.name())
                    .addFilter(new JwtAuthenticationFilter(authenticationManager(), jwtUtil, jwtConfig))
                    .addFilter(new JwtAuthorizationFilter(jwtUtil, jwtConfig, userDetailsService, authenticationManager()))
                    .sessionManagement()
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                        .and()
                    .csrf()
                        .disable();
        }
    }

1 个答案:

答案 0 :(得分:-2)

您已经有这个

.antMatchers(“ / api / register”) .permitAll()

这将允许未经身份验证的请求。 您还在寻找什么?