@Test
  public void testCustomAuthenticationDoesNotAuthenticateWithBootSecurityUser() throws Exception {
    this.context = new AnnotationConfigWebApplicationContext();
    this.context.setServletContext(new MockServletContext());

    this.context.register(
        AuthenticationManagerCustomizer.class,
        SecurityAutoConfiguration.class,
        ServerPropertiesAutoConfiguration.class);
    this.context.refresh();

    SecurityProperties security = this.context.getBean(SecurityProperties.class);
    AuthenticationManager manager = this.context.getBean(AuthenticationManager.class);

    UsernamePasswordAuthenticationToken token =
        new UsernamePasswordAuthenticationToken(
            security.getUser().getName(), security.getUser().getPassword());
    try {
      manager.authenticate(token);
      fail("Expected Exception");
    } catch (AuthenticationException success) {
    }

    token = new UsernamePasswordAuthenticationToken("foo", "bar");
    assertNotNull(manager.authenticate(token));
  }
 @Before
 public void init() {
   AuthenticationManager authenticationManager = this.context.getBean(AuthenticationManager.class);
   this.authentication =
       authenticationManager.authenticate(
           new UsernamePasswordAuthenticationToken("user", "password"));
 }
 private void pingAuthenticationListener() {
   AuthenticationListener listener = new AuthenticationListener();
   this.context.addApplicationListener(listener);
   AuthenticationManager manager = this.context.getBean(AuthenticationManager.class);
   try {
     manager.authenticate(new UsernamePasswordAuthenticationToken("foo", "wrong"));
     fail("Expected BadCredentialsException");
   } catch (BadCredentialsException e) {
     // expected
   }
   assertTrue(
       "Wrong event type: " + listener.event,
       listener.event instanceof AuthenticationFailureBadCredentialsEvent);
 }
 @SuppressWarnings({"ThrowableInstanceNeverThrown"})
 private void useAnonymousIfPossible(
     HttpServletRequest request,
     HttpServletResponse response,
     FilterChain chain,
     SecurityContext securityContext)
     throws IOException, ServletException {
   boolean anonAccessEnabled = context.getAuthorizationService().isAnonAccessEnabled();
   if (anonAccessEnabled || authInterceptors.accept(request)) {
     log.debug("Using anonymous");
     Authentication authentication = getNonUiCachedAuthentication(request);
     if (authentication == null) {
       log.debug("Creating the Anonymous token");
       final UsernamePasswordAuthenticationToken authRequest =
           new UsernamePasswordAuthenticationToken(UserInfo.ANONYMOUS, "");
       AuthenticationDetailsSource ads = new HttpAuthenticationDetailsSource();
       //noinspection unchecked
       authRequest.setDetails(ads.buildDetails(request));
       // explicitly ask for the default spring authentication manager by name (we have another one
       // which
       // is only used by the basic authentication filter)
       AuthenticationManager authenticationManager =
           context.beanForType("authenticationManager", AuthenticationManager.class);
       authentication = authenticationManager.authenticate(authRequest);
       if (authentication != null
           && authentication.isAuthenticated()
           && !RequestUtils.isUiRequest(request)) {
         AuthCacheKey authCacheKey =
             new AuthCacheKey(authFilter.getCacheKey(request), request.getRemoteAddr());
         nonUiAuthCache.put(authCacheKey, authentication);
         log.debug("Added anonymous authentication {} to cache", authentication);
       }
     } else {
       log.debug("Using cached anonymous authentication");
     }
     useAuthentication(request, response, chain, authentication, securityContext);
   } else {
     if (authFilter.acceptEntry(request)) {
       log.debug("Sending request requiring authentication");
       authFilter.commence(
           request,
           response,
           new InsufficientAuthenticationException("Authentication is required"));
     } else {
       log.debug("No filter or entry just chain");
       chain.doFilter(request, response);
     }
   }
 }
