当前位置: 首页>>代码示例>>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;未经允许,请勿转载。