Servlet access authorization through annotation and Spring Security

288 Views Asked by At

while trying to implement Spring Security and OAuth2, I have been able to make things work through a very simple example with 2 servlets but I have an issue while securing one of these servlets access : "AdminTestServlet" should only be authorized for users with role "ADMIN". It is working when using "configure" method of WebSecurityConfigurerAdapter (see. antMatchers) :

@EnableWebSecurity(debug = true)
@EnableGlobalMethodSecurity(jsr250Enabled = true, securedEnabled = true, prePostEnabled = true)
public static class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http
      .authorizeRequests(authorize -> authorize
          .antMatchers("/AdminTestServlet").hasAnyRole("ADMIN")
          .anyRequest().authenticated()
          .and()
      )
      .oauth2Login(withDefaults());
    }
  [...]
}

But now I would like to remove the antMatchers and set authorizations through annotations. And it should idealy be standard JavaEE annotation (@ServletSecurity for servlets). But while trying to set them on the Admin servlet it is not working (ie. I always get a 403 error event if I have ADMIN role):

@WebServlet(value = "/AdminTestServlet")
@DeclareRoles("ADMIN")
@ServletSecurity(@HttpConstraint(rolesAllowed={"ADMIN"}))
public class AdminTestServlet extends HttpServlet {
   protected void doGet(...) {
      [...]
   }
}

By the way I had not luck using Spring specific annotation (@Secured) neither : access is always allowed (no 403). There are a lot of posts about setting authorization anotations on JAX-RS endpoints relying on JSR-250 : @RolesAllowed. But I cannot find anything about doing so for Servlet. If someone could help me. Maybe it is not possible?

Thank you

0

There are 0 best solutions below