Java 类org.springframework.security.core.AuthenticationException 实例源码

项目:Using-Spring-Oauth2-to-secure-REST    文件:AuthorizationConfig.java   
@Override
public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest tokenRequest) throws AuthenticationException {
    logger.info("refresh token:" + refreshTokenValue);
    String jti = tokenRequest.getRequestParameters().get("jti");
    try {
        if ( jti != null )
                if ( blackListService.isBlackListed(jti) ) return null;


        OAuth2AccessToken token = super.refreshAccessToken(refreshTokenValue, tokenRequest);
        blackListService.addToBlackList(jti);
        return token;
    } catch (TokenBlackListService.TokenNotFoundException e) {
        e.printStackTrace();
        return null;
    }
}
项目:Spring-Security-Third-Edition    文件:CalendarUserAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String email = token.getName();
    CalendarUser user = email == null ? null : calendarService.findUserByEmail(email);
    if(user == null) {
        throw new UsernameNotFoundException("Invalid username/password");
    }
    // Database Password already encrypted:
    String password = user.getPassword();

    boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password);

    if(!passwordsMatch) {
        throw new BadCredentialsException("Invalid username/password");
    }
    Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities);
    return usernamePasswordAuthenticationToken;
}
项目:iotplatform    文件:IoTPErrorResponseHandler.java   
public void handle(Exception exception, HttpServletResponse response) {
  log.debug("Processing exception {}", exception.getMessage(), exception);
  if (!response.isCommitted()) {
    try {
      response.setContentType(MediaType.APPLICATION_JSON_VALUE);

      if (exception instanceof IoTPException) {
        handleThingsboardException((IoTPException) exception, response);
      } else if (exception instanceof AccessDeniedException) {
        handleAccessDeniedException(response);
      } else if (exception instanceof AuthenticationException) {
        handleAuthenticationException((AuthenticationException) exception, response);
      } else {
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        mapper.writeValue(response.getWriter(), IoTPErrorResponse.of(exception.getMessage(),
            IoTPErrorCode.GENERAL, HttpStatus.INTERNAL_SERVER_ERROR));
      }
    } catch (IOException e) {
      log.error("Can't handle exception", e);
    }
  }
}
项目:Spring-Security-Third-Edition    文件:CalendarUserAuthenticationProvider.java   
@Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        DomainUsernamePasswordAuthenticationToken token = (DomainUsernamePasswordAuthenticationToken) authentication;
        String userName = token.getName();
        String domain = token.getDomain();
        String email = userName + "@" + domain;

//        CalendarUser user = email == null ? null : calendarService.findUserByEmail(email);
        CalendarUser user = calendarService.findUserByEmail(email);
        logger.info("calendarUser: {}", user);

        if(user == null) {
            throw new UsernameNotFoundException("Invalid username/password");
        }
        String password = user.getPassword();
        if(!password.equals(token.getCredentials())) {
            throw new BadCredentialsException("Invalid username/password");
        }
        Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user);
        logger.info("authorities: {}", authorities);
        return new DomainUsernamePasswordAuthenticationToken(user, password, domain, authorities);
    }
项目:oasp-tutorial-sources    文件:BaseUserDetailsService.java   
/**
 * Returns the {@link GrantedAuthority}s of the user associated with the provided {@link UserProfile}.
 *
 * @param principal the {@link UserProfile} of the user
 * @return the associated {@link GrantedAuthority}s
 * @throws AuthenticationException if no principal is retrievable for the given {@code username}
 */
