Search in sources :

Example 56 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project molgenis by molgenis.

the class RestController method login.

/**
 * Login to the api.
 * <p>
 * Returns a json object with a token on correct login else throws an AuthenticationException. Clients can use this
 * token when calling the api.
 * <p>
 * Example:
 * <p>
 * Request: {username:admin,password:xxx}
 * <p>
 * Response: {token: b4fd94dc-eae6-4d9a-a1b7-dd4525f2f75d}
 */
@PostMapping(value = "/login", produces = APPLICATION_JSON_VALUE)
@ResponseBody
public LoginResponse login(@Valid @RequestBody LoginRequest login, HttpServletRequest request) {
    if (login == null) {
        throw new HttpMessageNotReadableException("Missing login");
    }
    if (isUser2fa()) {
        throw new BadCredentialsException("Login using /api/v1/login is disabled, two factor authentication is enabled");
    }
    return runAsSystem(() -> {
        UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword());
        authToken.setDetails(new WebAuthenticationDetails(request));
        // Authenticate the login
        Authentication authentication = authenticationManager.authenticate(authToken);
        if (!authentication.isAuthenticated()) {
            throw new BadCredentialsException("Unknown username or password");
        }
        User user = dataService.findOne(USER, new QueryImpl<User>().eq(UserMetaData.USERNAME, authentication.getName()), User.class);
        if (user.isChangePassword()) {
            throw new BadCredentialsException("Unable to log in because a password reset is required. Sign in to the website to reset your password.");
        }
        // User authenticated, log the user in
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // Generate a new token for the user
        String token = tokenService.generateAndStoreToken(authentication.getName(), "REST API login");
        return new LoginResponse(token, user.getUsername(), user.getFirstName(), user.getLastName());
    });
}
Also used : QueryImpl(org.molgenis.data.support.QueryImpl) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) User(org.molgenis.data.security.auth.User) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 57 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project molgenis by molgenis.

the class TwoFactorAuthenticationProviderImpl method authenticate.

@Override
public Authentication authenticate(Authentication authentication) {
    if (!supports(authentication.getClass())) {
        throw new IllegalArgumentException("Only TwoFactorAuthenticationToken is supported");
    }
    TwoFactorAuthenticationToken authToken = (TwoFactorAuthenticationToken) authentication;
    if (!twoFactorAuthenticationService.isConfiguredForUser()) {
        if (authToken.getSecretKey() != null) {
            if (otpService.tryVerificationCode(authToken.getVerificationCode(), authToken.getSecretKey())) {
                activateTwoFactorAuthentication(authToken);
                UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                authToken = new TwoFactorAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities(), authToken.getVerificationCode(), authToken.getSecretKey());
            }
        } else {
            throw new BadCredentialsException("Invalid secret generated");
        }
    } else {
        if (authToken.getVerificationCode() != null) {
            if (twoFactorAuthenticationService.isVerificationCodeValidForUser(authToken.getVerificationCode())) {
                UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                // if token is invalid
                authToken = new TwoFactorAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities(), authToken.getVerificationCode(), null);
            }
        } else {
            throw new BadCredentialsException("Invalid verification code entered");
        }
    }
    return authToken;
}
Also used : UserDetails(org.springframework.security.core.userdetails.UserDetails) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 58 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project molgenis by molgenis.

the class RecoveryServiceImpl method useRecoveryCode.

@Override
@Transactional
public void useRecoveryCode(String recoveryCode) {
    String userId = getUser().getId();
    RecoveryCode existingCode = runAsSystem(() -> dataService.query(RECOVERY_CODE, RecoveryCode.class).eq(USER_ID, userId).and().eq(CODE, recoveryCode).findOne());
    if (existingCode != null) {
        runAsSystem(() -> dataService.delete(RECOVERY_CODE, existingCode));
        UserSecret secret = runAsSystem(() -> dataService.query(USER_SECRET, UserSecret.class).eq(UserSecretMetaData.USER_ID, userId).findOne());
        secret.setFailedLoginAttempts(0);
        runAsSystem(() -> dataService.update(USER_SECRET, secret));
    } else {
        throw new BadCredentialsException("Invalid recovery code or code already used");
    }
}
Also used : RecoveryCode(org.molgenis.security.twofactor.model.RecoveryCode) UserSecret(org.molgenis.security.twofactor.model.UserSecret) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 59 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project spring-security by spring-projects.

the class BadCredentialsExceptionMixinTests method serializeBadCredentialsExceptionMixinTest.

// @formatter:on
@Test
public void serializeBadCredentialsExceptionMixinTest() throws JsonProcessingException, JSONException {
    BadCredentialsException exception = new BadCredentialsException("message");
    String serializedJson = this.mapper.writeValueAsString(exception);
    JSONAssert.assertEquals(EXCEPTION_JSON, serializedJson, true);
}
Also used : BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Test(org.junit.jupiter.api.Test)

Example 60 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project spring-security by spring-projects.

the class BadCredentialsExceptionMixinTests method deserializeBadCredentialsExceptionMixinTest.

@Test
public void deserializeBadCredentialsExceptionMixinTest() throws IOException {
    BadCredentialsException exception = this.mapper.readValue(EXCEPTION_JSON, BadCredentialsException.class);
    assertThat(exception).isNotNull();
    assertThat(exception.getCause()).isNull();
    assertThat(exception.getMessage()).isEqualTo("message");
    assertThat(exception.getLocalizedMessage()).isEqualTo("message");
}
Also used : BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Test(org.junit.jupiter.api.Test)

Aggregations

BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)174 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)63 Authentication (org.springframework.security.core.Authentication)57 Test (org.junit.jupiter.api.Test)32 Test (org.junit.Test)26 AuthenticationException (org.springframework.security.core.AuthenticationException)24 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)22 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)21 UserDetails (org.springframework.security.core.userdetails.UserDetails)20 GrantedAuthority (org.springframework.security.core.GrantedAuthority)15 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)14 HttpServletRequest (javax.servlet.http.HttpServletRequest)13 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)13 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)12 FilterChain (jakarta.servlet.FilterChain)10 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)10 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)10 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)9 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)7