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:cn.org.once.cstack.security.SecurityTestIT.java
@Before public void setup() { logger.info("*********************************"); logger.info(" setup "); logger.info("*********************************"); this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); // If user1 is null (first test) we create its session and its application try {/* w w w . ja v a 2s.c om*/ logger.info("Create session for user1 : " + user1); // we affect the user to skip this branch too User user1 = userService.findByLogin("usertest1"); Authentication authentication = new UsernamePasswordAuthenticationToken(user1.getLogin(), user1.getPassword()); Authentication result = authenticationManager.authenticate(authentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(result); session1 = new MockHttpSession(); session1.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext); } catch (ServiceException e) { logger.error(e.getLocalizedMessage()); } // After the first tests, all others are for User2 try { logger.info("Create session for user2"); User user2 = userService.findByLogin("usertest2"); Authentication authentication = new UsernamePasswordAuthenticationToken(user2.getLogin(), user2.getPassword()); Authentication result = authenticationManager.authenticate(authentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(result); session2 = new MockHttpSession(); session2.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext); } catch (ServiceException e) { logger.error(e.getLocalizedMessage()); } }
From source file:net.navasoft.madcoin.backend.services.rest.impl.TokenVerifierFilter.java
/** * Do filter./*from w ww . jav a2 s . c o m*/ * * @param request * the request * @param response * the response * @param chain * the chain * @throws IOException * Signals that an I/O exception has occurred. * @throws ServletException * the servlet exception * @since 8/09/2014, 10:28:12 AM */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Map<String, String[]> parms = request.getParameterMap(); if (parms.containsKey("allowanceToken")) { String token = parms.get("allowanceToken")[0]; try { if (tokenUtils.validate(token)) { UserDetails userDetails = tokenUtils.getUserFromToken(token); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails.getUsername(), userDetails.getPassword()); authentication.setDetails( new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request)); SecurityContextHolder.getContext().setAuthentication(userManager.authenticate(authentication)); } } catch (BadPaddingException e) { } catch (AuthenticationException e) { } } else if (parms.containsKey("workerToken")) { String token = parms.get("workerToken")[0]; try { if (providerTokenUtils.validate(token)) { UserDetails userDetails = providerTokenUtils.getUserFromToken(token); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails.getUsername(), userDetails.getPassword()); authentication.setDetails( new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request)); SecurityContextHolder.getContext() .setAuthentication(providerManager.authenticate(authentication)); } } catch (BadPaddingException e) { e.printStackTrace(); } catch (AuthenticationException e) { e.printStackTrace(); } } chain.doFilter(request, response); }
From source file:com.devicehive.auth.rest.HttpAuthenticationFilter.java
private void processBasicAuth(String authHeader) throws UnsupportedEncodingException { Pair<String, String> credentials = extractAndDecodeHeader(authHeader); UsernamePasswordAuthenticationToken requestAuth = new UsernamePasswordAuthenticationToken( credentials.getLeft().trim(), credentials.getRight().trim()); tryAuthenticate(requestAuth);/*w w w. ja va 2 s . com*/ }
From source file:org.cloudfoundry.tools.security.CloudFoundryAuthenticationProviderTest.java
@Test public void shouldNotAuthenticateIfCantLoginUsingCloudFoundryClientDueToMissingToken() throws Exception { setupEnvironment("user@cloudfoundry.com"); given(this.cloudFoundryClient.login()).willReturn(""); Authentication authentication = new UsernamePasswordAuthenticationToken("user@cloudfoundry.com", null); this.thrown.expect(BadCredentialsException.class); this.authenticationProvider.authenticate(authentication); }
From source file:com.ushahidi.swiftriver.core.api.controller.RiversControllerTest.java
@Test public void getDropsFromNonExistentRiver() throws Exception { Authentication authentication = new UsernamePasswordAuthenticationToken("user1", "password"); SecurityContextHolder.getContext().setAuthentication(authentication); this.mockMvc.perform(get("/v1/rivers/9999/drops").principal(authentication)) .andExpect(status().isNotFound()).andExpect(jsonPath("$.message").exists()); }
From source file:cz.zcu.kiv.eegdatabase.wui.app.session.EEGDataBaseSession.java
@Override public boolean authenticate(String username, String password) { if (password.equalsIgnoreCase(SOCIAL_PASSWD)) { this.setLoggedUser(facade.getPerson(username)); this.createShoppingCart(); this.createExperimentLicenseMap(); reloadPurchasedItemCache();//w w w. j a va 2 s .com return true; } boolean authenticated = false; try { Authentication authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(username, password)); SecurityContextHolder.getContext().setAuthentication(authentication); authenticated = authentication.isAuthenticated(); this.setLoggedUser(facade.getPerson(username)); reloadPurchasedItemCache(); this.createShoppingCart(); this.createExperimentLicenseMap(); } catch (AuthenticationException e) { error((String.format("User '%s' failed to login. Reason: %s", username, e.getMessage()))); authenticated = false; } if (getLoggedUser() != null && getLoggedUser().isLock()) { this.setLoggedUser(null); SecurityContextHolder.clearContext(); this.shoppingCart = null; error(ResourceUtils.getString("text.user.lock.login", username)); return false; } return authenticated; }
From source file:com.cfitzarl.cfjwed.core.security.AuthenticationProcessingFilter.java
/** * This is invoked when an authentication attempt is requested. It will parse the data coming from the browser * and prepare it for the authentication manager. The returned authentication object will be picked up and delegated * to either the {@link CustomAuthSuccessHandler} or {@link CustomAuthFailureHandler}. * * @param request the incoming request/*from w w w . j a v a 2s . c o m*/ * @param response the outgoing response * @return the authentication * @throws AuthenticationException * @throws IOException * @throws ServletException */ @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { Map body = new ObjectMapper().readValue(request.getInputStream(), Map.class); String principal = (String) body.get("principal"); String creds = (String) body.get("credentials"); return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(principal, creds)); }
From source file:net.sourceforge.jukebox.model.ProfileTest.java
/** * Tests the validator with an authentication token with <code>null</code> principal. *///from w w w. j a v a 2 s . c o m @Test public final void testInvalidTokenIncorrentPassword() { UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(null, "Administrator"); SecurityContextHolder.getContext().setAuthentication(auth); Profile profile = createProfile("oldpassword", "newPassword", "newPassword"); Set<ConstraintViolation<Profile>> constraintViolations = validator.validate(profile); assertEquals(constraintViolations.size(), 0); SecurityContextHolder.getContext().setAuthentication(null); }
From source file:com.bac.accountserviceapp.AccountServiceApp.java
@Override public AccountServiceAuthentication login(AccountServiceAuthentication authentication) { ///*from ww w .j av a2 s . c o m*/ // Validate authentication content // Objects.requireNonNull(authentication, noAuthenticationMsg); Objects.requireNonNull(authentication.getApplicationName(), noApplicationName); Objects.requireNonNull(authentication.getAccountKey(), incompleteLogin); Objects.requireNonNull(authentication.getAccountPassword(), incompleteLogin); // // Clear out any pre-set values // authentication.setAccountResource(null); authentication.setAccountRole(null); authentication.setAuthenticationOutcome(null); // // // UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( authentication.getAccountKey(), authentication.getAccountPassword()); Authentication loginToken = login(authenticationToken); authentication.setAccountPassword(null); // // If the token is not authenticated then return // AccountServiceAuthenticationOutcome loginOutcome = (AccountServiceAuthenticationOutcome) loginToken .getDetails(); if (loginOutcome != AUTHENTICATED) { authentication.setAuthenticationOutcome(loginOutcome); return authentication; } // // Temporarily set outcome to no role and then verify that // authentication.setAuthenticationOutcome(NO_ROLE); final String expectedApplicationName = authentication.getApplicationName(); if (loginToken.getAuthorities() != null) { for (GrantedAuthority authority : loginToken.getAuthorities()) { String authorityString = authority.getAuthority(); matcher = pattern.matcher(authorityString); if (!matcher.matches() || matcher.groupCount() != AUTHORITY_PATTERN_COUNT) { continue; } String authorityApplicationName = matcher.group(AUTHORITY_PATTERN_APPLICATION_ITEM); String authorityRole = matcher.group(AUTHORITY_PATTERN_ROLE_ITEM); if (!expectedApplicationName.equals(authorityApplicationName)) { continue; } // // Look up the AccountRole and add it to the outgoing authentication // AccountServiceRole accountRole; try { accountRole = AccountServiceRole.valueOf(authorityRole); } catch (IllegalArgumentException e) { logger.warn("Unable to find a valid Account Servie Role for '{}'", authorityRole); accountRole = null; } authentication.setAccountRole(accountRole); authentication.setAuthenticationOutcome(AUTHENTICATED); break; } } // // If NO_ROLE is overidden then populate the outgoing authentication with the Account resource // if (authentication.getAuthenticationOutcome() == AUTHENTICATED) { Account account = strategy.getAccountForApplication(expectedApplicationName, authentication.getAccountKey()); if (account == null) { authentication.setAuthenticationOutcome(NO_RESOURCE); } else { authentication.setAccountResource(account.getResourceName()); } } // // Complete so return // return authentication; }
From source file:org.unidle.controller.CreateQuestionControllerTest.java
@Test public void testQuestionPostWithErrors() throws Exception { SecurityContextHolder.getContext()// ww w .jav a2 s . co m .setAuthentication(new UsernamePasswordAuthenticationToken(user.getUuid(), null)); subject.perform(post("/question/create")).andExpect(view().name(".create-question")) .andExpect(model().attributeExists("questionForm")); }