public static Object getPrincipal() {
   Authentication authentication = getAuthentication();
   if (authentication != null) {
     return authentication.getPrincipal();
   }
   return null;
 }
Пример #2
0
  @RequestMapping(
      value = {"/pay_success_url"},
      method = RequestMethod.POST)
  public void successURL(
      @RequestParam(value = "OutSum", required = true) String outSum,
      @RequestParam(value = "InvId", required = true) String invId,
      @RequestParam(value = "SignatureValue", required = true) String signatureValue,
      @RequestParam(value = "Culture", required = false) String culture)
      throws Exception {

    double _money = Double.parseDouble(outSum);
    long _id = Long.parseLong(invId);

    String md5String = md5SignatureValue(_money, _id, password2, ":Shp_item=" + shp_item);
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetail = (UserDetails) auth.getPrincipal();
    Users u = userService.getRepository().findUsersByLogin(userDetail.getUsername());

    PaymentSystems ps =
        (PaymentSystems) paymentService.getRepository().findPaymentSystemsByUserId(u.getId());
    if (md5String.equals(ps.getKey())) {
      u.setSummaryCash(u.getSummaryCash() + _money);
      userService.getRepository().save(u);
    }
    HttpGet method = new HttpGet(url.concat("?OK").concat(invId));
    HttpClient client = new DefaultHttpClient();
    client.execute(method);
  }
Пример #3
0
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();

    User user = usersService.findByUserName(name);

    if (user == null) {
      throw new BadCredentialsException("Username not found");
    }

    if (!password.equals(user.getPassword())) {
      throw new BadCredentialsException("Wrong password");
    }

    List<UserRole> roles = usersService.getRoles(user);

    Collection<GrantedAuthorityImpl> impls = new ArrayList<GrantedAuthorityImpl>();

    for (UserRole ur : roles) impls.add(new GrantedAuthorityImpl(ur.getRole().getRolename()));

    UserDetails userDetails =
        new org.springframework.security.core.userdetails.User(name, password, impls);

    return new UsernamePasswordAuthenticationToken(userDetails, password, impls);
  }
Пример #4
0
  @RolesAllowed("ROLE_SAMPLE")
  public void logout() {
    final Authentication auth;

    auth = SecurityContextHolder.getContext().getAuthentication();
    log.info("Logout of user '" + auth.getName() + "'");
  }
 protected org.springframework.security.core.Authentication getAuthentification(
     javax.servlet.http.HttpServletRequest request,
     javax.servlet.http.HttpServletResponse response) {
   Authentication auth = mock(Authentication.class);
   when(auth.getPrincipal()).thenReturn(new SecuredUser(getTestUser(), null));
   return auth;
 };
Пример #6
0
 @RequestMapping("/reminder")
 public String displayPage() {
   System.out.println("getting reminder page");
   Authentication auth = SecurityContextHolder.getContext().getAuthentication();
   CurrentUser currentUser = (CurrentUser) auth.getPrincipal(); // get user id
   return "redirect:/a/" + currentUser.getId() + "/reminder";
 }
