有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java禁用特定URL Spring的基本身份验证

我是Spring新手,我需要为我的rest控制器的8/10 URL启用基本身份验证,另外2个应该可以在没有任何基本身份验证的情况下访问。 我使用gradle按应用程序构建,因此不涉及xml文件。(我看到了一些使用web.xml的解决方案,但我没有) 以下是我的web安全配置:

 @Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
        web.ignoring().antMatchers("/abcd/**");

    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("password");

    }
}

这是我的控制器:

    @RestController
@RequestMapping(value = "/abcd")
public class PaymentController implements ElasticSearchConstants {

    @RequestMapping(value = "/sample", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public static void authExpemtedController(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //do something
    }
}

我试过上网。忽略()。antMatchers(“/abcd/”);没有帮助。当我从邮递员那里尝试时,总是出现401错误: { “时间戳”:149274727955, “状态”:401, “错误”:“未经授权”, “消息”:“访问此资源需要完全身份验证”, “路径”:“/abcd/sample” }

我需要公开这样一个API,它不需要任何身份验证,而其他API需要进行身份验证

提前谢谢你的帮助

更新: 我知道http。授权请求()。蚂蚁匹配器(“/abcd”)。permitAll() 此方法仅允许任何用户访问。我根本不想向这个API传递任何用户信息


共 (1) 个答案

  1. # 1 楼答案

    您可能需要参考Section 5.4 Authorize Requests of the Spring Security docs

    Our examples have only required users to be authenticated and have done so for every URL in our application. We can specify custom requirements for our URLs by adding multiple children to our http.authorizeRequests() method. For example:

    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()                                                                                    
                .antMatchers("/resources/**", "/signup", "/about").permitAll()                                  
                .antMatchers("/admin/**").hasRole("ADMIN")                                                  
                .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")                        
                .anyRequest().authenticated()
                .and()
            // ...
            .formLogin();
    }