Esempio n. 5
0
  /** Authenticate based on username/pass */
  @Override
  public boolean authenticate(String username, String password) {
    String u = username == null ? "" : username;
    String p = password == null ? "" : password;

    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(u, p);

    // Attempt authentication.
    try {
      AuthenticationManager authenticationManager =
          ((EhourWebApplication) getApplication()).getAuthenticationManager();

      if (authenticationManager == null) {
        throw new AuthenticationServiceException("no authentication manager defined");
      }

      Authentication authResult = authenticationManager.authenticate(authRequest);
      setAuthentication(authResult);

      User user = ((AuthUser) authResult.getPrincipal()).getUser();

      auditService.doAudit(
          new Audit()
              .setAuditActionType(AuditActionType.LOGIN)
              .setUser(user)
              .setUserFullName(user.getFullName())
              .setDate(new Date())
              .setSuccess(Boolean.TRUE));

      LOGGER.info("Login by user '" + username + "'.");
      return true;

    } catch (BadCredentialsException e) {
      LOGGER.info("Failed to login for" + " user '" + username + "': " + e.getMessage());
      setAuthentication(null);
      return false;

    } catch (AuthenticationException e) {
      LOGGER.info("Could not authenticate a user", e);
      setAuthentication(null);
      throw e;

    } catch (RuntimeException e) {
      LOGGER.info("Unexpected exception while authenticating a user", e);
      setAuthentication(null);
      throw e;
    }
  }
  private boolean initSession(
      UserProfile user,
      String password,
      boolean requirePassword,
      HttpServletRequest request,
      HttpServletResponse response) {

    Authentication auth;

    try {
      if (requirePassword) {
        UsernamePasswordAuthenticationToken token =
            new UsernamePasswordAuthenticationToken(user.getUsername(), password);
        auth = authenticationManager.authenticate(token);
      } else {
        auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
      }

      context.getLogManager().loggedIn(user);
      SecurityContextHolder.getContext().setAuthentication(auth);
      securityContextRepository.saveContext(SecurityContextHolder.getContext(), request, response);
      rememberMeServices.loginSuccess(request, response, auth);
      request
          .getSession()
          .setAttribute("nquire-it-token", new BigInteger(260, random).toString(32));
    } catch (Exception ex) {
      auth = null;
    }

    return auth != null
        && auth.getPrincipal() != null
        && auth.getPrincipal() instanceof UserProfile;
  }
  @Test
  public void testDefaultUsernamePassword() throws Exception {
    this.context = new AnnotationConfigWebApplicationContext();
    this.context.setServletContext(new MockServletContext());

    this.context.register(SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class);
    this.context.refresh();

    SecurityProperties security = this.context.getBean(SecurityProperties.class);
    AuthenticationManager manager = this.context.getBean(AuthenticationManager.class);

    UsernamePasswordAuthenticationToken token =
        new UsernamePasswordAuthenticationToken(
            security.getUser().getName(), security.getUser().getPassword());
    assertNotNull(manager.authenticate(token));
  }
  @Before
  public void setup() {
    logger.info("setup");

    this.mockMvc =
        MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();

    User user = null;
    try {
      user = userService.findByLogin("johndoe");
    } catch (ServiceException e) {
      logger.error(e.getLocalizedMessage());
    }

    Authentication authentication = null;
    if (user != null) {
      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);
  }
Esempio n. 9
0
  @SuppressWarnings("deprecation")
  public void authenticate(Customer customer, String userName, String password) throws Exception {

    Validate.notNull(customer, "Customer cannot be null");

    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    GrantedAuthority role =
        new GrantedAuthorityImpl(Constants.PERMISSION_CUSTOMER_AUTHENTICATED); // required to login
    authorities.add(role);
    List<Integer> groupsId = new ArrayList<Integer>();
    List<Group> groups = customer.getGroups();
    if (groups != null) {
      for (Group group : groups) {
        groupsId.add(group.getId());
      }

      List<Permission> permissions = permissionService.getPermissions(groupsId);
      for (Permission permission : permissions) {
        GrantedAuthority auth = new GrantedAuthorityImpl(permission.getPermissionName());
        authorities.add(auth);
      }
    }

    Authentication authenticationToken =
        new UsernamePasswordAuthenticationToken(userName, password, authorities);

    Authentication authentication = customerAuthenticationManager.authenticate(authenticationToken);

    SecurityContextHolder.getContext().setAuthentication(authentication);
  }
Esempio n. 10
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;
    }
  }
  @Test
  public void testAuthentication() {

    Authentication request = new UsernamePasswordAuthenticationToken("Stefan.Huber", "blub");
    Authentication result = am.authenticate(request);
    SecurityContextHolder.getContext().setAuthentication(result);

    Object principe = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    JdbcUser user = null;
    if (principe instanceof JdbcUser) {
      user = (JdbcUser) principe;
      logger.info(
          "Successfully logged in User with Username: "******", Fullname: "
              + user.getFirstName()
              + " "
              + user.getLastName());
    }

    assertTrue(user != null);
    assertTrue(
        user.getFirstName().equalsIgnoreCase("stefan")
            && user.getLastName().equalsIgnoreCase("huber"));

    User u = us.getCurrentUser();
    assertTrue(u.getUserURI().equals(user.getUserURI()));
    assertTrue(us.getCurrentUserURI().equals(user.getUserURI()));
    // assertTrue(us.getCurrentUsername().equals(user.getUsername()));

    // Logger.info(user.getClass().);
  }