Пример #7
0
  @RequestMapping(
      value = {"/", "/welcome**"},
      method = RequestMethod.GET)
  public ModelAndView defaultPage() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    ModelAndView model = new ModelAndView();
    if (!(auth instanceof AnonymousAuthenticationToken)) {
      UserDetails userDetail = (UserDetails) auth.getPrincipal();
      model.addObject("nextBeers", nextBeerDAO.getBeers(userDetail.getUsername()));
      model.addObject(
          "hasBeersWithoutDate", nextBeerDAO.hasBeersWithoutDate(userDetail.getUsername()));
      model.setViewName("homeLogged");
    } else {
      model.setViewName("home");
    }
    NextBeer nextestBeer = nextBeerDAO.getNextBeer();
    Calendar today = Calendar.getInstance();
    today.set(Calendar.HOUR_OF_DAY, 23);
    today.set(Calendar.MINUTE, 59);
    if (nextestBeer != null && today.before(nextestBeer.getDateToPay())) {
      model.addObject("dateToPayNextBeers", nextestBeer.getDateToPay());
    }
    model.addObject("allNextBeers", nextBeerDAO.getAllNextBeers());

    return model;
  }
  @Override
  public Authentication attemptAuthentication(
      HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

    try {
      // call to daoAuthenticationProvider
      Authentication auth = super.attemptAuthentication(request, response);

      // store currentUser in HttpSession
      UserCredentials currentUser = userService.findByName(auth.getName());
      request.getSession().setAttribute(Constants.CURRENT_USER, currentUser);

      // display info about currentUser
      Collection<GrantedAuthority> gs = auth.getAuthorities();
      StringBuilder sb =
          new StringBuilder("===== Authentification Succesful : userName = "******" with roles: ");
      for (GrantedAuthority x : gs) {
        sb.append(x.getAuthority()).append(",");
      }
      log.info(sb.toString());
      return auth;
    } catch (AuthenticationException e) {
      log.info("Login wasn't successful for " + obtainUsername(request));
      throw e;
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see org.springframework.web.method.support.HandlerMethodArgumentResolver#resolveArgument(
   * org.springframework.core.MethodParameter,
   * org.springframework.web.method.support.ModelAndViewContainer,
   * org.springframework.web.context.request.NativeWebRequest,
   * org.springframework.web.bind.support.WebDataBinderFactory)
   */
  @Override
  public Object resolveArgument(
      MethodParameter parameter,
      ModelAndViewContainer mavContainer,
      NativeWebRequest webRequest,
      WebDataBinderFactory binderFactory)
      throws Exception {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
      return null;
    }
    Object details = authentication.getDetails();
    if (details != null && !parameter.getParameterType().isAssignableFrom(details.getClass())) {
      AuthenticationDetails authenticationDetails =
          findMethodAnnotation(AuthenticationDetails.class, parameter);
      if (authenticationDetails.errorOnInvalidType()) {
        throw new ClassCastException(
            details + " is not assiable to " + parameter.getParameterType());
      } else {
        return null;
      }
    }
    return details;
  }
Пример #10
0
 public Authentication authenticate(Authentication auth) throws AuthenticationException {
   if (auth.getName().equals(auth.getCredentials())) {
     return new UsernamePasswordAuthenticationToken(
         auth.getName(), auth.getCredentials(), AUTHORITIES);
   }
   throw new BadCredentialsException("Bad Credentials");
 }
  private void loginUser(Authentication authentication) {
    if (authentication == null) return;

    if (!(authentication.getPrincipal() instanceof Person)) return;

    Person person = (Person) authentication.getPrincipal();
    String username = person.getUsername();
    String name = person.getName();

    if (authentication.getDetails() instanceof WebAuthenticationDetails) {
      WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();

      String ip = details.getRemoteAddress();
      String sessionId = details.getSessionId();

      if (onLineManager.getOnlineUser(sessionId) != null) return;

      onLineManager.loginUser(ip, sessionId, person);

      logManager.log(username, name, ip, "登录系统", "");

      if (logger.isDebugEnabled())
        logger.debug(
            "用户 {}[{}] 登录系统,登录IP:{},session:{}", new Object[] {name, username, ip, sessionId});
    }
  }
Пример #12
0
  @Override
  public boolean changePassword(String password, Session session) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = authentication.getName();
    JSONObject o = new JSONObject(password);
    String currentPass = o.getString("currentPass");
    String newPass = o.getString("newPass");
    String hQLquey =
        new StringBuilder("update Users set password="******":newpass")
            .append(" where username=:username")
            .toString();
    if (authentication.isAuthenticated() && Utils.verifyPassword(username, currentPass, session)) {
      int status =
          session
              .createQuery(hQLquey)
              .setString("newpass", Utils.encryptPass(newPass))
              .setString("username", username)
              .executeUpdate();

      if (status == 1) {

        return true;
      }
    }

    return false;
  }
