Spring security 使用WebSecurityConfigureAdapter向任何人授权注册页面

Spring security 使用WebSecurityConfigureAdapter向任何人授权注册页面,spring-security,Spring Security,如果我使用令牌,我可以很好地访问用户页面http://localhost:8901/auth/user. 但是,如果我尝试只获取注册/注册“api调用”,则我得到的任何人都应该可以访问: “访问此资源需要完全身份验证” 我尝试了以下方法 httpSecurity .csrf() .disable() .authorizeRequests() .antMatch

如果我使用令牌,我可以很好地访问用户页面http://localhost:8901/auth/user.

但是,如果我尝试只获取注册/注册“api调用”,则我得到的任何人都应该可以访问: “访问此资源需要完全身份验证”

我尝试了以下方法

 httpSecurity
                .csrf()
                .disable()
                .authorizeRequests()
                    .antMatchers("/registration")
                    .permitAll()
                    .and()
                .authorizeRequests()
                    .anyRequest()
                    .authenticated()
                    .and()
                .httpBasic();
然后尝试查看是否可以启用所有功能,但仍然会出现相同的错误:

        httpSecurity
                .csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/**").permitAll()
                .and()
                .httpBasic();
我上的一些课

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    @Bean
    public UserDetailsService userDetailsServiceBean() throws Exception {
        return super.userDetailsServiceBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("user1").password("{noop}password1").roles("USER")
                .and()
                .withUser("user2").password("{noop}password2").roles("USER", "ADMIN");
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        httpSecurity
                .csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/**").permitAll()
                .and()
                .httpBasic();
    }
}
application.yml文件

#Setting the logging levels for the service
logging:
  level:
    com.netflix: DEBUG
    org.springframework.web: DEBUG
    com.test: DEBUG

eureka:
  instance:
    preferIpAddress: true
  client:
    service-url:
      default-zone: http://localhost:8761/eureka/
    register-with-eureka: true
    fetch-registry: true

ribbon:
  eureka:
    enabled: true

server:
  port: 8901
  servlet:
    context-path: /auth
bootstrap.yml文件:

spring:
  application:
    name: authenticationservice
  profiles:
    active:
      default
  cloud:
    config:
      enabled: true
主类

@SpringBootApplication
@RestController
@EnableOAuth2Client
@EnableResourceServer
@EnableAuthorizationServer
public class Application {
    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(value = { "/user" }, produces = "application/json")
    public Map<String, Object> user(OAuth2Authentication user) {
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("user", user.getUserAuthentication().getPrincipal());
        userInfo.put("authorities", AuthorityUtils.authorityListToSet(user.getUserAuthentication().getAuthorities()));
        return userInfo;
    }

    @RequestMapping(value = {"/validate"}, produces = "application/json")
    public User validate(OAuth2Authentication user)
    {
        return userRepository.findByUserName(user.getName());
    }

  
    @PostMapping("/registration")
    @ResponseStatus(code = HttpStatus.CREATED)
    public void register(@RequestBody UserRegistrationDetails userRegDetails) {
        logger.debug("Entering the register method");
        if (StringUtils.isEmpty(userRegDetails.getUserName()) || EmailValidator.emailValidator(userRegDetails.getUserName()) == false)
        {
            throw new InvalidException("Invalid email provided");
        }
        User existingUser = userRepository.findByUserName(userRegDetails.getUserName());
        if (existingUser != null)
            throw new InvalidException("The User already exists");
        if (EmailValidator.emailValidator(userRegDetails.getPassword()))
            throw new InvalidException("The provided password is invalid");
        User user = User.UserBuilder
                .builder()
                .withEnabled(true)
                .withUserName(userRegDetails.getUserName()).withPassword(userRegDetails.getPassword())
                .withEnabled(false)
                .withAuthorizationCode("SOMECODE")
                .withApplicationId(userRegDetails.getApplicationId())
                .build();
        userRepository.save(user);
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }


}

您的调用似乎触发了代码的资源服务器部分。这需要一个用于授权的令牌。按如下方式配置异常:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

  @Override
  public void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests()
            .antMatchers("/registration")
            .permitAll();
  }
}       

您可以从主类中删除@EnableResourceServer。

非常感谢我认为EnableResourceServer需要与@SpringBootApplication一起设置,我从WebSecurity配置器中删除了配置(HttpSecurity http),并使用了您建议的ResourceServerConfig。现在一切看起来都很好,所以我把你的答案标记为正确!
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

  @Override
  public void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests()
            .antMatchers("/registration")
            .permitAll();
  }
}