0

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

Benjamin C
  • 119
  • 2
  • 11
  • I'm not 100% certain that method security is supported at the servlet level, but with the right annotations it could be. `@RolesAllowed` might work. If you could provide a [minimal sample](https://stackoverflow.com/help/minimal-reproducible-example) in a git repo to get started, I could try and take a look. I've not set up a pure servlet example for some time, so knowing how you're setting up the application would be helpful. – Steve Riesenberg Feb 02 '22 at 19:16
  • Also, note that if you are using the method security annotations, for example `@RolesAllowed`, you need to enable them using `@EnableGlobalMethodSecurity(jsr250Enabled = true)` – Eleftheria Stein-Kousathana Feb 04 '22 at 15:11

0 Answers0