Пример #13
0
  @Override
  public UserProfile getUser(Authentication authentication) {
    Object userName = authentication.getPrincipal();
    String login;
    User auth = null;
    if (userName instanceof String) login = (String) userName;
    else {
      login = ((User) authentication.getPrincipal()).getUsername();
      auth = (User) authentication.getPrincipal();
    }

    UserProfile userProfile = new UserProfile();
    userProfile.setUserId(login);
    userProfile.setStatus("ENABLED");

    if (auth != null && !auth.getAuthorities().isEmpty()) {
      for (GrantedAuthority grantedAuthority : auth.getAuthorities()) {
        userProfile.addUserRole(grantedAuthority.getAuthority());
      }
    }
    if (auth != null) {
      SystemUser sysUser = systemUserService.findByLogin(login);
      if (sysUser != null) {
        userProfile.setApiKey(sysUser.getApiKey());
        userProfile.setCompany(sysUser.getCompany().getName());
      }
    }

    return userProfile;
  }
  @RequestMapping(value = "/grids/{id}")
  public String getGrid(@PathVariable("id") int id, Model model) {
    model.addAttribute("pageTitle", "Lista Grids");
    this.setActiveButton(1, model);
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String email = auth.getName(); // get logged in username
    Practitioner p = this.practitionerService.getPractitionerByEmail(email);
    List<Project> projects = this.practitionerService.getProjectsForPractitioner(p);
    Grid tempGrid = null;
    String chart = "";
    try {
      tempGrid = this.gridService.getGridById(id);
      if (projects.contains(tempGrid.getProject())) {
        chart = createChart(tempGrid);
        model.addAttribute("grid", tempGrid);
        model.addAttribute("gridTreeString", chart);

      } else {
        model.addAttribute("error", "You cannot acces to this grid");
      }
    } catch (Exception e) {
      model.addAttribute("error", "Grid not found");
    }
    return "grids";
  }
  public Authentication authenticate(Authentication auth) throws UsernameNotFoundException {

    /** Init a database user object */
    try {
      employeeEntity = employeeDao.findByLogin(auth.getName());
    } catch (RuntimeException e) {
      throw new BadCredentialsException(
          this.messageSource.getMessage(
              "auth.no_user", new Object[] {"userName"}, "Access denied", Locale.getDefault()));
    }

    /** Checking if user account is active */
    if (employeeEntity.getActive() == 0) {
      throw new BadCredentialsException(
          this.messageSource.getMessage(
              "auth.expired", new Object[] {"active"}, "Access denied", Locale.getDefault()));
    }

    /** Compare passwords Make sure to encode the password first before comparing */
    if (!passwordEncoder.isPasswordValid(
        employeeEntity.getPassword(), (String) auth.getCredentials(), null)) {
      throw new BadCredentialsException(
          this.messageSource.getMessage(
              "auth.wrong", new Object[] {"password"}, "Access denied", Locale.getDefault()));
    }

    /**
     * main logic of Authentication manager
     *
     * @return UsernamePasswordAuthenticationToken
     */
    userAccessLogger.debug("User is located!");
    return new UsernamePasswordAuthenticationToken(
        auth.getName(), auth.getCredentials(), getAuthorities(employeeEntity.getAdmin()));
  }
 Authentication windowsAuthentication(final Authentication authentication) {
   String name = authentication.getName();
   String password = authentication.getCredentials().toString();
   WindowsAuthProviderImpl authenticationProvider = new WindowsAuthProviderImpl();
   IWindowsIdentity loggedOnUser = authenticationProvider.logonUser(name, password);
   return loggedOnUser.isGuest() ? getAuthentication(authentication) : null;
 }
  public Request init(Request request) {
    // see if we have an env map already parsed in the request
    Object obj = request.getKvp().get("env");
    Map<String, Object> envVars = null;
    if (obj instanceof Map) {
      envVars = (Map) obj;
    }

    // inject the current user in it
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null && !(auth instanceof AnonymousAuthenticationToken)) {
      String name = auth.getName();
      if (envVars == null) {
        envVars = new HashMap<String, Object>();
      }
      envVars.put("GSUSER", name);
    }

    // set it into the EnvFunction
    if (envVars != null) {
      EnvFunction.setLocalValues(envVars);
    }

    return request;
  }
  // 要不要PreApproval??
  @Override
  public AuthorizationRequest checkForPreApproval(
      AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
    boolean approved = false;
    String clientId = authorizationRequest.getClientId();
    Set<String> scopes = authorizationRequest.getScope();

    OAuth2Request storedOAuth2Request = requestFactory.createOAuth2Request(authorizationRequest);

    OAuth2Authentication authentication =
        new OAuth2Authentication(storedOAuth2Request, userAuthentication);
    if (logger.isDebugEnabled()) {
      StringBuilder builder = new StringBuilder("Looking up existing token for ");
      builder.append("client_id=" + clientId);
      builder.append(", scope=" + scopes);
      builder.append(" and username="******"Existing access token=" + accessToken);
    if (accessToken != null && !accessToken.isExpired()) {
      logger.debug("User already approved with token=" + accessToken);
      approved = true;
    } else {
      logger.debug("Checking explicit approval");
      approved = userAuthentication.isAuthenticated() && approved;
    }

    authorizationRequest.setApproved(approved);
    return authorizationRequest;
  }
  /**
   * Basic implementation just requires the authorization request to be explicitly approved and the
   * user to be authenticated.
   *
   * @param authorizationRequest The authorization request.
   * @param userAuthentication the current user authentication
   * @return Whether the specified request has been approved by the current user.
   */
  public boolean isApproved(
      AuthorizationRequest authorizationRequest, Authentication userAuthentication) {

    String flag = authorizationRequest.getApprovalParameters().get(approvalParameter);
    boolean approved = flag != null && flag.toLowerCase().equals("true");

    OAuth2Authentication authentication =
        new OAuth2Authentication(authorizationRequest, userAuthentication);
    if (logger.isDebugEnabled()) {
      StringBuilder builder = new StringBuilder("Looking up existing token for ");
      builder.append("client_id=" + authorizationRequest.getClientId());
      builder.append(", scope=" + authorizationRequest.getScope());
      builder.append(" and username="******"Existing access token=" + accessToken);
    if (accessToken != null && !accessToken.isExpired()) {
      logger.debug("User already approved with token=" + accessToken);
      // A token was already granted and is still valid, so this is already approved
      approved = true;
    } else {
      logger.debug("Checking explicit approval");
      approved = userAuthentication.isAuthenticated() && approved;
    }

    return approved;
  }
Пример #20
0
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();
    Authentication auth = null;

    Iterator<Shop> accounts =
        HibernateEntityHelper.all(Shop.class)
            .stream()
            .filter(a -> a.getLogin().equals(name))
            .iterator();

    while (accounts.hasNext()) {
      Shop account = accounts.next();
      Boolean check = false;
      try {
        check = PasswordHasher.validatePassword(password, account.getPasswordHash());
      } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        // @TODO
        // Hoe vanuit hier een exception opvangen / communiceren naar gebruiker?
      }

      if (check) {
        List<GrantedAuthority> grantedAuths = new ArrayList();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_PHOTOGRAPHER"));
        auth = new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
      }
    }

    return auth;
  }
  @Override
  public UserDetails loadUserDetails(Authentication token) throws UsernameNotFoundException {
    ProfileUserDetails userDetails = null;
    String username = token.getName();
    String password = token.getCredentials().toString();

    try {
      String appToken =
          profileClient.getAppToken(crafterProfileAppUsername, crafterProfileAppPassword);
      // Tenant tenant = profileClient.getTenantByName(appToken, crafterProfileAppTenantName);
      // authenticate (if the user is inactive, this will also fail)
      profileClient.getTicket(appToken, username, password, crafterProfileAppTenantName);

      Profile profile =
          profileClient.getProfileByUsernameWithAllAttributes(
              appToken, username, crafterProfileAppTenantName);

      userDetails = new ProfileUserDetails(profile, getAuthorities(profile));

    } catch (AppAuthenticationFailedException e) {
      log.error("Error authenticating at app level=" + username);
      throw new BadCredentialsException("Error authenticating username="******"Error authenticating username="******"Error authenticating username=" + username, e);
    }

    return userDetails;
  }
  @Override
  public Authentication authenticate(Authentication a) throws AuthenticationException {
    FacebookUserDTO fud = (FacebookUserDTO) a.getPrincipal();
    String credentials = (String) a.getCredentials();

    // fetch user from our DB
    FacebookUser user = usersService.getByFacebookId(fud.getFacebookProfileId());

    // checking according to spring security documentation
    if (user.isDisabled()) {
      logger.info("Account disabled: " + user);
      throw new DisabledException("Konto wyłączone");
    }
    if (user.isLocked()) {
      logger.info("Account locked: " + user);
      throw new LockedException("Konto zablokowane");
    }

    // if user is allowed to access - allow him :)
    List<GrantedAuthority> authorities = usersService.getUsersAuthorities(user);
    logger.info("User granted authorities=" + authorities);

    // fetch profile of logged user and fill information from his profile
    Facebook facebook = new FacebookTemplate(fud.getAccessToken());
    FacebookProfile facebookProfile = facebook.userOperations().getUserProfile();
    fillUserData(user, facebookProfile);
    user.setAccessToken(fud.getAccessToken());

    Authentication auth = new UsernamePasswordAuthenticationToken(user, credentials, authorities);
    logger.info("Authentication completed: " + auth);
    return auth;
  }