Esempio n. 12
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 = "/register.json", method = RequestMethod.POST)
  public @ResponseBody Map<String, Object> register(@RequestBody Usuario usuario) {
    Map<String, Object> map = new HashMap();

    if (usuarioService.buscarUsuarioPorCorreo(usuario.getCorreo()) != null) {
      map.put("success", false);
      map.put("error", "El correo ya esta registrado");
    } else {
      try {
        UsernamePasswordAuthenticationToken token =
            new UsernamePasswordAuthenticationToken(usuario.getCorreo(), usuario.getClave());
        usuario.setRol(new Rol(1));
        usuario.setClave(EncryptUtil.toSHA1(usuario.getClave()));
        usuarioService.save(usuario);
        Authentication auth = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(auth);
        map.put("success", true);
      } catch (Exception e) {
        e.printStackTrace();
        map.put("success", false);
        map.put("error", "Error al registrar usuario");
      }
    }

    return map;
  }
Esempio n. 14
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("/"));
 }
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    String authToken = ((HttpServletRequest) request).getHeader("x-auth-token");

    if ((null != authToken)
        && !authToken.trim().equals("")
        && !authToken.trim().equalsIgnoreCase("null")) {
      String strToken = authToken;
      System.out.println("Token: " + strToken);

      if (tokenServiceImpl.validate(strToken)) {
        System.out.println("valid token found");

        User user = tokenServiceImpl.getUserFromToken(strToken);

        UsernamePasswordAuthenticationToken authentication =
            new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        authentication.setDetails(
            new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request));
        SecurityContextHolder.getContext()
            .setAuthentication(authManager.authenticate(authentication));
      } else {
        System.out.println("invalid token");
      }
    } else {
      System.out.println("no token found");
    }

    // continue thru the filter chain
    chain.doFilter(request, response);
  }
Esempio n. 16
0
 private void mockAuthentication() {
   AuthenticationManager authManager = mock(AuthenticationManager.class);
   final Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
   authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
   when(authManager.authenticate(any(Authentication.class)))
       .thenAnswer(
           new Answer<Authentication>() {
             @Override
             public Authentication answer(InvocationOnMock invocation) {
               Authentication auth = (Authentication) invocation.getArguments()[0];
               if (auth.getCredentials().equals("password")) {
                 return new UsernamePasswordAuthenticationToken(
                     auth.getPrincipal(), auth.getCredentials(), authorities);
               }
               throw new BadCredentialsException("wrong password");
             }
           });
   contextMock.putBean("authenticationManager", authManager);
 }
Esempio n. 17
0
  /**
   * Perform user login
   *
   * @param principal
   */
  protected void setupSecurityContext(String principal) {
    logger.entry(principal);
    UsernamePasswordAuthenticationToken preauth =
        new UsernamePasswordAuthenticationToken(principal, "password");
    Authentication auth = authMgr.authenticate(preauth);
    SecurityContextHolder.getContext().setAuthentication(auth);

    logger.info(auth.toString());
    logger.exit();
  }
 /**
  * 权限验证
  *
  * @param username
  * @param password
  * @return
  */
 private Response authentication(String username, String password) {
   try {
     Authentication authentication =
         authenticationManager.authenticate( //
             new UsernamePasswordAuthenticationToken(username, password));
     SecurityContextHolder.getContext().setAuthentication(authentication);
   } catch (AuthenticationException e) {
     return buildErrorResponse(Status.UNAUTHORIZED, e.getMessage());
   }
   return null;
 }
Esempio n. 19
0
  /**
   * Everytime a username and password authentication will return a new access token.
   *
   * @param login
   * @param password
   * @return
   */
  public String login(String login, String password) throws AuthenticationException {

    UsernamePasswordAuthenticationToken authenticationToken =
        new UsernamePasswordAuthenticationToken(login, password);
    // try to validate username and password
    Authentication authentication = authManager.authenticate(authenticationToken);
    // Save the successfully authenticated object in security context.
    SecurityContextHolder.getContext().setAuthentication(authentication);
    // Everytime a username and password authentication will make a new access token.
    return refreshAccessToken(login);
  }
 /**
  * This method will do authentication for the user. return true if successful else return false.
  *
  * @param user
  * @return
  */
 protected final boolean doLogin(UserDetails user) {
   if (user != null && doValidate(user)) {
     user = userGroupService.getUserByUsername(user.getUsername());
     MyFormProperties.getInstance().setUser(user);
     Authentication request =
         new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
     Authentication result = authenticationManager.authenticate(request);
     SecurityContextHolder.getContext().setAuthentication(result);
     return true;
   }
   return false;
 }
