本文整理汇总了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())));
}