Пример #23
0
  public static UserAccount getPrincipal() {
    UserAccount result;
    SecurityContext context;
    Authentication authentication;
    Object principal;

    // If the asserts in this method fail, then you're
    // likely to have your Tomcat's working directory
    // corrupt. Please, clear your browser's cache, stop
    // Tomcat, update your Maven's project configuration,
    // clean your project, clean Tomcat's working directory,
    // republish your project, and start it over.

    context = SecurityContextHolder.getContext();
    Assert.notNull(context);
    authentication = context.getAuthentication();
    Assert.notNull(authentication);
    principal = authentication.getPrincipal();
    Assert.isTrue(principal instanceof UserAccount);
    result = (UserAccount) principal;
    Assert.notNull(result);
    Assert.isTrue(result.getId() != 0);

    return result;
  }
Пример #24
0
 @RequestMapping(value = "/login_process", method = RequestMethod.POST)
 public ModelAndView loginProcess(
     @RequestParam("nick") final String username,
     @RequestParam("passwd") final String password,
     HttpServletRequest request,
     HttpServletResponse response)
     throws Exception {
   UsernamePasswordAuthenticationToken token =
       new UsernamePasswordAuthenticationToken(username, password);
   try {
     UserDetailsImpl details = (UserDetailsImpl) userDetailsService.loadUserByUsername(username);
     token.setDetails(details);
     Authentication auth = authenticationManager.authenticate(token);
     UserDetailsImpl userDetails = (UserDetailsImpl) auth.getDetails();
     if (!userDetails.getUser().isActivated()) {
       throw new AccessViolationException("User not activated");
     }
     SecurityContextHolder.getContext().setAuthentication(auth);
     rememberMeServices.loginSuccess(request, response, auth);
     AuthUtil.updateLastLogin(auth, userDao);
   } catch (Exception e) {
     return new ModelAndView(new RedirectView("/login.jsp?error=true"));
   }
   return new ModelAndView(new RedirectView("/"));
 }
