本文整理汇总了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;
}
}
示例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;
}
}
示例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);
}
}
}
示例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();
}
示例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;
}
示例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);
}
示例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);
}
示例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("密码错误~");
}
}
示例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());
}
示例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());
}
示例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));
}
}
示例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));
}