В настоящее время я работаю над проектом Spring, в котором уже реализована безопасность. (Университет) Но у меня возникла следующая проблема: если я хочу зарегистрировать нового пользователя в системе, у меня логически нет JWT для аутентифицировать нового пользователя. Я просто получаю Invalid authorization header or token
обратно из Spring, если пытаюсь зарегистрировать нового пользователя. Итак, я думаю, что безопасность настроена неправильно:
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserService userService;
private final PasswordEncoder passwordEncoder;
private final RequestMatcher whiteListedRequests;
private final SecurityProperties securityProperties;
private final JwtTokenizer jwtTokenizer;
@Autowired
public SecurityConfig(UserService userService,
PasswordEncoder passwordEncoder,
SecurityProperties securityProperties, JwtTokenizer jwtTokenizer) {
this.userService = userService;
this.securityProperties = securityProperties;
this.passwordEncoder = passwordEncoder;
this.jwtTokenizer = jwtTokenizer;
this.whiteListedRequests = new OrRequestMatcher(securityProperties.getWhiteList().stream()
.map(AntPathRequestMatcher::new)
.collect(Collectors.toList()));
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
.csrf()
.disable();
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/v1/users/sign-up")
.permitAll();
http.authorizeRequests().anyRequest()
.authenticated();
http.addFilter(new JwtAuthenticationFilter(authenticationManager(), securityProperties, jwtTokenizer));
http.addFilter(new JwtAuthorizationFilter(authenticationManager(), securityProperties));
}
@Override
public void configure(WebSecurity web) {
web.ignoring().requestMatchers(whiteListedRequests);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder);
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final List<String> permitAll = Collections.unmodifiableList(Collections.singletonList("*"));
final List<String> permitMethods = List.of(HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.PUT.name(),
HttpMethod.PATCH.name(), HttpMethod.DELETE.name(), HttpMethod.OPTIONS.name(), HttpMethod.HEAD.name(),
HttpMethod.TRACE.name());
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedHeaders(permitAll);
configuration.setAllowedOrigins(permitAll);
configuration.setAllowedMethods(permitMethods);
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
Есть ли у кого-нибудь подсказка, как я могу изменить конфигурацию безопасности, чтобы пользователь мог зарегистрироваться на моей конечной точке? (/ api / v1 / users / sign-up) Я немного заблудился и несколько часов пытаюсь управлять желаемым поведением! Заранее спасибо!
EDIT:
Я только что подумал, что мой application.yml содержит белый список:
white-list:
# Some other stuff ... (Database console etc.)
# Registration
- /api/v1/users/sign-up
Если я добавлю здесь URI, он будет работать правильно. Но есть ли решение просто добавить его через код?