Пример #25
0
  @Override
  public void savePayrolls(EmployeePayrollList payrolls) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    User user = (User) auth.getPrincipal();

    String savePayrollsQuery =
        "insert into employee_payroll(reg_no, emp_name, date, basic_salary, gross_pay, loan_deduction, other_deduction, created_by, created_on, net_salary, last_updated_by, last_updated_on) values(?,?,?,?,?,?,?,?,?,?,?,?)";
    System.out.println(payrolls.getMonth() + " " + payrolls.getYear());
    for (int i = 0; i < payrolls.getPayrolls().size(); i++) {
      EmployeePayroll payroll = payrolls.getPayrolls().get(i);
      jdbcTemplate.update(
          savePayrollsQuery,
          new Object[] {
            payroll.getRegNum(),
            payroll.getName(),
            payrolls.getMonth() + " " + payrolls.getYear(),
            payroll.getBasicSalary(),
            payroll.getGrossPay(),
            payroll.getLoanDeduction(),
            payroll.getOtherDeduction(),
            payroll.getCreatedBy(),
            payroll.getCreatedOn(),
            payroll.getNetSalary(),
            user.getUsername(),
            user.getUsername()
          });
    }
  }
Пример #26
0
  @RequestMapping(value = "/ajax_login_process", method = RequestMethod.POST)
  public HttpEntity<LoginStatus> loginAjax(
      @RequestParam("nick") final String username,
      @RequestParam("passwd") final String password,
      HttpServletRequest request,
      HttpServletResponse response) {
    UsernamePasswordAuthenticationToken token =
        new UsernamePasswordAuthenticationToken(username, password);
    try {
      UserDetailsImpl details = (UserDetailsImpl) userDetailsService.loadUserByUsername(username);
      token.setDetails(details);
      Authentication auth = authenticationManager.authenticate(token);
      UserDetailsImpl userDetails = (UserDetailsImpl) auth.getDetails();
      if (!userDetails.getUser().isActivated()) {
        return entity(new LoginStatus(false, "User not activated"));
      }
      SecurityContextHolder.getContext().setAuthentication(auth);
      rememberMeServices.loginSuccess(request, response, auth);
      AuthUtil.updateLastLogin(auth, userDao);

      return entity(new LoginStatus(auth.isAuthenticated(), auth.getName()));
    } catch (LockedException e) {
      return entity(new LoginStatus(false, "User locked"));
    } catch (UsernameNotFoundException e) {
      return entity(new LoginStatus(false, "Bad credentials"));
    } catch (BadCredentialsException e) {
      return entity(new LoginStatus(false, e.getMessage()));
    }
  }
  @RequestMapping(
      value = "/{id}",
      method = RequestMethod.GET,
      produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
  public String readResourceSet(@PathVariable("id") Long id, Model m, Authentication auth) {
    ensureOAuthScope(auth, SystemScopeService.UMA_PROTECTION_SCOPE);

    ResourceSet rs = resourceSetService.getById(id);

    if (rs == null) {
      m.addAttribute("code", HttpStatus.NOT_FOUND);
      m.addAttribute("error", "not_found");
      return JsonErrorView.VIEWNAME;
    } else {

      rs = validateScopes(rs);

      if (!auth.getName().equals(rs.getOwner())) {

        logger.warn(
            "Unauthorized resource set request from wrong user; expected "
                + rs.getOwner()
                + " got "
                + auth.getName());

        // it wasn't issued to this user
        m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
        return JsonErrorView.VIEWNAME;
      } else {
        m.addAttribute(JsonEntityView.ENTITY, rs);
        return ResourceSetEntityView.VIEWNAME;
      }
    }
  }
  @RequestMapping(value = "/group/create/invite", method = RequestMethod.POST)
  public String grpCrtInvite(
      @ModelAttribute("rootData") RootBean bean, Model model, Principal principal)
      throws Exception {

    initilize.exec();

    // ログインアカウントのUserNameを取得
    Authentication authentication = (Authentication) principal;
    UserDetails userDetails = (UserDetails) authentication.getPrincipal();
    String userName = userDetails.getUsername();

    /*グループを新規作成(MEMBERには、ログインアカウントのみをセット)し、
    ログインアカウント以外のーザを取得*/
    grpCrtInviteCommand.preProc(bean);
    grpCrtInviteCommand.exec(userName);
    this.bean = grpCrtInviteCommand.postProc();

    // ログインアカウント以外のユーザを画面にセット
    model.addAttribute("rootData", bean);

    finalize.exec(bean, CommonConstants.VIEW_INVITE_MEMBER);

    return "groupInviteMember";
  }
Пример #29
0
  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;
    }
  }
Пример #30
0
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    final UsernamePasswordAuthenticationToken userToken =
        (UsernamePasswordAuthenticationToken) authentication;
    String username = userToken.getName();
    String password = (String) authentication.getCredentials();

    if (!StringUtils.hasLength(username)) {
      throw new BadCredentialsException("Empty Username");
    }

    // FbsIdAuthenticationToken authToken = (FbsIdAuthenticationToken) authentication;

    User user = null;
    Map<String, Object> map = new Hashtable<String, Object>();
    UserAccountManagerBD userAccountManagerBD = new UserAccountManagerBD();
    try {
      user = userAccountManagerBD.getUserByLoginId(username);
      user.setUserId(user.getId());
    } catch (UserAccountManagementException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    /** Here will set Authentication object principal and cridential value * */
    UsernamePasswordAuthenticationToken result =
        new UsernamePasswordAuthenticationToken(user, password);
    result.setDetails(authentication.getDetails());
    return result;
  }