I am a beginner in Spring Security, so I coded a controller with two methods like this :
@RestController
public class EtudiantRestService {
@Autowired
private EtudiantReository etudiantReository;
@Secured(value = {"ROLE_ADMIN","ROLE_SCOLARITE"})
@RequestMapping(value = "/saveEtudiant",method = RequestMethod.GET)
private Etudiant saveEtudiant(Etudiant etudiant){
System.out.println(etudiant.getNom());
System.out.println(etudiant.getPrenom());
return etudiantReository.save(etudiant);
}
@Secured(value = {"ROLE_ADMIN","ROLE_SCOLARITE","ROLE_PROF","ROLE_ETUDIANT"})
@RequestMapping(value = "/etudiants")
public Page<Etudiant> listEtudiant(int page,int size){
return etudiantReository.findAll(new PageRequest(page,size));
}
}
The configurations of spring security is :
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void globalConfig(AuthenticationManagerBuilder auth) throws Exception{
// Type d'authentification (Base de données, LDAP, Mémoire)
auth.inMemoryAuthentication()
.withUser("admin").password("123456")
.roles("ADMIN","PROF");
auth.inMemoryAuthentication()
.withUser("prof").password("123456")
.roles("PROF");
auth.inMemoryAuthentication()
.withUser("etudiant1").password("123456")
.roles("ETUDIANT");
auth.inMemoryAuthentication()
.withUser("scolaritel").password("123456")
.roles("SCOLARITE");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// Pattern builder
http
.csrf().disable()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.defaultSuccessUrl("/index.html")
.failureUrl("/error.html");
}
}
Mon contrôleur fonctionne bien mais lorsque j'utilise la annotation @Secured et j'authentifier j'avais l'exception :
java.lang.NullPointerException: null at com.upsys.sec.service.EtudiantRestService.saveEtudiant(EtudiantRestService.java:29) ~[classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_102] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_102] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_102] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_102] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapt ....