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:fr.treeptik.cloudunit.snapshot.AbstractSnapshotControllerTestIT.java
@Before public void setup() { logger.info("setup"); this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); User user = null;//from w w w .j a v a2 s.c o m try { user = userService.findByLogin("johndoe"); } catch (ServiceException e) { logger.error(e.getLocalizedMessage()); } Authentication authentication = new UsernamePasswordAuthenticationToken(user.getLogin(), user.getPassword()); Authentication result = authenticationManager.authenticate(authentication); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(result); session = new MockHttpSession(); session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext); }
From source file:hsa.awp.scire.procedureLogic.DrawProcedureLogicTest.java
@Before @Transactional// ww w. ja v a2 s.co m public void setup() { SecurityContextHolder.getContext() .setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password")); Mockery context = new JUnit4Mockery(); final IMail mail = context.mock(IMail.class); context.checking(new Expectations() { { allowing(mail).send(); } }); IMailFactory mailFactory = new IMailFactory() { @Override public IMail getInstance(String recipient, String subject, String message, String sender) { return mail; } }; drawProcedureLogic = new DrawProcedureLogic(); drawProcedureLogic.setCampaignFacade(campaignFacade); drawProcedureLogic.setEventFacade(eventFacade); drawProcedureLogic.setUserFacade(userFacade); drawProcedureLogic.setMailFactory(mailFactory); drawProcedureLogic.setCampaignRuleChecker(campaignRuleChecker); /** create Campaign **/ campaign = Campaign.getInstance(0L); campaign.setName("halloweltCampaignTest" + Math.random()); campaign.setStartShow(Calendar.getInstance()); campaign.setEndShow(Calendar.getInstance()); campaignFacade.saveCampaign(campaign); /** create DrawProcedure **/ drawProcedure = DrawProcedure.getInstance(0L); drawProcedure.setInterval(Calendar.getInstance(), Calendar.getInstance()); drawProcedure.setName("hallowelt"); drawProcedure.setMaximumPriorityLists(3); drawProcedure.setMaximumPriorityListItems(3); campaign.addProcedure(drawProcedure); campaignFacade.saveDrawProcedure(drawProcedure); drawProcedureLogic.setProcedure(drawProcedure); /** Create Subject **/ subject = Subject.getInstance(0L); subject.setName("Testvorlesung"); eventFacade.saveSubject(subject); events = new LinkedList<Event>(); for (int i = 0; i < 30; i++) { events.add(createEvent(i)); } /** merge the Campaign **/ campaignFacade.updateCampaign(campaign); /** reset singleUser id counter **/ userId = 0L; /** create SingleUser **/ singleUser = createUser("halloWelt"); userFacade.saveSingleUser(singleUser); /** create initiator **/ init = createUser("init"); userFacade.saveSingleUser(init); }
From source file:com.github.peholmst.springsecuritydemo.ui.LoginView.java
@SuppressWarnings("serial") protected void init() { final Panel loginPanel = new Panel(); loginPanel.setCaption(getApplication().getMessage("login.title")); ((VerticalLayout) loginPanel.getContent()).setSpacing(true); final TextField username = new TextField(getApplication().getMessage("login.username")); username.setWidth("100%"); loginPanel.addComponent(username);/* ww w. j a v a 2s . c om*/ final TextField password = new TextField(getApplication().getMessage("login.password")); password.setSecret(true); password.setWidth("100%"); loginPanel.addComponent(password); final Button loginButton = new Button(getApplication().getMessage("login.button")); loginButton.setStyleName("primary"); // TODO Make it possible to submit the form by pressing <Enter> in any // of the text fields loginPanel.addComponent(loginButton); ((VerticalLayout) loginPanel.getContent()).setComponentAlignment(loginButton, Alignment.MIDDLE_RIGHT); loginButton.addListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { final Authentication auth = new UsernamePasswordAuthenticationToken(username.getValue(), password.getValue()); try { if (logger.isDebugEnabled()) { logger.debug("Attempting authentication for user '" + auth.getName() + "'"); } Authentication returned = getAuthenticationManager().authenticate(auth); if (logger.isDebugEnabled()) { logger.debug("Authentication for user '" + auth.getName() + "' succeeded"); } fireEvent(new LoginEvent(LoginView.this, returned)); } catch (BadCredentialsException e) { if (logger.isDebugEnabled()) { logger.debug("Bad credentials for user '" + auth.getName() + "'", e); } getWindow().showNotification(getApplication().getMessage("login.badCredentials.title"), getApplication().getMessage("login.badCredentials.descr"), Notification.TYPE_WARNING_MESSAGE); } catch (DisabledException e) { if (logger.isDebugEnabled()) { logger.debug("Account disabled for user '" + auth.getName() + "'", e); } getWindow().showNotification(getApplication().getMessage("login.disabled.title"), getApplication().getMessage("login.disabled.descr"), Notification.TYPE_WARNING_MESSAGE); } catch (LockedException e) { if (logger.isDebugEnabled()) { logger.debug("Account locked for user '" + auth.getName() + "'", e); } getWindow().showNotification(getApplication().getMessage("login.locked.title"), getApplication().getMessage("login.locked.descr"), Notification.TYPE_WARNING_MESSAGE); } catch (Exception e) { if (logger.isErrorEnabled()) { logger.error("Error while attempting authentication for user '" + auth.getName() + "'"); } ExceptionUtils.handleException(getWindow(), e); } } }); HorizontalLayout languages = new HorizontalLayout(); languages.setSpacing(true); final Button.ClickListener languageListener = new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { Locale locale = (Locale) event.getButton().getData(); if (logger.isDebugEnabled()) { logger.debug("Changing locale to [" + locale + "] and restarting the application"); } getApplication().setLocale(locale); getApplication().close(); } }; for (Locale locale : getApplication().getSupportedLocales()) { if (!getLocale().equals(locale)) { final Button languageButton = new Button(getApplication().getLocaleDisplayName(locale)); languageButton.setStyleName(Button.STYLE_LINK); languageButton.setData(locale); languageButton.addListener(languageListener); languages.addComponent(languageButton); } } loginPanel.addComponent(languages); loginPanel.setWidth("300px"); final HorizontalLayout viewLayout = new HorizontalLayout(); viewLayout.addComponent(loginPanel); viewLayout.setComponentAlignment(loginPanel, Alignment.MIDDLE_CENTER); viewLayout.setSizeFull(); viewLayout.setMargin(true); setCompositionRoot(viewLayout); setSizeFull(); }
From source file:fr.treeptik.cloudunit.modules.redis.SpringBootRedisModuleControllerTestIT.java
@Before public void setup() { logger.info("setup"); this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); User user = null;//from w w w. ja v a 2 s .c om try { user = userService.findByLogin("johndoe"); } catch (ServiceException e) { logger.error(e.getLocalizedMessage()); } assert user != null; Authentication authentication = new UsernamePasswordAuthenticationToken(user.getLogin(), user.getPassword()); Authentication result = authenticationManager.authenticate(authentication); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(result); session = new MockHttpSession(); String secContextAttr = HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY; session.setAttribute(secContextAttr, securityContext); }
From source file:org.unidle.controller.UpdateAccountControllerTest.java
@Test public void testUpdate() throws Exception { SecurityContextHolder.getContext()/*w w w.j a va2s .c om*/ .setAuthentication(new UsernamePasswordAuthenticationToken(user.getUuid(), null)); subject.perform(post("/account/update").param("email", "new@example.com") .param("firstName", "new first name").param("lastName", "new last name")) .andExpect(view().name(".ajax.updated-account")) .andExpect(model().attribute("user", allOf(hasProperty("email", equalTo("new@example.com")), hasProperty("firstName", equalTo("new first name")), hasProperty("lastName", equalTo("new last name"))))); assertThat(userRepository.findOne(user.getUuid())).satisfies(hasEmail("new@example.com")) .satisfies(hasFirstName("new first name")).satisfies(hasLastName("new last name")); }
From source file:seava.j4e.web.controller.session.SessionController.java
/** * Process login action/*from www . j a v a 2 s.co m*/ * * @param username * @param password * @param clientCode * @param language * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "/" + Constants.SESSION_ACTION_LOGIN, method = RequestMethod.POST) public ModelAndView login(@RequestParam(value = "user", required = true) String username, @RequestParam(value = "pswd", required = true) String password, @RequestParam(value = "client", required = true) String clientCode, @RequestParam(value = "lang", required = false) String language, HttpServletRequest request, HttpServletResponse response) throws Exception { try { if (logger.isInfoEnabled()) { logger.info("Session request: -> login "); } if (logger.isDebugEnabled()) { logger.debug(" --> request-params: user={}, client={}, pswd=*** ", new Object[] { username, clientCode }); } request.getSession().invalidate(); request.getSession(); prepareLoginParamsHolder(clientCode, language, request); String hashedPass = getMD5Password(password); Authentication authRequest = new UsernamePasswordAuthenticationToken(username, hashedPass); Authentication authResponse = this.getAuthenticationManager().authenticate(authRequest); SecurityContextHolder.getContext().setAuthentication(authResponse); response.sendRedirect(this.getSettings().get(Constants.PROP_CTXPATH) + Constants.URL_UI_EXTJS); return null; } catch (Exception e) { ModelAndView err = this.showLogin(request, response); String msg = "Access denied. "; if (e.getMessage() != null && !"".equals(e.getMessage())) { msg += e.getMessage(); } err.getModel().put("error", msg); return err; } }
From source file:fr.treeptik.cloudunit.infinity.SimpleLongRunnerTestMR.java
@Before public void setup() { logger.info("setup"); this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); User user = null;// w w w .j a v a 2 s . c o m try { user = userService.findByLogin("johndoe"); } catch (ServiceException e) { logger.error(e.getLocalizedMessage()); } Authentication authentication = new UsernamePasswordAuthenticationToken(user.getLogin(), user.getPassword()); Authentication result = authenticationManager.authenticate(authentication); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(result); session = new MockHttpSession(); session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext); }