public void authenticate(
      OAuthAccessToken oAuthAccessToken, HttpServletRequest request, HttpServletResponse response)
      throws FacebookException, IOException, ServletException {
    Facebook facebook =
        Face4jFactory.getInstance().getFacebookFactory().getInstance(oAuthAccessToken);
    User fbUser = facebook.getCurrentUser();
    PreAuthenticatedAuthenticationToken token =
        new PreAuthenticatedAuthenticationToken(fbUser, null);
    token.setDetails(ads.buildDetails((HttpServletRequest) request));

    try {
      Authentication authentication = authenticationManager.authenticate(token);
      SecurityContextHolder.getContext().setAuthentication(authentication);

      HttpSession session = request.getSession(true);
      session.setAttribute("username", fbUser.getEmail());

      LOG.info("Facebook user " + fbUser.getName());
      if (authentication.getAuthorities().contains(AppRole.NEW_USER)) {
        LOG.debug("New user authenticated. Redirecting to registration page");
        ((HttpServletResponse) response).sendRedirect(REGISTRATION_URL);

        return;
      }

    } catch (AuthenticationException e) {
      failureHandler.onAuthenticationFailure(
          (HttpServletRequest) request, (HttpServletResponse) response, e);

      return;
    }
  }
Example #2
0
 /**
  * 重新加载UserDetails
  *
  * @param username
  * @param request
  */
 public static void reloadUserDetails(String username, HttpServletRequest request) {
   UserDetailServiceImpl userDetailServiceImpl =
       ContextManager.getApplicationContext().getBean(UserDetailServiceImpl.class);
   UserDetails userDetails = userDetailServiceImpl.loadUserByUsername(username);
   PreAuthenticatedAuthenticationToken authentication =
       new PreAuthenticatedAuthenticationToken(
           userDetails, userDetails.getPassword(), userDetails.getAuthorities());
   if (request != null) {
     authentication.setDetails(new WebAuthenticationDetails(request));
   }
   SecurityContextHolder.getContext().setAuthentication(authentication);
 }
  @Test
  public void overrideCreateUserDetails() {
    SubclassPreAuthenticatedGrantedAuthoritiesUserDetailsService service =
        new SubclassPreAuthenticatedGrantedAuthoritiesUserDetailsService();

    PreAuthenticatedAuthenticationToken token =
        new PreAuthenticatedAuthenticationToken(CUSTOM_USERNAME + "NOTSAME", "pass");
    token.setDetails(
        new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
            new MockHttpServletRequest(), AuthorityUtils.createAuthorityList("ROLE_USER")));

    UserDetails userDetails = service.loadUserDetails(token);

    assertThat(userDetails.getUsername()).isEqualTo(CUSTOM_USERNAME);
  }