【问题标题】:Spring Security make username and password auth at specific pathSpring Security 在特定路径进行用户名和密码验证
【发布时间】:2018-06-27 14:18:12
【问题描述】:

我的 spring-boot 项目基于 REST 和 JWT 身份验证。现在我想禁用特定路径的 JWT 身份验证,而不是通过简单的用户名和密码进行身份验证。可以实现吗?

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().exceptionHandling()
                .authenticationEntryPoint(restAuthenticationEntryPoint())
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers("/login/**").permitAll()
                .antMatchers("/register/**").permitAll()
                .antMatchers("/api/jwt/**").authenticated()
                .anyRequest().authenticated().and()
                .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class).csrf().disable();
    }

我想通过用户名和密码添加身份验证,例如添加到“/api/data/**”。

编辑:

我的第一个配置是@Order(1)

 @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("abc").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/api/data/**").hasRole("ADMIN")
                .and()
                .httpBasic()
                .and()
                .csrf().disable();
    }

它可以工作,但是当执行对 api/data/** 具有正确凭据的请求时,jwtAuthenticationFilter() 也会触发。

【问题讨论】:

    标签: spring authentication spring-security


    【解决方案1】:

    实现 AuthenticationProvider 类以使用用户名和密码进行自定义身份验证。然后使用身份验证提供程序 -

        @Autowired
        private AuthenticationProvider authenticationProvider;
    
        @Autowired
        @Override
        protected void configure(
                @NotNull AuthenticationManagerBuilder auth) {
            auth.authenticationProvider(authenticationProvider);
        }
    
        @Override
        protected void configure(
                HttpSecurity http) throws
                Exception {
            http.requestMatchers()
                .antMatchers("/api/data/**")
                .and()
                .authorizeRequests()
                .anyRequest()
                .permitAll()
                .and()
                .csrf()
                .disable()
                .formLogin().disable()
                .and()
               .authenticationProvider(authenticationProvider);
        }
    

    【讨论】:

      猜你喜欢
      • 2019-09-18
      • 2016-04-30
      • 2020-01-18
      • 2012-03-07
      • 2014-11-09
      • 2012-02-08
      • 2017-10-16
      • 2010-11-13
      • 2021-12-05
      相关资源
      最近更新 更多