java - Spring REST 安全 : Enable Basic Authentication only on a specific endpoint

标签 java spring spring-mvc spring-security spring-restcontroller

我已经为我的 REST API 配置了 Spring Security(使用 HeaderHttpSessionStrategy)。

我的“WebSecurityConfigurerAdapter”实现如下所示。

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

        http

            .csrf().disable()

            .authorizeRequests()
                .antMatchers("/user/**").authenticated()
                .antMatchers("/**").permitAll()

                .and()
            .requestCache()
                .requestCache(new NullRequestCache())
                .and()

            .httpBasic()
            ;

    }

现在,我如何配置“HttpSecurity”对象,以便基本身份验证仅适用于特定端点。

例如:

/user/login :基本身份验证只能在此端点上进行。成功完成身份验证后,返回 x-auth-token header 。

/user/create :客户端不能在此端点上进行身份验证。应该只返回 401。只能使用使用/user/login 创建的“x-auth-token”进行访问端点。

最佳答案

您可以定义多个 WebSecurityConfigurerAdapter。具有请求匹配器以限制对 /user/login 的适用性的更高优先级之一,例如:http.requestMatcher(new AntPathRequestMatcher("/user/login")),以及另一个作为其余的包罗万象。您可以省略 requestMatcher 以使 http 定义不受限制。

关于java - Spring REST 安全 : Enable Basic Authentication only on a specific endpoint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40539337/

相关文章:

java - Spring 中 DynamoDB 的事务策略

java - 如何在Spring RestTemplate中发送调用者的IP地址

java - 将 JPA 与 Oracle 一起使用并按小时分组时出现问题

java - 如何添加 JButton 和 JLabels 而不会发生冲突?

mysql - SQL异常 : Access denied in Spring Boot

java - Spring MVC : use different JSR-303 validators on the same bean?

spring - RequestMapping转换异常

java - 获取 java.lang.IllegalStateException : Neither BindingResult nor plain target object for bean name 'command' available as request attribute

java - 用java连接mongoDB

java - 尝试检索 PackageInfo 时获取空上下文