Esempio n. 21
0
  public String login() throws ServletException, IOException {
    try {

      AppUser user = new AppUser();
      user.setLogin("admin");
      user.setPassword("password");
      user.addRole(Role.USER.value());
      user.addRole(Role.ADMIN.value());
      getUserSvc().update(user);
      System.out.println("LoginForm" + getUserSvc().getById(userName));

      WebApplicationContext ac =
          WebApplicationContextUtils.getWebApplicationContext(
              (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext());
      AuthenticationManager authenticationManager = ac.getBean(AuthenticationManager.class);
      Authentication authentication =
          authenticationManager.authenticate(
              new UsernamePasswordAuthenticationToken(getUserName(), getPassword()));
      SecurityContextHolder.getContext().setAuthentication(authentication);

      setLoggedUser(authentication.getName());
      setLoggedRole(validateAdmin() ? Role.ADMIN.display() : Role.USER.display());

      getSessionModel().reset();

    } catch (Exception ex) {
      // log.equals(ex.getMessage());
      // ConfigUtil.addMessage("Login Failed: " + ex.getMessage());
      ex.printStackTrace();
      String message = ex.getLocalizedMessage();
      if (message == null) {
        message = "Incorrect user name or password";
      }
      FacesContext.getCurrentInstance()
          .addMessage("growl", new FacesMessage("Error", "Login Failed: " + message));
      return null;
    }

    return ConfigUtil.getSavedUrl() + "?faces-redirect=true";
  }
  @Test
  public void testAttemptAuthentication() throws IOException, ServletException {
    VistaBasicAuthenticationFilter f = new VistaBasicAuthenticationFilter();
    f.setAuthenticationManager(mockAuthenticationManager);
    f.setAuthenticationEntryPoint(authenticationEntryPoint);
    f.afterPropertiesSet();

    String vistaId = "9F2B";
    String division = "500";
    String accessCode = "10VEHU";
    String verifyCode = "VEHU10";

    byte[] token =
        new String(vistaId + ";" + division + ":" + accessCode + ";" + verifyCode)
            .getBytes("UTF-8");
    request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token), "UTF-8"));
    request.setRemoteAddr("10.0.1.34");
    request.setRemoteHost("www.example.org");
    request.setRequestURI("/foo.xml");
    request.setMethod("GET");

    VistaAuthenticationToken authRequest =
        new VistaAuthenticationToken(
            "9F2B", "500", "10VEHU", "VEHU10", "10.0.1.34", "www.example.org");
    when(mockAuthenticationManager.authenticate(AuthenticationTokenMatchers.eq(authRequest)))
        .thenReturn(
            new VistaAuthenticationToken(
                new VistaUser(
                    new RpcHost("localhost"),
                    "9F2B",
                    "500",
                    "500",
                    "12345",
                    "500:10VEHU;VEHU10",
                    "Vehu,Ten",
                    true,
                    true,
                    true,
                    true,
                    new ArrayList<GrantedAuthority>()),
                "500:10VEHU;VEHU10",
                "10.0.1.34",
                null,
                new ArrayList<GrantedAuthority>()));

    f.doFilter(request, response, filterChain);

    assertSame(request, filterChain.getRequest());
    assertSame(response, filterChain.getResponse());

    verify(mockAuthenticationManager).authenticate(AuthenticationTokenMatchers.eq(authRequest));
  }
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    UserDetails userDetails = (UserDetails) authentication.getPrincipal();

    authentication =
        authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(
                userDetails.getUsername(), userDetails.getPassword()));

    SecurityContextHolder.getContext().setAuthentication(authentication);

    return authentication;
  }
