本文整理匯總了Java中org.springframework.security.authentication.BadCredentialsException類的典型用法代碼示例。如果您正苦於以下問題:Java BadCredentialsException類的具體用法?Java BadCredentialsException怎麽用?Java BadCredentialsException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
BadCredentialsException類屬於org.springframework.security.authentication包,在下文中一共展示了BadCredentialsException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: authenticate
import org.springframework.security.authentication.BadCredentialsException; //導入依賴的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;
}
}
示例2: authenticate
import org.springframework.security.authentication.BadCredentialsException; //導入依賴的package包/類
@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);
}
示例3: authenticate
import org.springframework.security.authentication.BadCredentialsException; //導入依賴的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
示例4: onAuthenticationFailure
import org.springframework.security.authentication.BadCredentialsException; //導入依賴的package包/類
@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);
}
示例5: authenticate
import org.springframework.security.authentication.BadCredentialsException; //導入依賴的package包/類
@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);
}
}
示例6: extractAndDecodeHeader
import org.springframework.security.authentication.BadCredentialsException; //導入依賴的package包/類
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)};
}
}
示例7: onAuthenticationFailure
import org.springframework.security.authentication.BadCredentialsException; //導入依賴的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(), 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));
}
示例8: attemptAuthentication
import org.springframework.security.authentication.BadCredentialsException; //導入依賴的package包/類
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;
}
}
示例9: validateTicket
import org.springframework.security.authentication.BadCredentialsException; //導入依賴的package包/類
@Override
public KerberosTicketValidation validateTicket(byte[] token) throws BadCredentialsException {
boolean validTicket;
try {
validTicket = Arrays.equals(validKerberosTicket.getBytes("UTF-8"), token);
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
if (!validTicket) {
throw new BadCredentialsException(MockKerberosTicketValidator.class.getSimpleName() + " does not validate token");
}
return new KerberosTicketValidation(
"[email protected]",
"HTTP/[email protected]",
null,
null);
}
示例10: authenticate
import org.springframework.security.authentication.BadCredentialsException; //導入依賴的package包/類
@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.");
}
}
示例11: authenticate
import org.springframework.security.authentication.BadCredentialsException; //導入依賴的package包/類
@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.");
}
}
示例12: authenticate
import org.springframework.security.authentication.BadCredentialsException; //導入依賴的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("密碼錯誤~");
}
}
示例13: run
import org.springframework.security.authentication.BadCredentialsException; //導入依賴的package包/類
@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);
}
示例14: handleAuthenticationException
import org.springframework.security.authentication.BadCredentialsException; //導入依賴的package包/類
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));
}
示例15: authenticate
import org.springframework.security.authentication.BadCredentialsException; //導入依賴的package包/類
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())));
}