Я разрабатываю приложение весенней загрузки с JWT.Когда я пытаюсь разрешить все до 2 конечных точек, это не работает.Все API защищены и требуют токена.Пожалуйста, помогите мне написать конфигурацию.Вот мой код:
Конфигурация безопасности:
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@Configuration
public class AdapterJWTSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Override
protected void configure(AuthenticationManagerBuilder auth) {
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf().disable()
.cors()
.and()
.authorizeRequests()
.antMatchers("/user/signIn", "/user/addUser").permitAll()
.and()
.anonymous()
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.addFilter(new JWTAuthorizationFilter(authenticationManagerBean()));
}
}
Я пытался сделать это в двух конфигурациях безопасности Spring, но это не сработало.
JwtFilter:
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
public JWTAuthorizationFilter(AuthenticationManager authManager) {
super(authManager);
}
@Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain) throws IOException, ServletException {
String token = req.getHeader(JwtConstants.HEADER_STRING);
if (token == null) {
try {
chain.doFilter(req, res);
} catch (JwtException e) {
System.out.println(e.getMessage());
}
return;
}
UsernamePasswordAuthenticationToken authentication = getAuthentication(req, res);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(req, res);
}
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
String token = request.getHeader(JwtConstants.HEADER_STRING);
if (token != null) {
Claims claims = validateToken(token);
if (claims != null) {
return new UsernamePasswordAuthenticationToken(claims, null, new ArrayList<>());
}
return null;
}
return null;
}
private Claims validateToken(String token) {
Claims claims = null;
try {
return Jwts.parser()
.setSigningKey(JwtConstants.SECRET)
.parseClaimsJws(token).getBody();
} catch (Exception e) {
return null;
}
}
}
Контроллер
Если это может быть полезно
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/rest/user/")
public class UserController {
private UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping("addUser")
public List<String> addUser(@Valid @RequestBody User user,BindingResult bindingResult) {
return userService.addNewUser(user, bindingResult);
}
@PostMapping("signIn")
public List<String> generate(@Valid @RequestBody UserRequestLogin user) {
return userService.signIn(user);
}
}