How to Mock the security context in Spring MVC for testing -
i need test protected urls, therefore need set mock security context in tests (junit).
in particular need perform gets , post against web application, using authenticated user. below there code, able create such security context need inject in 'mockmvc' object.
set authentication object in security context , works, output result of 'securitycontextholder.getcontext().getauthentication().getprincipal()' chanelle.evans@616747.com when call on /profile have assertion error because redirected login page, , not /profile.
@webappconfiguration @contextconfiguration(locations = {"classpath:spring/security.xml", "classpath:spring/view.xml"}) @activeprofiles("default") @runwith(springjunit4classrunner.class) public class authenticationtest { @autowired webapplicationcontext ctx; private mockmvc mockmvc; @autowired private filterchainproxy springsecurityfilterchain; @beforeclass public static void setupbeforeclass() throws exception { } @afterclass public static void teardownafterclass() throws exception { } @before public void setup() throws exception { mockmvc = mockmvcbuilders.webappcontextsetup(ctx).addfilters(springsecurityfilterchain).build(); //@formatter:off userdetailslogic userdetailslogic = null; userdetailslogic = ctx.getbean(userdetailslogic.class); final userdetailsimp userdetailsimp = new userdetailsimp(); userdetailsimp.setaccountid(1001); userdetailsimp.setuserid(8001); userdetailsimp.setpassword("a378c92df7531df6fdf351f7ae1713f91f2dd2d45b9c6e1a8b02736ee3afec6595ff60465e9cb8da"); userdetailsimp.setusername("chanelle.evans@616747.com"); userdetailsimp.setemail("chanelle.evans@616747.com"); final collection<grantedauthorityimplementation> authorities= new arraylist<grantedauthorityimplementation>(); authorities.add(new grantedauthorityimplementation("role_user")); userdetailsimp.setauthorities(authorities); userdetailsimp.setaccountnonexpired(true); userdetailsimp.setaccountnonlocked(true); userdetailsimp.setcredentialsnonexpired(true); userdetailsimp.setenabled(true); final authentication authtoken = new usernamepasswordauthenticationtoken (userdetailsimp.getusername(), userdetailsimp.getpassword(), userdetailsimp.getauthorities()); securitycontextholder.getcontext().setauthentication(authtoken); system.out.println("principal:"+securitycontextholder.getcontext().getauthentication().getprincipal()); mockmvc.perform(get("/profile").principal(authtoken) .contenttype(mediatype.text_html) .accept(mediatype.text_html)) .anddo(print()) .andexpect(status().isok()) .andexpect(redirectedurl(null)) .andexpect(forwardedurl(null)); //@formatter:on } i guess should put authentication object inside mockmvc object, not know how
have idea?
this wrote few days ago. think helpful (i tested same thing against login form, using session second request) see loginuser1ok(..))
see mvctest.java in
Comments
Post a Comment