protected Set<GrantedAuthority> getAuthorities(UserProfile principal) throws AuthenticationException {

  if (principal == null) {
    LOG.warn("Principal must not be null.");
    throw new IllegalArgumentException();
  }
  // determine granted authorities for spring-security...
  Set<GrantedAuthority> authorities = new HashSet<>();
  Collection<String> accessControlIds = this.principalAccessControlProvider.getAccessControlIds(principal);
  Set<AccessControl> accessControlSet = new HashSet<>();
  for (String id : accessControlIds) {
    boolean success = this.accessControlProvider.collectAccessControls(id, accessControlSet);
    if (!success) {
      LOG.warn("Undefined access control {}.", id);
    }
  }
  for (AccessControl accessControl : accessControlSet) {
    authorities.add(new AccessControlGrantedAuthority(accessControl));
  }
  return authorities;
}
项目:Spring-Security-Third-Edition    文件:CalendarUserAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String email = token.getName();
    CalendarUser user = email == null ? null : calendarService.findUserByEmail(email);
    if(user == null) {
        throw new UsernameNotFoundException("Invalid username/password");
    }
    // Database Password already encrypted:
    String password = user.getPassword();

    boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password);

    if(!passwordsMatch) {
        throw new BadCredentialsException("Invalid username/password");
    }
    Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities);
    return usernamePasswordAuthenticationToken;
}
项目:rest-api-jwt-spring-security    文件:AuthenticationRestController.java   
@RequestMapping(value = "/api/${jwt.route.authentication.path}", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest, Device device) throws AuthenticationException {

    // Perform the security
    final Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(
                    authenticationRequest.getUsername(),
                    authenticationRequest.getPassword()
            )
    );
    SecurityContextHolder.getContext().setAuthentication(authentication);

    // Reload password post-security so we can generate token
    final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
    final String token = "Bearer "+jwtTokenUtil.generateToken(userDetails, device);

    // Return the token
    return ResponseEntity.ok(new JwtAuthenticationResponse(token));
}
项目:Spring-Security-Third-Edition    文件:CalendarUserAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String email = token.getName();
    CalendarUser user = email == null ? null : calendarService.findUserByEmail(email);
    if(user == null) {
        throw new UsernameNotFoundException("Invalid username/password");
    }
    // Database Password already encrypted:
    String password = user.getPassword();

    boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password);

    if(!passwordsMatch) {
        throw new BadCredentialsException("Invalid username/password");
    }
    Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities);
    return usernamePasswordAuthenticationToken;
}
项目:spring-backend-boilerplate    文件:AuthenticationFailureHandlerMvcImpl.java   
@Override
public void onAuthenticationFailure(HttpServletRequest request,
                                    HttpServletResponse response,
                                    AuthenticationException exception) throws IOException, ServletException {
    logger.error(exception, exception);
    AuthEvent userLogin = AuthEventHelper.buildFailedAuthEvent(request, exception);
    userAuditService.saveUserAuthEvent(userLogin);
    String accept = request.getHeader("Accept");
    if (accept != null && accept.contains("application/json")) {
        logger.warn("The ajax request is not authenticated.");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.flushBuffer();
        return;
    }
    super.onAuthenticationFailure(request, response, exception);
}
项目:Spring-Security-Third-Edition    文件:CalendarUserAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String email = token.getName();
    CalendarUser user = email == null ? null : calendarService.findUserByEmail(email);
    if(user == null) {
        throw new UsernameNotFoundException("Invalid username/password");
    }
    // Database Password already encrypted:
    String password = user.getPassword();

    boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password);

    if(!passwordsMatch) {
        throw new BadCredentialsException("Invalid username/password");
    }
    Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities);
    return usernamePasswordAuthenticationToken;
}
项目:nixmash-blog    文件:CustomAuthenticationFailureHandler.java   
@Override
public void onAuthenticationFailure(final HttpServletRequest request,
                                    final HttpServletResponse response, final AuthenticationException exception)
        throws IOException, ServletException {

    setDefaultFailureUrl("/signin?error");
    super.onAuthenticationFailure(request, response, exception);

    String errorMessage = webUI.getMessage(GENERIC_AUTHENTICATION_ERROR_KEY);

    User user = userService.getUserByUsername(request.getParameter(USERNAME));
    if (user != null) {

        String notYetApprovedMessage = webUI.getMessage(NOT_YET_USER_VERIFIED_ERROR_KEY,
                user.getUsername(), user.getEmail());

        if (exception.getMessage().equalsIgnoreCase((USER_IS_DISABLED))) {
            if (user.getUserData().getApprovedDatetime() == null) errorMessage = notYetApprovedMessage;
        }
    }
    request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, errorMessage);
}
项目:ARCLib    文件:JwtTokenProvider.java   
@Override
public JwtToken authenticate(Authentication authentication) throws AuthenticationException {

    JwtToken token = (JwtToken) authentication;

    if (token.getPrincipal() instanceof String) {

        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws((String) token.getPrincipal())
                    .getBody();

            UserDetails user = handler.parseClaims(claims);

            return new JwtToken(user, claims, user.getAuthorities());
        } catch (ClaimJwtException ex) {
            throw new BadCredentialsException("JWT error", ex);
        }
    } else {
        return null;
    }
}
项目:fish-admin    文件:JwtAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    // 获取认证的用户名 & 密码
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();

    User user = userRepository.findByUserName(name);
    if (user == null) throw new UsernameNotFoundException("username not found!");
    if (!user.isEnable()) throw new AuthenticationException("user has been disabled!") {};
    // 认证逻辑
    if (user.validatePassword(password)) {

        // 这里设置权限和角色
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        // authorities.add( new GrantedAuthorityImpl("ROLE_ADMIN") );
        // authorities.add( new GrantedAuthorityImpl("AUTH_WRITE") );
        // 生成令牌
        Authentication auth = new UsernamePasswordAuthenticationToken(name, password, authorities);
        return auth;
    }else {
        throw new BadCredentialsException("密码错误~");
    }
}
项目:kinota-server    文件:AgentAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.notNull(authentication, "No authentication data provided");
    String id = (String) authentication.getPrincipal();
    String key = (String) authentication.getCredentials();

    Agent agent = agentService.retrieveAgent(id);
    if (agent == null) {
        throw new UsernameNotFoundException("Agent not found: " + id);
    }
    if (!StringUtils.equals(key, agent.getKey())) {
        throw new BadCredentialsException("Authentication Failed. Agent ID or Key not valid.");
    }
    User user = new User(id, key, roles);
    return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
}
项目:SpringTutorial    文件:AuthenticationExample.java   
public static void main(String[] args) throws Exception {
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

  while(true) {
    System.out.println("Please enter your username:");
    String name = in.readLine();
    System.out.println("Please enter your password:");
    String password = in.readLine();
    try {
      Authentication request = new UsernamePasswordAuthenticationToken(name, password);
      Authentication result = am.authenticate(request);
      SecurityContextHolder.getContext().setAuthentication(result);
      break;
    } catch(AuthenticationException e) {
      System.out.println("Authentication failed: " + e.getMessage());
    }
  }
  System.out.println("Successfully authenticated. Security context contains: \n" +
            SecurityContextHolder.getContext().getAuthentication());
}
项目:Spring-Security-Third-Edition    文件:CalendarUserAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String email = token.getName();
    CalendarUser user = email == null ? null : calendarService.findUserByEmail(email);
    if(user == null) {
        throw new UsernameNotFoundException("Invalid username/password");
    }
    // Database Password already encrypted:
    String password = user.getPassword();

    boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password);

    if(!passwordsMatch) {
        throw new BadCredentialsException("Invalid username/password");
    }
    Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities);
    return usernamePasswordAuthenticationToken;
}
项目:hauth-java    文件:CustomAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    // 获取认证的用户名 & 密码
    String name = authentication.getName();
    Object pd = authentication.getCredentials();
    if (pd == null) {
        return new UsernamePasswordAuthenticationToken(name, "", new ArrayList<>());
    }
    String password = pd.toString();
    UserLoginEntity userLoginEntity = loginService.loginValidator(name, password);
    // 认证逻辑
    if (userLoginEntity.isFlag()) {
        return getRole(name, password);
    } else {
        logger.info("登录失败,原因是:账号 {}: {}", userLoginEntity.getUsername(), userLoginEntity.getMessage());
        throw new BadCredentialsException(new GsonBuilder().create().toJson(userLoginEntity));
    }
}
项目:kinota-server    文件:AgentAuthenticationFailureHandler.java   
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                       AuthenticationException e) throws IOException, ServletException {
    response.setStatus(HttpStatus.UNAUTHORIZED.value());
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    if (e instanceof BadCredentialsException) {
        mapper.writeValue(response.getWriter(), AgentAuthErrorResponse.of("Invalid username or password",
                AgentAuthErrorCode.Authentication, HttpStatus.UNAUTHORIZED));
    } else if (e instanceof JwtExpiredTokenException) {
        mapper.writeValue(response.getWriter(), AgentAuthErrorResponse.of("Token has expired",
                AgentAuthErrorCode.Jwt_Token_Expired, HttpStatus.UNAUTHORIZED));
    } else if (e instanceof AuthMethodNotSupportedException) {
        mapper.writeValue(response.getWriter(), AgentAuthErrorResponse.of(e.getMessage(),
                AgentAuthErrorCode.Authentication, HttpStatus.UNAUTHORIZED));
    }
    mapper.writeValue(response.getWriter(), AgentAuthErrorResponse.of("Authentication failed",
            AgentAuthErrorCode.Authentication, HttpStatus.UNAUTHORIZED));
}
项目:generator-spring-rest-jwt    文件:_AuthenticationRestController.java   
@RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest, Device device) throws AuthenticationException {

    // Perform the security
    final Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(
                    authenticationRequest.getUsername(),
                    authenticationRequest.getPassword()
            )
    );
    SecurityContextHolder.getContext().setAuthentication(authentication);

    // Reload password post-security so we can generate token
    final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
    final String token = jwtTokenUtil.generateToken(userDetails, device);

    // Return the token
    return ResponseEntity.ok(new JwtAuthenticationResponse(token));
}
项目:Armory    文件:UserJWTController.java   
@PostMapping("/authenticate")
@Timed
public ResponseEntity<?> authorize(@Valid @RequestBody LoginVM loginVM, HttpServletResponse response) {

    UsernamePasswordAuthenticationToken authenticationToken =
        new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword());

    try {
        Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe();
        String jwt = tokenProvider.createToken(authentication, rememberMe);
        response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
        return ResponseEntity.ok(new JWTToken(jwt));
    } catch (AuthenticationException exception) {
        return new ResponseEntity<>(Collections.singletonMap("AuthenticationException",exception.getLocalizedMessage()), HttpStatus.UNAUTHORIZED);
    }
}
项目:infotaf    文件:AjaxLoginProcessingFilter.java   
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
    if (!HttpMethod.POST.name().equals(request.getMethod()) || !WebUtil.isAjax(request)) {
        if(logger.isDebugEnabled()) {
            logger.debug("Authentication method not supported. Request method: " + request.getMethod());
        }
        throw new AuthMethodNotSupportedException("Authentication method not supported");
    }

    LoginRequest loginRequest = objectMapper.readValue(request.getReader(), LoginRequest.class);

    if (StringUtils.isBlank(loginRequest.getUsername()) || StringUtils.isBlank(loginRequest.getPassword())) {
        throw new AuthenticationServiceException("Username or Password not provided");
    }

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword());

    return this.getAuthenticationManager().authenticate(token);
}
项目:Spring-Security-Third-Edition    文件:CalendarUserAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String email = token.getName();
    CalendarUser user = email == null ? null : calendarService.findUserByEmail(email);
    if(user == null) {
        throw new UsernameNotFoundException("Invalid username/password");
    }
    // Database Password already encrypted:
    String password = user.getPassword();

    boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password);

    if(!passwordsMatch) {
        throw new BadCredentialsException("Invalid username/password");
    }
    Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities);
    return usernamePasswordAuthenticationToken;
}
项目:joal    文件:WebSocketAuthenticatorService.java   
public UsernamePasswordAuthenticationToken getAuthenticatedOrFail(final CharSequence username, final CharSequence authToken) throws AuthenticationException {
    if (StringUtils.isBlank(username)) {
        throw new AuthenticationCredentialsNotFoundException("Username was null or empty.");
    }
    if (StringUtils.isBlank(authToken)) {
        throw new AuthenticationCredentialsNotFoundException("Authentication token was null or empty.");
    }
    if (!appSecretToken.equals(authToken)) {
        throw new BadCredentialsException("Authentication token does not match the expected token");
    }

    // Everithing is fine, return an authenticated Authentication. (the constructor with grantedAuthorities auto set authenticated = true)
    // null credentials, we do not pass the password along to prevent security flaw
    return new UsernamePasswordAuthenticationToken(
            username,
            null,
            Collections.singleton((GrantedAuthority) () -> "USER")
    );
}
项目:item-shop-reactive-backend    文件:HttpBasicAuthenticationEntryPoint.java   
@Override
public <T> Mono<T> commence(ServerWebExchange exchange, AuthenticationException e) {        
    ServerHttpResponse response = exchange.getResponse();
    if (exchange.getRequest().getMethod().equals(HttpMethod.OPTIONS)) {
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().set("WWW-Authenticate", "Basic realm=\"Reactive\"");
        response.getHeaders().set("Access-Control-Allow-Credentials", "true");
        response.getHeaders().set("Access-Control-Allow-Headers", "authorization, content-type");
        response.getHeaders().set("Access-Control-Allow-Methods", "POST");
        response.getHeaders().set("Access-Control-Allow-Origin", "http://localhost:3000");
        response.getHeaders().set("Access-Control-Max-Age", "1800");
        return Mono.empty();
    }

    response.setStatusCode(HttpStatus.UNAUTHORIZED);
    response.getHeaders().set("WWW-Authenticate", "Basic realm=\"Reactive\"");
    return Mono.empty();
}
项目:jersey-jwt-springsecurity    文件:JwtAuthenticationEntryPoint.java   
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

    HttpStatus status;
    ApiErrorDetails errorDetails = new ApiErrorDetails();

    if (authException instanceof InvalidAuthenticationTokenException) {
        status = HttpStatus.UNAUTHORIZED;
        errorDetails.setTitle(authException.getMessage());
        errorDetails.setMessage(authException.getCause().getMessage());
    } else {
        status = HttpStatus.FORBIDDEN;
        errorDetails.setTitle(status.getReasonPhrase());
        errorDetails.setMessage(authException.getMessage());
    }

    errorDetails.setStatus(status.value());
    errorDetails.setPath(request.getRequestURI());

    response.setStatus(status.value());
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);

    mapper.writeValue(response.getWriter(), errorDetails);
}
项目:spring-backend-boilerplate    文件:AuthenticationEntryPointMvcImpl.java   
@Override
public void commence(HttpServletRequest request,
                     HttpServletResponse response,
                     AuthenticationException authException) throws IOException, ServletException {
    if (authException != null) {
        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/json")) {
            logger.warn("The ajax request is not authenticated.");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.flushBuffer();
            return;
        }
    }

    super.commence(request, response, authException);
}
项目:spring-auth-example    文件:FooAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication)
    throws AuthenticationException {
  logger.debug(
      "==== Authenticating using FooAuthenticationProvider: " +
          authentication);

  // here goes username/password authentication for Foo
  Response response = userService
      .authenticateFoo(String.valueOf(authentication.getPrincipal()),
          String.valueOf(authentication.getCredentials()));

  if (response.isOk()) {
    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("FOO_READ"));
    authorities.add(new SimpleGrantedAuthority("FOO_WRITE"));
    return new FooUsernamePasswordAuthenticationToken(
        authentication.getPrincipal(), authentication.getCredentials(),
        authorities);
  } else {
    throw new BadCredentialsException("Authentication failed.");
  }
}
项目:unitimes    文件:UniTimeAuthenticationFailureHandler.java   
@Override
public void onAuthenticationFailure(HttpServletRequest request,
        HttpServletResponse response, AuthenticationException exception)
        throws IOException, ServletException {

    // Is already locked?
    if (exception != null && exception instanceof LockedException) {
        super.onAuthenticationFailure(request, response, exception);
        return;
    }

    LoginManager.addFailedLoginAttempt(request.getParameter("j_username"), new Date());

    if (ApplicationProperty.PasswordReset.isTrue() && User.findByUserName(request.getParameter("j_username")) != null)
        request.getSession().setAttribute("SUGGEST_PASSWORD_RESET", true);

    super.onAuthenticationFailure(request, response, exception);
}
项目:Spring-Security-Third-Edition    文件:CalendarUserAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String email = token.getName();
    CalendarUser user = email == null ? null : calendarService.findUserByEmail(email);
    if(user == null) {
        throw new UsernameNotFoundException("Invalid username/password");
    }
    // Database Password already encrypted:
    String password = user.getPassword();

    boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password);

    if(!passwordsMatch) {
        throw new BadCredentialsException("Invalid username/password");
    }
    Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities);
    return usernamePasswordAuthenticationToken;
}
项目:iotplatform    文件:RestAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  Assert.notNull(authentication, "No authentication data provided");

  Object principal = authentication.getPrincipal();
  if (!(principal instanceof UserPrincipal)) {
    throw new BadCredentialsException("Authentication Failed. Bad user principal.");
  }

  UserPrincipal userPrincipal = (UserPrincipal) principal;
  if (userPrincipal.getType() == UserPrincipal.Type.USER_NAME) {
    String username = userPrincipal.getValue();
    String password = (String) authentication.getCredentials();
    return authenticateByUsernameAndPassword(userPrincipal, username, password);
  } else {
    String publicId = userPrincipal.getValue();
    return authenticateByPublicId(userPrincipal, publicId);
  }
}
项目:spring-boot-jwt    文件:UserService.java   
public String signin(String username, String password) {
  try {
    authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
    return jwtTokenProvider.createToken(username, userRepository.findByUsername(username).getRoles());
  } catch (AuthenticationException e) {
    throw new CustomException("Invalid username/password supplied", HttpStatus.UNPROCESSABLE_ENTITY);
  }
}
项目:Spring-Security-Third-Edition    文件:CalendarUserAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String email = token.getName();
    CalendarUser user = email == null ? null : calendarService.findUserByEmail(email);
    if(user == null) {
        throw new UsernameNotFoundException("Invalid username/password");
    }
    // Database Password already encrypted:
    String password = user.getPassword();

    boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password);

    if(!passwordsMatch) {
        throw new BadCredentialsException("Invalid username/password");
    }
    Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities);
    return usernamePasswordAuthenticationToken;
}
项目:spring-io    文件:CustomSignInAdapter.java   
@Override
public String signIn(String userId, Connection<?> connection, NativeWebRequest request){
    try {
        UserDetails user = userDetailsService.loadUserByUsername(userId);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            user,
            null,
            user.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String jwt = tokenProvider.createToken(authenticationToken, false);
        ServletWebRequest servletWebRequest = (ServletWebRequest) request;
        servletWebRequest.getResponse().addCookie(getSocialAuthenticationCookie(jwt));
    } catch (AuthenticationException ae) {
        log.error("Social authentication error");
        log.trace("Authentication exception trace: {}", ae);
    }
    return jHipsterProperties.getSocial().getRedirectAfterSignIn();
}
项目:Spring-Security-Third-Edition    文件:CalendarUserAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String email = token.getName();
    CalendarUser user = email == null ? null : calendarService.findUserByEmail(email);
    if(user == null) {
        throw new UsernameNotFoundException("Invalid username/password");
    }
    // Database Password already encrypted:
    String password = user.getPassword();

    boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password);

    if(!passwordsMatch) {
        throw new BadCredentialsException("Invalid username/password");
    }
    Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities);
    return usernamePasswordAuthenticationToken;
}
项目:SpringBootDemoApp    文件:UserJWTController.java   
@ApiOperation(value = "authorize",notes = "authorize")
@PostMapping("/authenticate")
public ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM, HttpServletResponse response) {

    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword());

    try {
        Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext()
            .setAuthentication(authentication);
        boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe();
        String jwt = tokenProvider.createToken(authentication, rememberMe);
        response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, Constants.BEARER + jwt);
        return ResponseEntity.ok(new JWTToken(jwt));
    } catch (AuthenticationException ae) {
        log.trace("Authentication exception trace: {}", ae);
        return new ResponseEntity<>(Collections.singletonMap("AuthenticationException", ae.getLocalizedMessage()), HttpStatus.UNAUTHORIZED);
    }
}
项目:jwt-security-spring-boot-starter    文件:JWTLoginFilter.java   
@Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {

  Optional<? extends AuthenticationRequestBody> requestBody = Try.of(() ->
    Optional.ofNullable(new ObjectMapper().readValue(httpServletRequest.getInputStream(),
      jwtSecurityProperties.getAuthenticationRequestBody()))
  ).recover(ex ->
    Optional.empty()
  ).get();

  final UsernamePasswordAuthenticationToken token =
    new UsernamePasswordAuthenticationToken(requestBody.map(AuthenticationRequestBody::getLogin).orElse(null),
      requestBody.map(AuthenticationRequestBody::getPassword).orElse(null));

  token.setDetails(requestBody.map(AuthenticationRequestBody::isRememberMe));

  return getAuthenticationManager().authenticate(token);
}
项目:bdf2    文件:DefaultFrameworkService.java   
private void preChecks(UsernamePasswordAuthenticationToken authentication)throws AuthenticationException{
    boolean useCaptcha=Configure.getBoolean("bdf2.useCaptchaForLogin");
    if(useCaptcha){
        String key=ContextHolder.getRequest().getParameter("captcha_");
        if(StringUtils.isNotEmpty(key)){
            String sessionkey=(String)ContextHolder.getHttpSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
            if(sessionkey==null){
                throw new BadCredentialsException("验证码过期");
            }else if(!sessionkey.equals(key)){
                throw new BadCredentialsException("验证码不正确");                    
            }
        }else{
            throw new BadCredentialsException("验证码不能为空");                   
        }
    }
    if (authentication.getPrincipal() == null) {
        throw new BadCredentialsException("Username can not be null");
    }
    if (authentication.getCredentials() == null) {
        throw new BadCredentialsException("password can not be null");
    }
}
项目:Spring-Security-Third-Edition    文件:CalendarUserAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String email = token.getName();
    CalendarUser user = email == null ? null : calendarService.findUserByEmail(email);
    if(user == null) {
        throw new UsernameNotFoundException("Invalid username/password");
    }
    // Database Password already encrypted:
    String password = user.getPassword();

    boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password);

    if(!passwordsMatch) {
        throw new BadCredentialsException("Invalid username/password");
    }
    Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities);
    return usernamePasswordAuthenticationToken;
}
项目:users-service    文件:JwtTokenAuthenticationProcessingFilter.java   
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request,
                                          HttpServletResponse response,
                                          AuthenticationException failed
) throws IOException, ServletException {
    SecurityContextHolder.clearContext();
    failureHandler.onAuthenticationFailure(request, response, failed);
}
项目:users-service    文件:JwtAuthenticationEntryPoint.java   
@Override
public void commence(HttpServletRequest request,
                     HttpServletResponse response,
                     AuthenticationException ex
) throws IOException, ServletException {
    response.sendError(HttpStatus.UNAUTHORIZED.value(), "Unauthorized");
}