private SecurityUser authenticateByUserId(UserId userId) {
User user = userService.findUserById(userId);
if (user == null) {
throw new UsernameNotFoundException("User not found by refresh token");
}
UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId());
if (userCredentials == null) {
throw new UsernameNotFoundException("User credentials not found");
}
if (!userCredentials.isEnabled()) {
throw new DisabledException("User is not active");
}
if (user.getAuthority() == null)
throw new InsufficientAuthenticationException("User has no authority assigned");
UserPrincipal userPrincipal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), userPrincipal);
return securityUser;
}
java类org.springframework.security.authentication.DisabledException的实例源码
RefreshTokenAuthenticationProvider.java 文件源码
项目:iotplatform
阅读 31
收藏 0
点赞 0
评论 0
AuthenticationFailure.java 文件源码
项目:reporting-tool
阅读 23
收藏 0
点赞 0
评论 0
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
AuthenticationException e) throws IOException, ServletException {
if (LOG.isTraceEnabled()) {
LOG.trace("Login failed for user {}.", httpServletRequest.getParameter(SecurityConstants.USERNAME_PARAM));
}
final LoginStatus status = new LoginStatus(false, false, null, e.getMessage());
if (e instanceof LockedException) {
status.setErrorId("login.locked");
} else if (e instanceof DisabledException) {
status.setErrorId("login.disabled");
} else if (e instanceof UsernameNotFoundException) {
status.setErrorId("login.error");
}
mapper.writeValue(httpServletResponse.getOutputStream(), status);
}
ActiveDirectoryAliasLdapAuthenticationProvider.java 文件源码
项目:parking-api
阅读 22
收藏 0
点赞 0
评论 0
private void raiseExceptionForErrorCode(int code, NamingException exception) {
String hexString = Integer.toHexString(code);
Throwable cause = new ActiveDirectoryAuthenticationException(hexString,
exception.getMessage(), exception);
switch (code) {
case PASSWORD_EXPIRED:
throw new CredentialsExpiredException(messages.getMessage(
"LdapAuthenticationProvider.credentialsExpired",
"User credentials have expired"), cause);
case ACCOUNT_DISABLED:
throw new DisabledException(messages.getMessage(
"LdapAuthenticationProvider.disabled", "User is disabled"), cause);
case ACCOUNT_EXPIRED:
throw new AccountExpiredException(messages.getMessage(
"LdapAuthenticationProvider.expired", "User account has expired"),
cause);
case ACCOUNT_LOCKED:
throw new LockedException(messages.getMessage(
"LdapAuthenticationProvider.locked", "User account is locked"), cause);
default:
throw badCredentials(cause);
}
}
AuthenticationEvaluatorImpl.java 文件源码
项目:engerek
阅读 31
收藏 0
点赞 0
评论 0
@Override
public UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv, T authnCtx)
throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException,
CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {
checkEnteredCredentials(connEnv, authnCtx);
MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), true);
UserType userType = principal.getUser();
CredentialsType credentials = userType.getCredentials();
CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);
if (checkCredentials(principal, authnCtx, connEnv)) {
recordPasswordAuthenticationSuccess(principal, connEnv, getCredential(credentials), credentialsPolicy);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal,
authnCtx.getEnteredCredential(), principal.getAuthorities());
return token;
} else {
recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch");
throw new BadCredentialsException("web.security.provider.invalid");
}
}
AuthenticationEvaluatorImpl.java 文件源码
项目:engerek
阅读 25
收藏 0
点赞 0
评论 0
@Override
public UserType checkCredentials(ConnectionEnvironment connEnv, T authnCtx)
throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException,
CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {
checkEnteredCredentials(connEnv, authnCtx);
MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), false);
UserType userType = principal.getUser();
CredentialsType credentials = userType.getCredentials();
CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);
if (checkCredentials(principal, authnCtx, connEnv)) {
return userType;
} else {
recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch");
throw new BadCredentialsException("web.security.provider.invalid");
}
}
LdapAuthenticator.java 文件源码
项目:communote-server
阅读 34
收藏 0
点赞 0
评论 0
/**
* Tests the status of the LDAP details and throws an appropriate exception.
*
* @param dirContextOperations
* The context containing user data.
* @param username
* The username.
* @throws AuthenticationException
* if the status would prevent logging in
*/
private void checkAccountStatus(DirContextOperations dirContextOperations, String username)
throws AuthenticationException {
UserDetails ldapDetails = new LdapUserDetailsMapper()
.mapUserFromContext(dirContextOperations, username,
new ArrayList<GrantedAuthority>());
if (!ldapDetails.isEnabled()) {
throw new DisabledException("LDAP account is disabled.");
}
if (!ldapDetails.isAccountNonLocked()) {
throw new LockedException("LDAP account is locked.");
}
if (!ldapDetails.isCredentialsNonExpired()) {
throw new CredentialsExpiredException("Credentials for LDAP account are expired.");
}
if (!ldapDetails.isAccountNonExpired()) {
throw new AccountExpiredException("LDAP account is expired.");
}
}
SpringUserDetailsService.java 文件源码
项目:uaa-service
阅读 25
收藏 0
点赞 0
评论 0
@Override
public UserDetails loadUserByUsername(final String username) {
LOGGER.debug("Authenticating {}", username);
final String lowercaseUsername = username.toLowerCase();
final Optional<User> loadedUser = userRepository.findUserByUsernameIgnoreCase(lowercaseUsername);
return loadedUser.map(user -> {
if (isNotBlank(user.getActivationCode())) {
// ActivationCode of user is set so the account is not yet activated.
throw new DisabledException("Given user is not yet activated.");
}
if (isNotBlank(user.getPasswordResetCode())) {
// PasswordResetCode of user is set so the account is disabled till the password was reseted.
throw new DisabledException("Given user has requested password reset.");
}
// Map authorities
final List<SimpleGrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
.map(authority -> new SimpleGrantedAuthority(authority.getName())).collect(Collectors.toList());
// Return converted user
return springSecurityUser(lowercaseUsername, user.getPassword(), grantedAuthorities);
}).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseUsername + " was not found"));
}
BasicUrlAuthenticationFailureHandler.java 文件源码
项目:gnext
阅读 23
收藏 0
点赞 0
评论 0
/**
* handle locked ?
*
* @param userId
* @return
*/
protected AuthenticationException handlerLocked(String userId) {
AuthUser user = authUserServ.load(userId);
if (user.getErrorCount() >= 5) {
Long dateTime = user.getStateTime().getTime();
// 1 DAY = 86 400 000 ms
if(new Date().getTime()-dateTime <86400000){
// Locked user if input 6 error password
user.setEnabled(0);
authUserServ.add(user);
return new DisabledException(messages.getMessage(
"AccountStatusUserDetailsChecker.locked"));
}
}else{
// error count ++
user.setErrorCount(user.getErrorCount() + 1);
// state time
user.setStateTime(new Date());
}
int onlyCount=6-user.getErrorCount();
authUserServ.add(user);
return new BadCredentialsException(messages.getMessage(
"AccountStatusUserDetailsChecker.onlyCount", new Object[] { onlyCount }));
}
AuthenticationEvaluatorImpl.java 文件源码
项目:midpoint
阅读 24
收藏 0
点赞 0
评论 0
@Override
public UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv, T authnCtx)
throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException,
CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {
checkEnteredCredentials(connEnv, authnCtx);
MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), true);
UserType userType = principal.getUser();
CredentialsType credentials = userType.getCredentials();
CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);
if (checkCredentials(principal, authnCtx, connEnv)) {
recordPasswordAuthenticationSuccess(principal, connEnv, getCredential(credentials), credentialsPolicy);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal,
authnCtx.getEnteredCredential(), principal.getAuthorities());
return token;
} else {
recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch");
throw new BadCredentialsException("web.security.provider.invalid");
}
}
AuthenticationEvaluatorImpl.java 文件源码
项目:midpoint
阅读 26
收藏 0
点赞 0
评论 0
@Override
public UserType checkCredentials(ConnectionEnvironment connEnv, T authnCtx)
throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException,
CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {
checkEnteredCredentials(connEnv, authnCtx);
MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), false);
UserType userType = principal.getUser();
CredentialsType credentials = userType.getCredentials();
CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);
if (checkCredentials(principal, authnCtx, connEnv)) {
return userType;
} else {
recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch");
throw new BadCredentialsException("web.security.provider.invalid");
}
}
Shogun2AuthenticationProviderTest.java 文件源码
项目:shogun2
阅读 27
收藏 0
点赞 0
评论 0
/**
* Tests whether a {@link DisabledException} is thrown when the user is not
* active.
*/
@Test(expected=DisabledException.class)
public void authenticate_shouldThrowDisabledExceptionIfUserIsInactive() {
// 1. Mock an authentication request object
final String shogun2UserName = "user";
final String correctPassword = "correctPassword";
final User userToAuth = createUserMock(shogun2UserName, correctPassword);
// set user as inactive
userToAuth.setActive(false);
// 2. Mock the auth request for the inactive user
Authentication authRequest = mock(Authentication.class);
when(authRequest.getName()).thenReturn(shogun2UserName);
when(authRequest.getCredentials()).thenReturn(correctPassword);
// 3. Mock the userDao
when(userDao.findByAccountName(shogun2UserName)).thenReturn(userToAuth);
// 4. Call the authenticate method with the mocked object to provoke
// the expected DisabledException
authProvider.authenticate(authRequest);
}
AuthenticationEvaluatorImpl.java 文件源码
项目:midpoint
阅读 22
收藏 0
点赞 0
评论 0
@Override
public UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv, T authnCtx)
throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException,
CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {
checkEnteredCredentials(connEnv, authnCtx);
MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), true);
UserType userType = principal.getUser();
CredentialsType credentials = userType.getCredentials();
CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);
if (checkCredentials(principal, authnCtx, connEnv)) {
recordPasswordAuthenticationSuccess(principal, connEnv, getCredential(credentials), credentialsPolicy);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal,
authnCtx.getEnteredCredential(), principal.getAuthorities());
return token;
} else {
recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch");
throw new BadCredentialsException("web.security.provider.invalid");
}
}
AuthenticationEvaluatorImpl.java 文件源码
项目:midpoint
阅读 25
收藏 0
点赞 0
评论 0
@Override
public UserType checkCredentials(ConnectionEnvironment connEnv, T authnCtx)
throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException,
CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {
checkEnteredCredentials(connEnv, authnCtx);
MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), false);
UserType userType = principal.getUser();
CredentialsType credentials = userType.getCredentials();
CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);
if (checkCredentials(principal, authnCtx, connEnv)) {
return userType;
} else {
recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch");
throw new BadCredentialsException("web.security.provider.invalid");
}
}
PersonContextMapperTest.java 文件源码
项目:urlaubsverwaltung
阅读 25
收藏 0
点赞 0
评论 0
@Test(expected = DisabledException.class)
public void ensureLoginIsNotPossibleIfUserIsDeactivated() throws UnsupportedMemberAffiliationException,
NamingException {
Person person = TestDataCreator.createPerson();
person.setPermissions(Collections.singletonList(Role.INACTIVE));
Mockito.when(personService.getPersonByLogin(Mockito.anyString())).thenReturn(Optional.of(person));
Mockito.when(ldapUserMapper.mapFromContext(Mockito.eq(context)))
.thenReturn(new LdapUser(person.getLoginName(), Optional.of(person.getFirstName()),
Optional.of(person.getLastName()), Optional.of(person.getEmail())));
Mockito.when(ldapSyncService.syncPerson(Mockito.any(Person.class), Matchers.<Optional<String>>any(),
Matchers.<Optional<String>>any(), Matchers.<Optional<String>>any()))
.thenReturn(person);
personContextMapper.mapUserFromContext(context, person.getLoginName(), null);
}
IdentificationPopoverPanel.java 文件源码
项目:artifact-listener
阅读 25
收藏 0
点赞 0
评论 0
@Override
protected void onInitialize() {
super.onInitialize();
// Vérification des retours d'auth pac4J
HttpServletRequest request = ((ServletWebRequest) RequestCycle.get().getRequest()).getContainerRequest();
Exception exception = (Exception) request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
if (exception != null) {
if (exception instanceof DisabledException) {
getSession().error(getString("home.identification.classic.error.userDisabled"));
} else if (exception instanceof AuthenticationServiceException) {
LOGGER.error("Authentication failed", exception);
getSession().error(getString("home.identification.error.badCredentials") + exception.getMessage());
} else {
LOGGER.error("An unknown error occurred during the authentication process", exception);
getSession().error(getString("home.identification.error.unknown"));
}
request.getSession().removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
}
ResponsiveIdentificationPanel.java 文件源码
项目:artifact-listener
阅读 26
收藏 0
点赞 0
评论 0
@Override
protected void onInitialize() {
super.onInitialize();
// Vérification des retours d'auth pac4J
HttpServletRequest request = ((ServletWebRequest) RequestCycle.get().getRequest()).getContainerRequest();
Exception exception = (Exception) request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
if (exception != null) {
if (exception instanceof DisabledException) {
getSession().error(getString("home.identification.classic.error.userDisabled"));
} else if (exception instanceof AuthenticationServiceException) {
LOGGER.error("Authentication failed", exception);
getSession().error(getString("home.identification.error.badCredentials") + exception.getMessage());
} else {
LOGGER.error("An unknown error occurred during the authentication process", exception);
getSession().error(getString("home.identification.error.unknown"));
}
request.getSession().removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
}
UserAuthenticationProvider.java 文件源码
项目:JenkinsHue
阅读 23
收藏 0
点赞 0
评论 0
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
log.debug("Prüfen, ob sich der Nutzer in der DB befindet...");
if (userService.findByLogin(authentication.getName().toLowerCase()) == null) {
log.debug("Der Nutzer " + authentication.getName() + " befindet sich nicht in der DB.");
throw new DisabledException(authentication.getName()); // muss eine AccountStatusException sein!!
}
log.debug("Der Nutzer " + authentication.getName() + " befindet sich in der DB.");
return null; // danach wird Provider gefragt (ldapAuthentication)
}
FormLoginSecurityConfig.java 文件源码
项目:sns-todo
阅读 34
收藏 0
点赞 0
评论 0
@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {
ExceptionMappingAuthenticationFailureHandler failureHandler = new ExceptionMappingAuthenticationFailureHandler();
Map<String, String> failureUrlMap = new HashMap<>();
failureUrlMap.put(BadCredentialsException.class.getName(), LoginAuthenticationFailureHandler.PASS_ERROR_URL);
failureUrlMap.put(CaptchaException.class.getName(), LoginAuthenticationFailureHandler.CODE_ERROR_URL);
failureUrlMap.put(AccountExpiredException.class.getName(), LoginAuthenticationFailureHandler.EXPIRED_URL);
failureUrlMap.put(LockedException.class.getName(), LoginAuthenticationFailureHandler.LOCKED_URL);
failureUrlMap.put(DisabledException.class.getName(), LoginAuthenticationFailureHandler.DISABLED_URL);
failureHandler.setExceptionMappings(failureUrlMap);
return failureHandler;
}
CurrentUserDetailsService.java 文件源码
项目:nixmash-blog
阅读 26
收藏 0
点赞 0
评论 0
@Override
public CurrentUser loadUserByUsername(String username)
throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (!user.isEnabled())
throw new DisabledException(USER_IS_DISABLED);
return new CurrentUser(user);
}
AuthResponse.java 文件源码
项目:parkingcloud
阅读 29
收藏 0
点赞 0
评论 0
protected AuthResponse(Exception e){
super(e);
this.setService(SERVICE_NAME);
if (e instanceof AuthenticationException) {
if (e instanceof UsernameNotFoundException) {
this.setErrorCode(CodeUsernameNotFound);
} else if (e instanceof DisabledException) {
this.setErrorCode(CodeDisabled);
} else if (e instanceof LockedException) {
this.setErrorCode(CodeLocked);
} else if (e instanceof BadCredentialsException) {
this.setErrorCode(CodeBadCredentials);
} else if (e instanceof CredentialsExpiredException) {
this.setErrorCode(CodeCredentialsExpired);
} else if (e instanceof BadCaptchaException) {
this.setErrorCode(CodeBadCaptcha);
} else if (e instanceof SmsProviderException){
this.setErrorCode(CodeSmsProvide);
} else if (e instanceof UserExistException){
this.setErrorCode(CodeSmsProvide);
} else if (e instanceof UnauthorizedException){
this.setErrorCode(CodeUnauthorized);
} else {
this.setErrorCode(CodeAuthenticationFailed);
}
}
}
RestAuthenticationProvider.java 文件源码
项目:iotplatform
阅读 31
收藏 0
点赞 0
评论 0
private Authentication authenticateByUsernameAndPassword(UserPrincipal userPrincipal, String username,
String password) {
User user = userService.findUserByEmail(username);
if (user == null) {
throw new UsernameNotFoundException("User not found: " + username);
}
UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId());
if (userCredentials == null) {
throw new UsernameNotFoundException("User credentials not found");
}
if (!userCredentials.isEnabled()) {
throw new DisabledException("User is not active");
}
if (!encoder.matches(password, userCredentials.getPassword())) {
throw new BadCredentialsException("Authentication Failed. Username or Password not valid.");
}
if (user.getAuthority() == null)
throw new InsufficientAuthenticationException("User has no authority assigned");
SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), userPrincipal);
return new UsernamePasswordAuthenticationToken(securityUser, null, securityUser.getAuthorities());
}
AbstractAuthenticationProvider.java 文件源码
项目:reporting-tool
阅读 30
收藏 0
点赞 0
评论 0
void verifyAccountStatus(Person user) {
if (user.isLocked()) {
throw new LockedException("Account is locked.");
}
if (!user.isEnabled()) {
throw new DisabledException("Account is disabled.");
}
}
AuthenticationFailureTest.java 文件源码
项目:reporting-tool
阅读 23
收藏 0
点赞 0
评论 0
@Test
public void authenticationFailureReturnsLoginStatusWithErrorInfoOnAccountDisabled() throws Exception {
final MockHttpServletRequest request = AuthenticationSuccessTest.request();
final MockHttpServletResponse response = AuthenticationSuccessTest.response();
final String msg = "Account is disabled.";
failure.onAuthenticationFailure(request, response, new DisabledException(msg));
final LoginStatus status = mapper.readValue(response.getContentAsString(), LoginStatus.class);
assertFalse(status.isSuccess());
assertFalse(status.isLoggedIn());
assertNull(status.getUsername());
assertEquals(msg, status.getErrorMessage());
assertEquals("login.disabled", status.getErrorId());
}
JwtAuthenticationProvider.java 文件源码
项目:oma-riista-web
阅读 31
收藏 0
点赞 0
评论 0
@Override
public Authentication authenticate(final Authentication authentication) {
final JwtAuthenticationToken authRequest = (JwtAuthenticationToken) authentication;
final Jws<Claims> claimsJws = parserAndVerify(authRequest);
if (claimsJws.getBody().getExpiration() == null) {
throw new BadCredentialsException("Only temporary JWT supported");
}
final String username = claimsJws.getBody().getSubject();
final UserDetails userDetails;
try {
userDetails = userDetailsService.loadUserByUsername(username);
} catch (final UsernameNotFoundException notFound) {
throw new BadCredentialsException("Bad credentials");
}
if (!userDetails.isAccountNonLocked()) {
throw new LockedException("User account is locked");
}
if (!userDetails.isEnabled()) {
throw new DisabledException("User is disabled");
}
if (!userDetails.isAccountNonExpired()) {
throw new AccountExpiredException("User account has expired");
}
if (!userDetails.isCredentialsNonExpired()) {
throw new CredentialsExpiredException("User credentials have expired");
}
LOG.info("Successful JWT authentication for username={}", userDetails.getUsername());
return JwtAuthenticationToken.createAuthenticated(userDetails, authRequest.getDetails());
}
ExceptionControllerAdvice.java 文件源码
项目:kanbanboard
阅读 30
收藏 0
点赞 0
评论 0
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler({AccessDeniedException.class, LockedException.class,
DisabledException.class, CredentialsExpiredException.class})
@ResponseBody
ResultDto handleUserException(HttpServletRequest req, Exception ex) {
return new ResultDto(ex.getLocalizedMessage());
}
BoardServiceImpl.java 文件源码
项目:kanbanboard
阅读 24
收藏 0
点赞 0
评论 0
@Override
public Board updateBoard(String id, BoardUpdateDto boardUpdateDto) {
User user = getAuthorizedUser();
Board board = boardRepository.findOne(id);
if (board != null) {
if (!user.hasRole(UserRole.ADMIN) && !board.getOwner().equals(user) && !board.getUsers().contains(user)) {
log.error("User {} does not have rights to alter board {}.", user.getUsername(), id);
throw new AccessDeniedException("User is not allowed to alter board.");
}
board.setName(boardUpdateDto.getName());
board.setOwner(userService.loadUserByUsername(boardUpdateDto.getOwner().getUsername()));
if (boardUpdateDto.getMembers() != null) {
Set<User> members = new LinkedHashSet<>();
boardUpdateDto.getMembers().forEach(d -> {
try {
members.add(userService.loadUserByUsername(d.getUsername()));
} catch (AccessDeniedException | LockedException | DisabledException | CredentialsExpiredException e) {
log.warn(e.getMessage());
}
});
board.setUsers(members);
}
boardRepository.save(board);
} else {
log.info("No board with given id {} found.", id);
throw new BoardNotFoundException("Board with id " + id + " not found.");
}
return board;
}
DefaultAuthenticationProvider.java 文件源码
项目:rpb
阅读 28
收藏 0
点赞 0
评论 0
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
String username = String.valueOf(auth.getPrincipal());
String password = String.valueOf(auth.getCredentials());
String passwordHash = DigestUtils.shaHex(password);
// Log the default authentication request
log.info("username:" + username);
// Use the username to load the data for the user, including authorities and password.
UserDetails user = userDetailsService.loadUserByUsername(username);
// Check if account is enabled
if (!user.isEnabled()) {
throw new DisabledException("This user account is disabled");
}
// Check the passwords match.
if (!user.getPassword().equals(passwordHash)) {
throw new BadCredentialsException("Bad Credentials");
}
// Return an authenticated token, containing user data and authorities
return new DefaultUsernamePasswordAuthenticationToken(
user, // principal
null, // credentials
user.getAuthorities() // authorities
);
}
AuthenticationEvaluatorImpl.java 文件源码
项目:engerek
阅读 22
收藏 0
点赞 0
评论 0
private boolean checkCredentials(MidPointPrincipal principal, T authnCtx, ConnectionEnvironment connEnv) {
UserType userType = principal.getUser();
CredentialsType credentials = userType.getCredentials();
if (credentials == null || getCredential(credentials) == null) {
recordAuthenticationFailure(principal, connEnv, "no credentials in user");
throw new AuthenticationCredentialsNotFoundException("web.security.provider.invalid");
}
CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);
// Lockout
if (isLockedOut(getCredential(credentials), credentialsPolicy)) {
recordAuthenticationFailure(principal, connEnv, "password locked-out");
throw new LockedException("web.security.provider.locked");
}
if (suportsAuthzCheck()) {
// Authorizations
if (!hasAnyAuthorization(principal)) {
recordAuthenticationFailure(principal, connEnv, "no authorizations");
throw new DisabledException("web.security.provider.access.denied");
}
}
// Password age
checkPasswordValidityAndAge(connEnv, principal, getCredential(credentials), credentialsPolicy);
return passwordMatches(connEnv, principal, getCredential(credentials), authnCtx);
}
AuthenticationEvaluatorImpl.java 文件源码
项目:engerek
阅读 27
收藏 0
点赞 0
评论 0
/**
* Special-purpose method used for Web Service authentication based on javax.security callbacks.
*
* In that case there is no reasonable way how to reuse existing methods. Therefore this method is NOT part of the
* AuthenticationEvaluator interface. It is mostly a glue to make the old Java security code work.
*/
public String getAndCheckUserPassword(ConnectionEnvironment connEnv, String enteredUsername)
throws AuthenticationCredentialsNotFoundException, DisabledException, LockedException,
CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {
MidPointPrincipal principal = getAndCheckPrincipal(connEnv, enteredUsername, true);
UserType userType = principal.getUser();
CredentialsType credentials = userType.getCredentials();
if (credentials == null) {
recordAuthenticationFailure(principal, connEnv, "no credentials in user");
throw new AuthenticationCredentialsNotFoundException("web.security.provider.invalid");
}
PasswordType passwordType = credentials.getPassword();
SecurityPolicyType securityPolicy = principal.getApplicableSecurityPolicy();
PasswordCredentialsPolicyType passwordCredentialsPolicy = SecurityUtil.getEffectivePasswordCredentialsPolicy(securityPolicy);
// Lockout
if (isLockedOut(passwordType, passwordCredentialsPolicy)) {
recordAuthenticationFailure(principal, connEnv, "password locked-out");
throw new LockedException("web.security.provider.locked");
}
// Authorizations
if (!hasAnyAuthorization(principal)) {
recordAuthenticationFailure(principal, connEnv, "no authorizations");
throw new AccessDeniedException("web.security.provider.access.denied");
}
// Password age
checkPasswordValidityAndAge(connEnv, principal, passwordType.getValue(), passwordType.getMetadata(), passwordCredentialsPolicy);
return getPassword(connEnv, principal, passwordType.getValue());
}
TestAbstractAuthenticationEvaluator.java 文件源码
项目:engerek
阅读 21
收藏 0
点赞 0
评论 0
private void loginJackGoodPasswordExpectDenied(final String TEST_NAME, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException {
display("now", clock.currentTimeXMLGregorianCalendar());
ConnectionEnvironment connEnv = createConnectionEnvironment();
XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar();
// WHEN
TestUtil.displayWhen(TEST_NAME);
try {
getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getGoodPasswordJack()));
AssertJUnit.fail("Unexpected success");
} catch (DisabledException e) {
// This is expected
// THEN
TestUtil.displayThen(TEST_NAME);
display("expected exception", e);
// this is important. The exception should give no indication whether the password is
// good or bad
assertDisabledException(e, USER_JACK_USERNAME);
}
PrismObject<UserType> userAfter = getUser(USER_JACK_OID);
display("user after", userAfter);
assertFailedLogins(userAfter, 0);
}