Example usage for org.springframework.security.authentication UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken

List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken

Introduction

In this page you can find the example usage for org.springframework.security.authentication UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken.

Prototype

public UsernamePasswordAuthenticationToken(Object principal, Object credentials) 

Source Link

Document

This constructor can be safely used by any code that wishes to create a UsernamePasswordAuthenticationToken, as the #isAuthenticated() will return false.

Usage

From source file:io.github.azige.bbs.web.controller.AccountController.java

public ResponseEntity<?> loginAjax(@RequestBody Account account, Model model) throws IOException {
    try {//w  w  w . j av  a2s .co  m
        Authentication authentication = accountService.authenticate(
                new UsernamePasswordAuthenticationToken(account.getAccountName(), account.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        Profile loginProfile = (Profile) authentication.getPrincipal();
        return new ResponseEntity<>(loginProfile, HttpStatus.OK);
    } catch (AuthenticationException ex) {
        return new ResponseEntity<>(
                new ErrorResult(
                        messageSource.getMessage("account.login.fail", null, LocaleContextHolder.getLocale())),
                HttpStatus.UNAUTHORIZED);
    }
}

From source file:hsa.awp.scire.procedureLogic.AbstractProcedureLogicTest.java

@Before
public void setUp() throws Exception {

    SecurityContextHolder.getContext()//from   ww w . ja va2s  . co m
            .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;
        }
    };

    this.abs = new FifoProcedureLogic();
    // Set the Factories to the AbstractRegistration
    abs.setMailFactory(mailFactory);
    abs.setUserFacade(userFac);
    abs.setEventFacade(eventFac);
    abs.setCampaignFacade(campFac);
    abs.setCampaignRuleChecker(campaignRuleChecker);
}

From source file:com.vdenotaris.spring.boot.security.saml.web.core.CurrentUserHandlerMethodArgumentResolverTest.java

@Test
public void testResolveArgument() throws Exception {
    // given//from   w ww  .j  a  v  a 2s  .co m
    ModelAndViewContainer mavContainer = mock(ModelAndViewContainer.class);
    WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class);
    NativeWebRequest webRequest = mock(NativeWebRequest.class);
    JWTAuthenticatedUser stubUser = new JWTAuthenticatedUser(USER_NAME);
    Principal stubPrincipal = new UsernamePasswordAuthenticationToken(stubUser, null);
    when(webRequest.getUserPrincipal()).thenReturn(stubPrincipal);

    // when/then
    assertEquals(stubUser, resolver.resolveArgument(validParam, mavContainer, webRequest, binderFactory));
    assertEquals(WebArgumentResolver.UNRESOLVED,
            resolver.resolveArgument(notAnnotatedParam, mavContainer, webRequest, binderFactory));
    assertEquals(WebArgumentResolver.UNRESOLVED,
            resolver.resolveArgument(wrongTypeParam, mavContainer, webRequest, binderFactory));
}

From source file:example.springdata.jpa.security.SecurityIntegrationTests.java

@Test
public void findBusinessObjectsForCurrentUserShouldReturnOnlyBusinessObjectsWhereCurrentUserIsOwner() {

    SecurityContextHolder.getContext().setAuthentication(tomAuth);

    List<BusinessObject> businessObjects = secureBusinessObjectRepository.findBusinessObjectsForCurrentUser();

    assertThat(businessObjects, hasSize(1));
    assertThat(businessObjects, contains(object3));

    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(ollie, "x"));

    businessObjects = secureBusinessObjectRepository.findBusinessObjectsForCurrentUser();

    assertThat(businessObjects, hasSize(2));
    assertThat(businessObjects, contains(object1, object2));
}

From source file:org.ihtsdo.otf.refset.api.authentication.UserController.java

@RequestMapping(method = RequestMethod.POST, value = "/getUserDetails", produces = "application/json", consumes = "application/json")
@ApiOperation(value = "Authenticate a user for given username and password provided in request header and returns user details ", notes = "This api call authenticate a user and also authorize a user for Refset app access. Pre-Auth tokens(X-REFSET-PRE-AUTH-USERNAME & X-REFSET-PRE-AUTH-TOKEN)"
        + " supplied in request header, are being used for authentication/authorization. If successful"
        + " it returns an User details object and a authentication token X-REFSET-AUTH-TOKEN as part of response header"
        + " to be used in header of subsequent requests for API handshake")
