List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken
public UsernamePasswordAuthenticationToken(Object principal, Object credentials)
UsernamePasswordAuthenticationToken
, as the #isAuthenticated() will return false
. From source file:waffle.spring.WindowsAuthenticationProviderTests.java
/** * Test authenticate./*from ww w . ja v a 2s. c o m*/ */ @Test public void testAuthenticate() { final MockWindowsIdentity mockIdentity = new MockWindowsIdentity(WindowsAccountImpl.getCurrentUsername(), new ArrayList<String>()); final WindowsPrincipal principal = new WindowsPrincipal(mockIdentity); final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( principal, "password"); final Authentication authenticated = this.provider.authenticate(authentication); Assert.assertNotNull(authenticated); Assert.assertTrue(authenticated.isAuthenticated()); final Collection<? extends GrantedAuthority> authorities = authenticated.getAuthorities(); final Iterator<? extends GrantedAuthority> authoritiesIterator = authorities.iterator(); Assert.assertEquals(3, authorities.size()); final List<String> list = new ArrayList<>(); while (authoritiesIterator.hasNext()) { list.add(authoritiesIterator.next().getAuthority()); } Collections.sort(list); Assert.assertEquals("ROLE_EVERYONE", list.get(0)); Assert.assertEquals("ROLE_USER", list.get(1)); Assert.assertEquals("ROLE_USERS", list.get(2)); Assert.assertTrue(authenticated.getPrincipal() instanceof WindowsPrincipal); }
From source file:hsa.awp.admingui.DummyValueCreator.java
/** * Inserts the test data.//from ww w . j a v a 2 s.co m */ @Test @Transactional public void insertData() { logger.debug("start test insertData()"); SecurityContextHolder.getContext() .setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password")); Campaign c = Campaign.getInstance(0L); c.setName("CampaignName"); campaignFacade.saveCampaign(c); logger.debug("saved campaign " + c); DrawProcedure d1 = DrawProcedure.getInstance(0L); d1.getDrawDate().roll(Calendar.DATE, 1); d1.getEndDate().roll(Calendar.DATE, 2); d1.setName("1. Losung"); campaignFacade.saveDrawProcedure(d1); logger.debug("saved drawProcedure " + d1); DrawProcedure d2 = DrawProcedure.getInstance(0L); d2.getStartDate().roll(Calendar.DATE, 2); d2.getEndDate().roll(Calendar.DATE, 4); d2.getDrawDate().roll(Calendar.DATE, 3); d2.setName("2. Losung"); campaignFacade.saveDrawProcedure(d2); logger.debug("saved drawProcedure " + d2); FifoProcedure f1 = FifoProcedure.getInstance(0L); Calendar f1Start = Calendar.getInstance(); f1Start.roll(Calendar.DATE, 4); Calendar f1End = Calendar.getInstance(); f1End.roll(Calendar.DATE, 5); f1.setInterval(f1Start, f1End); f1.setName("Restfifo"); campaignFacade.saveFifoProcedure(f1); logger.debug("saved fifiProcedure " + f1); c.addProcedure(f1); c.addProcedure(d1); c.addProcedure(d2); campaignFacade.updateCampaign(c); Category c1 = Category.getInstance("Testkategorie1", 0L); Category c2 = Category.getInstance("Testkategorie2", 0L); eventFacade.saveCategory(c1); eventFacade.saveCategory(c2); Subject s1 = Subject.getInstance(0L); s1.setName("TestFach"); eventFacade.saveSubject(s1); c1.addSubject(s1); eventFacade.updateSubject(s1); eventFacade.updateCategory(c1); SingleUser t1 = SingleUser.getInstance("meixner"); t1.setName("Gerhard Meixner"); RoleMapping roleMapping = RoleMapping.getInstance(Role.REGISTERED); userFacade.saveRoleMapping(roleMapping); t1.getRolemappings().add(roleMapping); userFacade.saveSingleUser(t1); Event e1 = Event.getInstance(1, 0L); e1.setMaxParticipants(20); e1.setSubject(s1); e1.getTeachers().add(t1.getId()); e1.setSubject(s1); eventFacade.saveEvent(e1); Event e2 = Event.getInstance(2, 0L); e2.setMaxParticipants(20); e2.setSubject(s1); e2.getTeachers().add(t1.getId()); e2.setSubject(s1); eventFacade.saveEvent(e2); Event e3 = Event.getInstance(3, 0L); e3.setMaxParticipants(30); e3.setSubject(s1); e3.getTeachers().add(t1.getId()); e3.setSubject(s1); eventFacade.saveEvent(e3); s1.addEvent(e1); s1.addEvent(e2); s1.addEvent(e3); eventFacade.updateSubject(s1); c.getEventIds().add(e1.getId()); campaignFacade.updateCampaign(c); PriorityList p1 = PriorityList.getInstance(0L); p1.setDate(Calendar.getInstance()); campaignFacade.savePriorityList(p1); PriorityListItem pi1 = PriorityListItem.getInstance(p1, e1.getId(), 1, 0L); PriorityListItem pi2 = PriorityListItem.getInstance(p1, e2.getId(), 2, 0L); PriorityListItem pi3 = PriorityListItem.getInstance(p1, e3.getId(), 3, 0L); campaignFacade.savePriorityListItem(pi1); campaignFacade.savePriorityListItem(pi2); campaignFacade.savePriorityListItem(pi3); p1.getItems().add(pi1); p1.getItems().add(pi2); p1.getItems().add(pi3); campaignFacade.updatePriorityList(p1); d1.getPriorityLists().add(p1); campaignFacade.updatePriorityList(p1); }
From source file:org.sharetask.data.DbUnitTest.java
@Before public void init() throws DatabaseUnitException, SQLException, MalformedURLException { // insert data into database DatabaseOperation.DELETE.execute(getConnection(), getDataSet()); DatabaseOperation.INSERT.execute(getConnection(), getDataSet()); // login// w ww . ja va2s. co m if (enableSecurity) { final Authentication authentication = new UsernamePasswordAuthenticationToken("test1@test.com", "password"); final Authentication authenticate = authenticationManager.authenticate(authentication); SecurityContextHolder.getContext().setAuthentication(authenticate); } }
From source file:org.unidle.repository.AuditorAwareImplTest.java
@Test public void testGetCurrentAuditorWithoutUuid() throws Exception { SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(null, null)); final Object result = subject.getCurrentAuditor(); assertThat(result).isNull();//from w w w .j a v a 2 s .c om }
From source file:com.organization.projectname.controller.AuthenticationController.java
@RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST) public ResponseEntity<?> createAuthenticationToken(@RequestBody AuthenticationRequest authenticationRequest, Device device) throws AuthenticationException, Exception { userService.isIPOK();/* ww w. j av a 2s .c o m*/ // Perform the security final Authentication authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword())); SecurityContextHolder.getContext().setAuthentication(authentication); // Reload password post-security so we can generate token final UserDetails userDetails = userService.loadUserByUsername(authenticationRequest.getUsername()); final String token = jwtTokenUtil.generateToken(userDetails, device); // Return the token return ResponseEntity.ok(new AuthenticationResponse(token)); }
From source file:fr.esiea.windmeal.controller.authentication.AuthenticationCtrl.java
@RequestMapping(value = "/login", method = RequestMethod.POST, consumes = "application/json") @ResponseBody// ww w.j ava 2s .co m @ResponseStatus(HttpStatus.OK) public void login(@RequestBody User user, HttpServletResponse response) throws InvalidLoginException { LOGGER.info("[Controller] Querying to log in User \"" + user.toString() + "\""); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword()); try { Authentication auth = authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(auth); } catch (BadCredentialsException ex) { throw new InvalidLoginException(); } }
From source file:jedai.business.JAuthorizationService.java
/** * authenticates a client//w ww .j a va 2s . co m * * @param authvo * AuthVO the object being authenticated * * @return val * Boolean the returned boolean value */ public boolean authenticate(AuthVO authvo) { Authentication token = new UsernamePasswordAuthenticationToken(authvo.getUserName(), authvo.getPassword()); try { token = authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(token); } catch (AuthenticationException ex) { // report error System.out.println("ERROR: " + ex); } if (!token.isAuthenticated()) { return false; } return true; }
From source file:com.utest.webservice.auth.UtestWSS4JInInterceptor.java
@SuppressWarnings("unchecked") @Override/* w w w. j av a 2 s.com*/ public void handleMessage(final SoapMessage message) throws Fault { try { super.handleMessage(message); final Vector<WSHandlerResult> result = (Vector<WSHandlerResult>) message .getContextualProperty(WSHandlerConstants.RECV_RESULTS); if ((result != null) && !result.isEmpty()) { for (final WSHandlerResult res : result) { // loop through security engine results for (final WSSecurityEngineResult securityResult : (Vector<WSSecurityEngineResult>) res .getResults()) { final int action = (Integer) securityResult.get(WSSecurityEngineResult.TAG_ACTION); // determine if the action was a username token if ((action & WSConstants.UT) > 0) { // get the principal object final WSUsernameTokenPrincipal principal = (WSUsernameTokenPrincipal) securityResult .get(WSSecurityEngineResult.TAG_PRINCIPAL); if (principal.getPassword() == null) { principal.setPassword(""); } Authentication authentication = new UsernamePasswordAuthenticationToken( principal.getName(), principal.getPassword()); authentication = authenticationProvider.authenticate(authentication); if (!authentication.isAuthenticated()) { System.out.println("This user is not authentic."); } SecurityContextHolder.getContext().setAuthentication(authentication); } } } } } catch (final RuntimeException ex) { ex.printStackTrace(); throw ex; } }
From source file:hsa.awp.campaign.facade.CampaignFacadeTest.java
/** * We do not want to test security issues. So we set our login to admin. *///from w w w .ja v a2 s . com @Before public void setUp() { SecurityContextHolder.getContext() .setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password")); }
From source file:it.geosolutions.geostore.services.rest.BaseAuthenticationTest.java
protected void doAutoLogin(String username, String password, HttpServletRequest request) { try {/*from ww w. ja va2 s. c o m*/ // Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); // token.setDetails(new WebAuthenticationDetails(request)); Authentication authentication = ((AuthenticationProvider) context.getBean("geostoreLdapProvider")) .authenticate(token); LOGGER.info("Logging in with [{" + authentication.getPrincipal() + "}]"); SecurityContextHolder.getContext().setAuthentication(authentication); } catch (Exception e) { SecurityContextHolder.getContext().setAuthentication(null); LOGGER.error("Failure in autoLogin", e); } }