我想忽略所有带有HttpMethod.GET
的网址,并且需要对带有Post,Delete,Put的Urls进行身份验证。我的网址是"/api/manga","/api/grupos","/api/autor","/genero","/api/pagina","/api/capitulo"
PermitAll不适用于JWTFilter,如果删除过滤器,则可以正常工作。
如何忽略或允许所有带有HttpMethod.GET
的网址?需要创建单独的api进行身份验证吗?
WebSecurityConfig
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/manga", "/api/grupos", "/api/autor", "/genero", "/api/pagina",
"/api/capitulo")
.permitAll().anyRequest().fullyAuthenticated().and()
.addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class).httpBasic()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf()
.disable();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/favicon.ico", "/", "/index.html", "/registrar", "/autenticar", "/app/**");
}
}
JWTAuthenticationFilter
public class JWTAuthenticationFilter extends GenericFilterBean {
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String AUTHORITIES_KEY = "roles";
@Override
public void doFilter(final ServletRequest req, final ServletResponse res,final FilterChain filterChain)
throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) req;
String authReader = request.getHeader(AUTHORIZATION_HEADER);
if (authReader == null || !authReader.startsWith("Bearer ")) {
((HttpServletResponse) res).sendError(HttpServletResponse.SC_UNAUTHORIZED, "invalido autorization");
} else {
try {
final String token = authReader.substring(7);
final Claims claims = Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody();
request.setAttribute("claims", claims);
SecurityContextHolder.getContext().setAuthentication(getAuthentication(claims));
filterChain.doFilter(req, res);
} catch (SignatureException e) {
((HttpServletResponse) res).sendError(HttpServletResponse.SC_UNAUTHORIZED, "invalid token");
}
}
}
public Authentication getAuthentication(Claims claims) {
List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
List<String> roles = (List<String>) claims.get(AUTHORITIES_KEY);
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
User principal = new User(claims.getSubject(), "", authorities);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToklen = new UsernamePasswordAuthenticationToken(
principal, "", authorities);
return usernamePasswordAuthenticationToklen;
}
}
控制器
@RestController
@Transactional
@RequestMapping(value="/api")
public class AutorController {
@Autowired
private AutorRepository autorRepository;
@Autowired
private AutorService autorService;
@RequestMapping(value = "/autor/{id}", method = RequestMethod.GET)
public @ResponseBody ResponseEntity<Page<AutorEntity>> buscarMangaPorId(@PathVariable(value = "id") Long id,
Integer page) {
AutorEntity autor = autorRepository.findOne(id);
if (autor == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
if (page == null) {
page = 0;
}
if (page >= 1) {
page--;
}
Pageable pageable = new PageRequest(page, 20);
return new ResponseEntity<>(autorService.buscarMangaPorId(id, pageable), HttpStatus.OK);
}
@RequestMapping(value = "/autor/lista", method = RequestMethod.GET)
public List<AutorEntity> listarAutores() {
return autorService.listarTodos();
}
@PreAuthorize("hasAuthority('ADMIN')")
@RequestMapping(value = "/autor", method = RequestMethod.POST)
public ResponseEntity<AutorEntity> cadastrarAutor(@RequestBody AutorEntity autor) {
if (autorRepository.findOneByNome(autor.getNome()) != null) {
throw new RuntimeException("Nome Repetido");
}
return new ResponseEntity<>(autorService.cadastrar(autor), HttpStatus.OK);
}
如果需要创建不同的api来分隔HttpMethod,我现在不这样做。
该如何解决?
答案 0 :(得分:1)
解决方案是忽略HttpMethod.GET
,因此所有带有get方法的网址都将被忽略。
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.GET)
.antMatchers("/favicon.ico", "/", "/index.html", "/registrar",
"/autenticar", "/app/**");
}
答案 1 :(得分:0)
您可以提供方法类型明智的安全性,例如打击。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers(HttpMethod.GET).permitAll();
http.authorizeRequests().antMatchers(HttpMethod.POST).denyAll();
http.authorizeRequests().antMatchers(HttpMethod.DELETE,"/url").denyAll();
http.authorizeRequests().antMatchers(HttpMethod.PATCH,"/url").denyAll();
http.authorizeRequests().antMatchers(HttpMethod.PUT,"/url/*").denyAll();
}
我希望它可以帮助您实现目标。