@PreAuthorize("hasRole('ROLE_USER')")
public ResponseEntity<Result<Map<String, Object>>> login() throws Exception {

    logger.debug("authenticating user {}");

    Result<Map<String, Object>> r = Utility.getResult();
    Map<String, Object> data = new HashMap<String, Object>();
    User u = org.ihtsdo.otf.refset.common.Utility.getUserDetails();
    if (StringUtils.isEmpty(u.getGivenname())) {

        Authentication authentication = new UsernamePasswordAuthenticationToken(u, u.getPassword());
        provider.authenticate(authentication);
        u = (User) authentication.getPrincipal();

    }//from w w  w  .jav a 2 s  . c  o m
    u.setPassword(null);//make it empty before sending it in response
    data.put("user", u);
    r.setData(data);

    r.getMeta().setMessage(SUCCESS);
    r.getMeta().setStatus(HttpStatus.OK);

    return new ResponseEntity<Result<Map<String, Object>>>(r, HttpStatus.OK);
}

From source file:ch.entwine.weblounge.kernel.security.SpringSecurityFormAuthentication.java

/**
 * {@inheritDoc}/*from w  w  w  . j a  va  2s .c  o m*/
 * 
 * @see org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter#attemptAuthentication(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {

    if (postOnly && !"POSTS".equals(request.getMethod())) {
        throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
    }

    // Get the username
    String username = StringUtils.trimToEmpty(request.getParameter(SPRING_SECURITY_FORM_USERNAME_KEY));

    // Get the password
    String password = request.getParameter(SPRING_SECURITY_FORM_PASSWORD_KEY);
    if (password == null) {
        password = "";
    }

    // Using the extracted credentials, create an authentication request
    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,
            password);
    authRequest.setDetails(authenticationDetailsSource.buildDetails(request));

    // Place the last username attempted into HttpSession for views
    HttpSession session = request.getSession(false);

    if (session != null || getAllowSessionCreation()) {
        request.getSession().setAttribute(SPRING_SECURITY_LAST_USERNAME_KEY,
                TextEscapeUtils.escapeEntities(username));
    }

    return this.getAuthenticationManager().authenticate(authRequest);
}

From source file:org.unidle.web.CurrentUserInterceptorTest.java

@Test
public void testPostHandleWithHandlerMethodWithCorrectBean() throws Exception {

    SecurityContextHolder.getContext()/* w w w  .j a v a  2 s. co  m*/
            .setAuthentication(new UsernamePasswordAuthenticationToken(user.getUuid(), null));

    subject.postHandle(null, null, new HandlerMethod(this, "toString"), modelAndView);

    assertThat(modelAndView.getModel()).satisfies(containsKey((CURRENT_USER.getName())));
}

From source file:org.unidle.social.AnalyticTrackingConnectInterceptorTest.java

@Test
public void testPostConnect() throws Exception {
    SecurityContextHolder.getContext()/* ww w .  j a  v a  2 s .  c  o m*/
            .setAuthentication(new UsernamePasswordAuthenticationToken(user.getUuid(), null));

    subject.postConnect(new ConnectionStub<>(new ConnectionData("provider id", "provider user id",
            "display name", "profile url", "image url", "access token", "secret", "refresh token", 1234L)),
            null);

    assertThat(analytics.trackings.size()).isEqualTo(1);
    assertThat(analytics.trackings.containsKey(user.getUuid())).isTrue();
    assertThat(analytics.trackings.getFirst(user.getUuid()).getLeft()).isEqualTo(CONNECT);
    assertThat(analytics.trackings.getFirst(user.getUuid()).getRight()).contains(PROPERTY_DISPLAY_NAME,
            "display name", PROPERTY_PROVIDER_ID, "provider id", PROPERTY_PROVIDER_USER_ID, "provider user id");
}

From source file:fr.esiea.esieaddress.SpringMvcIntegrationTest.java

@Before
public void setUp() throws Exception {

    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    Authentication auth = new UsernamePasswordAuthenticationToken("test@gmail.com", "pwd");
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(auth);
}

From source file:hsa.awp.campaign.facade.CampaignFacadeSecurityTest.java

/**
 * This constructor sets up the mocks and facade.
 *//*from   w  ww  .jav  a  2 s. c  o m*/
public CampaignFacadeSecurityTest() {

    securityContext = SecurityContextHolder.getContext();
    secretaryAuthentication = new UsernamePasswordAuthenticationToken("secretary", "password");
    adminAuthentication = new UsernamePasswordAuthenticationToken("admin", "password");
    facultyAuthentication = new UsernamePasswordAuthenticationToken("faculty", "password");
    studentAuthentication = new UsernamePasswordAuthenticationToken("student", "password");
}