當前位置: 首頁>>代碼示例>>Java>>正文


Java AuthenticationException類代碼示例

本文整理匯總了Java中org.springframework.security.core.AuthenticationException的典型用法代碼示例。如果您正苦於以下問題:Java AuthenticationException類的具體用法?Java AuthenticationException怎麽用?Java AuthenticationException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


AuthenticationException類屬於org.springframework.security.core包,在下文中一共展示了AuthenticationException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: refreshAccessToken

import org.springframework.security.core.AuthenticationException; //導入依賴的package包/類
@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;
    }
}
 
開發者ID:tinmegali,項目名稱:Using-Spring-Oauth2-to-secure-REST,代碼行數:18,代碼來源:AuthorizationConfig.java

示例2: authenticate

import org.springframework.security.core.AuthenticationException; //導入依賴的package包/類
@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;
}
 
開發者ID:PacktPublishing,項目名稱:Spring-Security-Third-Edition,代碼行數:21,代碼來源:CalendarUserAuthenticationProvider.java

示例3: authenticate

import org.springframework.security.core.AuthenticationException; //導入依賴的package包/類
@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;
    }
}
 
開發者ID:LIBCAS,項目名稱:ARCLib,代碼行數:24,代碼來源:JwtTokenProvider.java

示例4: handle

import org.springframework.security.core.AuthenticationException; //導入依賴的package包/類
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);
    }
  }
}
 
開發者ID:osswangxining,項目名稱:iotplatform,代碼行數:23,代碼來源:IoTPErrorResponseHandler.java

示例5: commence

import org.springframework.security.core.AuthenticationException; //導入依賴的package包/類
@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();
}
 
開發者ID:guilhebl,項目名稱:item-shop-reactive-backend,代碼行數:19,代碼來源:HttpBasicAuthenticationEntryPoint.java

示例6: authenticate

import org.springframework.security.core.AuthenticationException; //導入依賴的package包/類
@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);
    }
 
開發者ID:PacktPublishing,項目名稱:Spring-Security-Third-Edition,代碼行數:23,代碼來源:CalendarUserAuthenticationProvider.java

示例7: getAuthorities

import org.springframework.security.core.AuthenticationException; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:oasp,項目名稱:oasp-tutorial-sources,代碼行數:29,代碼來源:BaseUserDetailsService.java

示例8: createAuthenticationToken

import org.springframework.security.core.AuthenticationException; //導入依賴的package包/類
@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));
}
 
開發者ID:adriano-fonseca,項目名稱:rest-api-jwt-spring-security,代碼行數:20,代碼來源:AuthenticationRestController.java

示例9: onAuthenticationFailure

import org.springframework.security.core.AuthenticationException; //導入依賴的package包/類
@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);
}
 
開發者ID:melthaw,項目名稱:spring-backend-boilerplate,代碼行數:17,代碼來源:AuthenticationFailureHandlerMvcImpl.java

示例10: onAuthenticationFailure

import org.springframework.security.core.AuthenticationException; //導入依賴的package包/類
@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);
}
 
開發者ID:mintster,項目名稱:nixmash-blog,代碼行數:23,代碼來源:CustomAuthenticationFailureHandler.java

示例11: authenticate

import org.springframework.security.core.AuthenticationException; //導入依賴的package包/類
@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("密碼錯誤~");
    }
}
 
開發者ID:myliang,項目名稱:fish-admin,代碼行數:24,代碼來源:JwtAuthenticationProvider.java

示例12: authenticate

import org.springframework.security.core.AuthenticationException; //導入依賴的package包/類
@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());
}
 
開發者ID:kinota,項目名稱:kinota-server,代碼行數:17,代碼來源:AgentAuthenticationProvider.java

示例13: main

import org.springframework.security.core.AuthenticationException; //導入依賴的package包/類
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());
}
 
開發者ID:Illusionist80,項目名稱:SpringTutorial,代碼行數:21,代碼來源:AuthenticationExample.java

示例14: authenticate

import org.springframework.security.core.AuthenticationException; //導入依賴的package包/類
@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));
    }
}
 
開發者ID:hzwy23,項目名稱:hauth-java,代碼行數:19,代碼來源:CustomAuthenticationProvider.java

示例15: onAuthenticationFailure

import org.springframework.security.core.AuthenticationException; //導入依賴的package包/類
@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));
}
 
開發者ID:kinota,項目名稱:kinota-server,代碼行數:19,代碼來源:AgentAuthenticationFailureHandler.java


注:本文中的org.springframework.security.core.AuthenticationException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。