@PreAuthorize


DOMANDA:

Ho questo controller:


@Controller
public class HelloController {

   @RequestMapping("/menu.htm")
   @PreAuthorize("hasRole('autore')")
   public String provaPreAuthorize(){
     return "autore";
   }
}

@PreAuthorize non funziona e non reagisce come dovrebbe, facendo passare anche utenti non autorizzati.

Perchè viene ignorato?


RISPOSTA:

Il problema inizialmente crea non pochi grattacapi. Intanto stiamo parlando di Spring Security 3.0 o successivi, perchè nelle versioni precedenti esistevano altre annotazioni meno potenti chiamate @Secure. Non mischiate mai nello stesso progetto i 2 tipi di annotazione che non funzioneranno a causa di conflitti negli xml.

La soluzione è ancora una volta semplice, bisogna aggiungere nell'xml di configurazione della DispatcherServlet (e non dentro quello della Security) le seguenti righe tra gli attributi del tag beans:

xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation"http://www.springframework.org/schema/security 
      http://www.springframework.org/schema/security/spring-security-3.1.xsd"

E questo tag:
<security:global-method-securitypre-post-annotations="enabled" /> 

Per completezza, ecco l'intero il dispatcher-servlet.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:security="http://www.springframework.org/schema/security"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.1.xsd"
>

<security:global-method-security pre-post-annotations="enabled" /> 

<context:component-scan base-package="hello.security.controller" />

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    p:prefix="/jsp/" p:suffix=".jsp" />
</beans>

Commenti

Post popolari in questo blog

Arrotondamento e troncamento in Java

Eclipse: Shortcuts (scorciatoie) da tastiera

Strutture dati: List, Set, Map

Creare un eseguibile Java