Esempio n. 24
0
  private void authenticateUserAndSetSession(Users user, HttpServletRequest request) {
    String username = user.getusername();
    String password = user.getPassword();
    UsernamePasswordAuthenticationToken token =
        new UsernamePasswordAuthenticationToken(username, password);

    // generate session if one doesn't exist
    request.getSession();

    token.setDetails(new WebAuthenticationDetails(request));
    Authentication authenticatedUser = authenticationManager.authenticate(token);

    SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
  }
  @Test
  public void authenticatesWithAuthenticationManager() throws IOException, ServletException {
    final Authentication expectedAuthentication = mock(Authentication.class);
    when(authenticationManager.authenticate(Matchers.<Authentication>any()))
        .thenReturn(expectedAuthentication);

    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getParameter("expiry")).thenReturn("1475037954");
    when(request.getParameter("type")).thenReturn("CMB_SSO:SIMPLE");
    when(request.getParameter("id")).thenReturn("id-" + UUID.randomUUID().toString());
    when(request.getParameter("secret")).thenReturn("secret-" + UUID.randomUUID().toString());

    final Authentication outputAuthentication =
        filter.attemptAuthentication(request, mock(HttpServletResponse.class));
    assertSame(expectedAuthentication, outputAuthentication);
  }
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    try {

      Authentication authentication = tokenExtractor.extract(request);

      if (authentication == null) {
        if (debug) {
          logger.debug("No token in request, will continue chain.");
        }
      } else {
        request.setAttribute(
            OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
        if (authentication instanceof AbstractAuthenticationToken) {
          AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
          needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
        }
        Authentication authResult = authenticationManager.authenticate(authentication);

        if (debug) {
          logger.debug("Authentication success: " + authResult);
        }

        SecurityContextHolder.getContext().setAuthentication(authResult);
      }
    } catch (OAuth2Exception failed) {
      SecurityContextHolder.clearContext();

      if (debug) {
        logger.debug("Authentication request failed: " + failed);
      }

      authenticationEntryPoint.commence(
          request, response, new InsufficientAuthenticationException(failed.getMessage(), failed));

      return;
    }

    chain.doFilter(request, response);
  }
  @RequestMapping(value = "/login.json", method = RequestMethod.POST)
  @ResponseBody
  public Map<String, Object> login(
      @RequestParam("j_username") String username, @RequestParam("j_password") String password) {

    Map<String, Object> map = new HashMap();
    UsernamePasswordAuthenticationToken token =
        new UsernamePasswordAuthenticationToken(username, password);

    try {
      Authentication auth = authenticationManager.authenticate(token);
      SecurityContextHolder.getContext().setAuthentication(auth);
      map.put("success", true);
    } catch (BadCredentialsException e) {
      map.put("success", false);
    }

    return map;
  }
  @Override
  public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    log.info("handle({})", callbacks);
    WSPasswordCallback pwdCallback = (WSPasswordCallback) callbacks[0];

    log.debug("identifier: " + pwdCallback.getIdentifier());
    log.debug("usage: " + pwdCallback.getUsage());
    int usage = pwdCallback.getUsage();

    if (usage == WSPasswordCallback.USERNAME_TOKEN) {
      String password = pwdCallback.getPassword();
      Authentication authentication =
          new UsernamePasswordAuthenticationToken(pwdCallback.getIdentifier(), password);
      authentication = authenticationManager.authenticate(authentication);
      SecurityContextHolder.getContext().setAuthentication(authentication);

      // Return the password to the caller
      pwdCallback.setPassword(password);
    }
  }
 @Override
 public boolean authenticate(LoginInfo loginInfo) {
   try {
     Authentication usernamePasswordAuthentication =
         new UsernamePasswordAuthenticationToken(loginInfo.getUsername(), loginInfo.getPassword());
     Authentication authenticateResult =
         authenticationManager.authenticate(usernamePasswordAuthentication);
     SecurityContextHolder.getContext().setAuthentication(authenticateResult);
     logger.info(
         String.format(
             "Authentication of '%s' was %ssuccessful",
             loginInfo.getUsername(), (authenticateResult.isAuthenticated() ? "" : "not ")));
     return authenticateResult.isAuthenticated();
   } catch (AuthenticationException e) {
     String msg =
         String.format("User '%s' could not authenticated correct:", loginInfo.getUsername());
     logger.info(msg, e);
   }
   return false;
 }
Esempio n. 30
0
 @RequestMapping(value = "/login", method = RequestMethod.GET)
 public String login(String code, Model model) {
   if (code != null) {
     OAuthEntity oAuth = OAuthUtil.getUserInfo(code);
     logger.info("login user: "******"";
     if (user != null) {
       password = user.getPassword();
     } else {
       return "login";
     }
     UsernamePasswordAuthenticationToken authRequest =
         new UsernamePasswordAuthenticationToken(oAuth.getUserId(), password);
     Authentication authentication = authenticationManager.authenticate(authRequest);
     SecurityContextHolder.getContext().setAuthentication(authentication);
     return "app";
   } else {
     return "login";
   }
 }