DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Spring Boot: JUnit Integration Test
  • Spring Boot: Testing Service Layer Code with JUnit 5 and Mockito, RESTful Web Services
  • Component Tests for Spring Cloud Microservices

Trending

  • You Are Using Claude Wrong (And So Is Everyone You Know)
  • How to Test a PATCH API Request With REST-Assured Java
  • 8 Ways to Improve Application Performance
  • Introduction to Retrieval Augmented Generation (RAG)
  1. DZone
  2. Coding
  3. Java
  4. Spring-Test-MVC Junit Testing Spring Security Layer with Method Level Security

Spring-Test-MVC Junit Testing Spring Security Layer with Method Level Security

By 
Krishna Prasad user avatar
Krishna Prasad
·
Feb. 21, 13 · Interview
Likes (0)
Comment
Save
Tweet
Share
23.5K Views

Join the DZone community and get the full member experience.

Join For Free

For people in hurry get the code from Github.

In continuation of my earlier blog on spring-test-mvc junit testing Spring Security layer with InMemoryDaoImpl, in this blog I will discuss how to use achieve method level access control. Please follow the steps in this blog to setup spring-test-mvc and run the below test case.

mvn test -Dtest=com.example.springsecurity.web.controllers.SecurityControllerTest

The JUnit test case looks as below,

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = WebContextLoader.class, value = { "classpath:/META-INF/spring/services.xml",
"classpath:/META-INF/spring/security.xml",
"classpath:/META-INF/spring/mvc-config.xml" })
public class SecurityControllerTest {

@Autowired
CalendarService calendarService;

@Test
public void testMyEvents() throws Exception {
Authentication auth = new UsernamePasswordAuthenticationToken("[email protected]", "user1");
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(auth);

calendarService.findForUser(0);
SecurityContextHolder.clearContext();
}

@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void testForbiddenEvents() throws Exception {
calendarService.findForUser(0);
}
}
@Test(expected=AccessDeniedException.class)
public void testWrongUserEvents() throws Exception {
Authentication auth = new UsernamePasswordAuthenticationToken("[email protected]", "user2");
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(auth);

calendarService.findForUser(0);
SecurityContextHolder.clearContext();
}

If you notice, if the user did not login or if the user is trying to access another users information it will throw an exception.

The interface access control is as below,

public interface CalendarService {

@PreAuthorize("hasRole('ROLE_ADMIN') or principal.id == #userId")
List<Event> findForUser(int userId);
}

The PreAuthorize only works on interface so that any implementation that implements this interface has this access control.

I hope this blog helps you.


 

Spring Security JUnit Spring Framework

Published at DZone with permission of Krishna Prasad. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Spring Boot: JUnit Integration Test
  • Spring Boot: Testing Service Layer Code with JUnit 5 and Mockito, RESTful Web Services
  • Component Tests for Spring Cloud Microservices

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook