Announcement Announcement Module
Collapse
No announcement yet.
How could I unit test the @Secured? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How could I unit test the @Secured?

    I'm using @Secured feature in my project, I have been trying to use following code to unit test the user "empl1" but failed. The code will still execute but I could get my expected AccessDeniedException.

    Unit test code:
    Code:
    @Test(expected = AccessDeniedException.class)
        public void testA() {
            assertNotNull(userService);
            
            UserDetails ud = userService.loadUserByUsername("empl1");
            assertNotNull(ud);
            
            Authentication auth = new UsernamePasswordAuthenticationToken(ud.getUsername(), ud.getPassword(), ud.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(auth);
            reportService.funcA();
    Security context code:
    Code:
    <security:global-method-security secured-annotations="enabled"/>
     
     <security:authentication-manager>
         <security:authentication-provider>
             <security:password-encoder hash="plaintext"/>
            <security:user-service>
               <security:user name="empl1" password="pass1" authorities="ROLE_EMPLOYEE_A" />
               <security:user name="empl2" password="pass2" authorities="ROLE_EMPLOYEE" />
            </security:user-service>
         </security:authentication-provider>
     </security:authentication-manager>
    Service code:

    Code:
    @Service
    public class ReportService {
        @Secured("ROLE_EMPLOYEE")
        public void funcA() {
            System.out.println("ASD");
        }
    }
    is there a better way to run unit test on the @Secured thing with JUnit?
    THanks @!

  • #2
    This question has been asked on StackOverflow.

    The forums are moving to stackoverflow, a page explaining all this will be available there in a few days: http://spring.io/questions

    Comment

    Working...
    X