Spring 安全的 permitAll 未授权

Spring Security's permitAll Unauthorized

我想忽略所有带 HttpMethod.GET 的网址,带 Post,Delete,Put 的网址需要验证。我的网址是 "/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。

如何解决这个问题?

您可以像 blow 一样提供方法类型明智的安全性。

@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();
}

希望对您有所帮助。

解决方法是忽略HttpMethod.GET,这样所有带get方法的url都会被忽略。

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
        .antMatchers(HttpMethod.GET)
        .antMatchers("/favicon.ico", "/", "/index.html", "/registrar",
                "/autenticar", "/app/**");
    }