Close

Spring Security - Method Security with JSR-250 @RolesAllowed

[Last Updated: Sep 11, 2017]

Spring Security provides support for JSR-250 annotation security. That means we can use javax.annotation.security.RolesAllowed in the place of Spring's @Secured annotation.

Example

We are going to reuse our last example. We just need to replace @Secured with @RolesAllowed in the service class and enabled JSR-250 annotation in Java config class. We will also need to include JSR-250 API maven dependency.

Additional Maven Dependency

pom.xml

<dependency>
   <groupId>javax.annotation</groupId>
   <artifactId>jsr250-api</artifactId>
   <version>1.0</version>
</dependency>

Service Interface

package com.logicbig.example;

import javax.annotation.security.RolesAllowed;
import java.util.List;

public interface ShoppingCartService {
  @RolesAllowed("ROLE_CUSTOMER")
  int placeOrder(OrderItem order);

  @RolesAllowed("ROLE_ADMIN")
  List<OrderItem> getOrderList();
}

Java Config class

@Configuration
@EnableWebSecurity
@EnableWebMvc
@ComponentScan
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class AppConfig extends WebSecurityConfigurerAdapter {

  protected void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests()
          .anyRequest().authenticated()
          .and()
          .formLogin()
          .and()
          .exceptionHandling().accessDeniedPage("/noAccess");
  }

  @Override
  public void configure(AuthenticationManagerBuilder builder)
          throws Exception {
      builder.inMemoryAuthentication()
             .withUser("ann").password("123").roles("CUSTOMER")
             .and()
             .withUser("ray").password("234").roles("ADMIN");
  }

  @Bean
  public ViewResolver viewResolver() {
      InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
      viewResolver.setPrefix("/WEB-INF/views/");
      viewResolver.setSuffix(".jsp");
      return viewResolver;
  }
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

The output will be same as the last example.

Example Project

Dependencies and Technologies Used:

  • spring-security-web 4.2.3.RELEASE: spring-security-web.
  • spring-security-config 4.2.3.RELEASE: spring-security-config.
  • spring-webmvc 4.3.9.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.1.0 Java Servlet API
  • jsr250-api 1.0: JSR-250 Reference Implementation by Glassfish.
  • JDK 1.8
  • Maven 3.3.9

Method Security with JSR-250 Annotation Select All Download
  • method-security-with-jsr-250
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ShoppingCartService.java
          • webapp
            • WEB-INF
              • views

    See Also