@Override public Authentication authenticate(Authentication auth){ Usuario user = userRepository.findByEmail(auth.getName()); if (user == null) { throw new BadCredentialsException("User not found"); } String password = (String) auth.getCredentials(); if (!new BCryptPasswordEncoder().matches(password, user.getContraseña())) { throw new BadCredentialsException("Wrong password"); } List<GrantedAuthority> roles = new ArrayList<>(); for (String role : user.getRol()) { roles.add(new SimpleGrantedAuthority(role)); } return new UsernamePasswordAuthenticationToken(user.getEmail(), password, roles); }
@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; }
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { System.out.println("failure"); String targetUrl = ""; if(exception instanceof BadCredentialsException){ targetUrl = "/login.html?error=" + exception.getMessage(); } else { targetUrl = "/login.html?error=" + true; } if (response.isCommitted()) { System.out.println("Internal problem in redirection"); return; } redirectStrategy.sendRedirect(request, response, targetUrl); }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { // Determine if this AuthenticationProvider's identityProvider should be able to support this AuthenticationRequest boolean tokenOriginatedFromThisIdentityProvider = checkTokenOriginatedFromThisIdentityProvider(authentication); if (!tokenOriginatedFromThisIdentityProvider) { // Returning null indicates to The Spring Security AuthenticationManager that this AuthenticationProvider // cannot authenticate this token and another provider should be tried. return null; } AuthenticationRequestToken authenticationRequestToken = ((AuthenticationRequestToken)authentication); AuthenticationRequest authenticationRequest = authenticationRequestToken.getAuthenticationRequest(); try { AuthenticationResponse authenticationResponse = identityProvider.authenticate(authenticationRequest); if (authenticationResponse == null) { return null; } return buildAuthenticatedToken(authenticationRequestToken, authenticationResponse); } catch (InvalidCredentialsException e) { throw new BadCredentialsException("Identity Provider authentication failed.", e); } }
private String[] extractAndDecodeHeader(String header, HttpServletRequest request) throws IOException { byte[] base64Token = header.substring(6).getBytes("UTF-8"); byte[] decoded; try { decoded = Base64.decode(base64Token); } catch (IllegalArgumentException var7) { throw new BadCredentialsException("Failed to decode basic authentication token"); } String token = new String(decoded, "UTF-8"); int delim = token.indexOf(":"); if (delim == -1) { throw new BadCredentialsException("Invalid basic authentication token"); } else { return new String[]{token.substring(0, delim), token.substring(delim + 1)}; } }
@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(), ErrorResponse.of("Invalid username or password", ErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED)); } else if (e instanceof JwtExpiredTokenException) { mapper.writeValue(response.getWriter(), ErrorResponse.of("Token has expired", ErrorCode.JWT_TOKEN_EXPIRED, HttpStatus.UNAUTHORIZED)); } else if (e instanceof AuthMethodNotSupportedException) { mapper.writeValue(response.getWriter(), ErrorResponse.of(e.getMessage(), ErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED)); } mapper.writeValue(response.getWriter(), ErrorResponse.of("Authentication failed", ErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED)); }
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { try { OAuth2AccessToken accessToken = restTemplate.getAccessToken(); FacebookUser facebookUser = userIdentity.findOrCreateFrom(accessToken); repository.save(facebookUser); Authentication authentication = new UsernamePasswordAuthenticationToken( facebookUser, null, Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))); publish(new AuthenticationSuccessEvent(authentication)); return authentication; } catch (OAuth2Exception e) { BadCredentialsException error = new BadCredentialsException( "Cannot retrieve the access token", e); publish(new OAuth2AuthenticationFailureEvent(error)); throw error; } }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { logger.debug( "==== Authenticating using BarAuthenticationProvider: " + authentication); // here goes username/password authentication for Foo Response response = userService .authenticateBar(String.valueOf(authentication.getPrincipal()), String.valueOf(authentication.getCredentials())); if (response.isOk()) { List<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("BAR_READ")); authorities.add(new SimpleGrantedAuthority("BAR_WRITE")); return new BarUsernamePasswordAuthenticationToken( authentication.getPrincipal(), authentication.getCredentials(), authorities); } else { throw new BadCredentialsException("Authentication failed."); } }
@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."); } }
@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("密码错误~"); } }
@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; } }
@Override public KerberosTicketValidation run() throws Exception { byte[] responseToken = new byte[0]; GSSName gssName = null; GSSContext context = GSSManager.getInstance().createContext((GSSCredential) null); boolean first = true; while (!context.isEstablished()) { if (first) { kerberosTicket = tweakJdkRegression(kerberosTicket); } responseToken = context.acceptSecContext(kerberosTicket, 0, kerberosTicket.length); gssName = context.getSrcName(); if (gssName == null) { throw new BadCredentialsException("GSSContext name of the context initiator is null"); } first = false; } if (!holdOnToGSSContext) { context.dispose(); } return new KerberosTicketValidation(gssName.toString(), servicePrincipal, responseToken, context); }
private void handleAuthenticationException(AuthenticationException authenticationException, HttpServletResponse response) throws IOException { response.setStatus(HttpStatus.UNAUTHORIZED.value()); if (authenticationException instanceof BadCredentialsException) { mapper.writeValue(response.getWriter(), IoTPErrorResponse.of("Invalid username or password", IoTPErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED)); } else if (authenticationException instanceof JwtExpiredTokenException) { mapper.writeValue(response.getWriter(), IoTPErrorResponse.of("Token has expired", IoTPErrorCode.JWT_TOKEN_EXPIRED, HttpStatus.UNAUTHORIZED)); } else if (authenticationException instanceof AuthMethodNotSupportedException) { mapper.writeValue(response.getWriter(), IoTPErrorResponse.of(authenticationException.getMessage(), IoTPErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED)); } mapper.writeValue(response.getWriter(), IoTPErrorResponse.of("Authentication failed", IoTPErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED)); }
public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; UserEntity entity; try { entity = user.authenticate(String.valueOf(auth.getPrincipal()), String.valueOf(auth.getCredentials())); if (entity == null) { throw new NotFoundException(ExceptionConstants.USER_NOT_FOUND); } } catch (Exception e) { throw new BadCredentialsException(ExceptionConstants.PASSWORD_DOES_NOT_MATCH); } return new UsernamePasswordAuthenticationToken(UserParser.toDTO(entity), null, Collections.singletonList(new SimpleGrantedAuthority(entity.getRoles().name()))); }
/** * Implementation of an abstract method defined in the base class. The * additionalAuthenticationChecks() method is called by authenticate() * method of the base class after the invocation of retrieveUser() method. */ @Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { if (authentication.getCredentials() == null) { logger.warn("Authentication failed: no credentials provided"); throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), null); } String presentedPassword = authentication.getCredentials().toString(); if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) { logger.warn("Authentication failed: password does not match stored value"); throw new BadCredentialsException(messages.getMessage("UserDetailsAuthenticationProviderImpl.badCredentials", "Bad credentials"), null); } }
@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()); }
@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)); }
public User parseUserFromToken(String token) { try { String username = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody() .getSubject(); String roleString = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token).getBody().get("roles", String.class); List<SimpleGrantedAuthority> roles = new ArrayList<>(); if (!StringUtils.isEmpty(roleString)) { String[] roleValues = StringUtils.split(roleString, ","); for (String roleValue : roleValues) { roles.add(new SimpleGrantedAuthority(roleValue)); } } return new User(username, token, roles); } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) { throw new BadCredentialsException("Invalid JWT token: ", ex); } catch (ExpiredJwtException expiredEx) { throw new JwtExpiredTokenException("JWT Token expired", expiredEx); } }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName().trim(); String password = authentication.getCredentials().toString().trim(); try { User storedCredentials = userService.testCredentials(username, password); // if user is authenticated return Spring authentication if (storedCredentials != null) { return new UsernamePasswordAuthenticationToken(username, storedCredentials.getPassword(), Arrays.asList(new SimpleGrantedAuthority(storedCredentials.getRole().toString()))); } } catch (IOException e) { logger.error("Error while accessing database", e); } throw new BadCredentialsException("Bad credentials"); }
@ApiOperation("get token") @RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST) public ResponseEntity<TokenRes> createAuthenticationToken(@Valid @ModelAttribute JwtAuthenticationReq authenticationRequest, HttpServletRequest httpServletRequest) throws AuthenticationException { // Perform the security String username = authenticationRequest.getUsername(); UserDetails userDetails = userDetailsService.loadUserByUsername(username); if (!passwordEncoder.matches(authenticationRequest.getPassword(), userDetails.getPassword())) { throw new BadCredentialsException(username); } // For simple validation it is completely sufficient to just check the token integrity. You don't have to call // the database compellingly. Again it's up to you ;) UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest)); LOGGER.info("authenticated user {}, setting security context", username); SecurityContextHolder.getContext().setAuthentication(authentication); // Reload password post-security so we can generate token String token = jwtTokenUtil.generateToken(username); LOGGER.info("username:{},token:{}", username, token); // Return the token return ResponseEntity.ok(new TokenRes(token)); }
@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)); } }
@Override public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String authToken = tokenHelper.getToken(request); if (authToken != null && !skipPathRequest(request, pathsToSkip)) { // get username from token String username = null; try { username = tokenHelper.getUsernameFromToken(authToken); logger.info("[TokenAuthenticationFilter->doFilterInternal] authToken is {} and username is {}", authToken, username); if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { User user = cacheHelper.getSessionUser("session_" + username); if (cacheHelper.getSessionUser("session_" + username) == null) { throw new BadCredentialsException("回话失效,请重新登录"); } // get user UserDetails userDetails = (UserDetails) user;//userDetailsService.loadUserByUsername(username); // create authentication TokenBasedAuthentication authentication = new TokenBasedAuthentication(userDetails); authentication.setToken(authToken); SecurityContextHolder.getContext().setAuthentication(authentication); } } catch (Exception e) { logger.error("[TokenAuthenticationFilter->doFilterInternal] authToken is {} and username is {};" + " error:", authToken, username, e); SecurityContextHolder.getContext().setAuthentication(new AnonAuthentication()); } } else { SecurityContextHolder.getContext().setAuthentication(new AnonAuthentication()); } chain.doFilter(request, response); }
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"); } }
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") ); }
@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); }