Search in sources :

Example 26 with IdmJwtAuthentication

use of eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication in project CzechIdMng by bcvsolutions.

the class AbstractIntegrationTest method loginAsNoAdmin.

/**
 * User will be logged as user with all authorities without APP_ADMIN
 *
 * Lookout: security context is mocked
 *
 * @param user
 */
public void loginAsNoAdmin(String user) {
    Collection<GrantedAuthority> authorities = IdmAuthorityUtils.toAuthorities(moduleService.getAvailablePermissions()).stream().filter(authority -> {
        return !IdmGroupPermission.APP_ADMIN.equals(authority.getAuthority());
    }).collect(Collectors.toList());
    IdmIdentityDto identity = (IdmIdentityDto) lookupService.getDtoLookup(IdmIdentityDto.class).lookup(user);
    SecurityContextHolder.getContext().setAuthentication(new IdmJwtAuthentication(identity, null, authorities, "test"));
}
Also used : AbstractEntityRepository(eu.bcvsolutions.idm.core.api.repository.AbstractEntityRepository) BeforeClass(org.junit.BeforeClass) WebEnvironment(org.springframework.boot.test.context.SpringBootTest.WebEnvironment) RunWith(org.junit.runner.RunWith) Autowired(org.springframework.beans.factory.annotation.Autowired) IdmJwtAuthentication(eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication) BaseEntity(eu.bcvsolutions.idm.core.api.entity.BaseEntity) LookupService(eu.bcvsolutions.idm.core.api.service.LookupService) IdmAuthorityUtils(eu.bcvsolutions.idm.core.security.api.utils.IdmAuthorityUtils) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) After(org.junit.After) TransactionContextHolder(eu.bcvsolutions.idm.core.api.domain.TransactionContextHolder) IdmLongRunningTaskFilter(eu.bcvsolutions.idm.core.scheduler.api.dto.filter.IdmLongRunningTaskFilter) Assume(org.junit.Assume) ModuleService(eu.bcvsolutions.idm.core.api.service.ModuleService) SpringRunner(org.springframework.test.context.junit4.SpringRunner) IdmLongRunningTaskService(eu.bcvsolutions.idm.core.scheduler.api.service.IdmLongRunningTaskService) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) Before(org.junit.Before) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) LongRunningTaskManager(eu.bcvsolutions.idm.core.scheduler.api.service.LongRunningTaskManager) Collection(java.util.Collection) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) IdmEntityEventFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmEntityEventFilter) IdmCacheManager(eu.bcvsolutions.idm.core.api.service.IdmCacheManager) ReadWriteDtoService(eu.bcvsolutions.idm.core.api.service.ReadWriteDtoService) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Ignore(org.junit.Ignore) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) BaseDto(eu.bcvsolutions.idm.core.api.dto.BaseDto) TransactionCallback(org.springframework.transaction.support.TransactionCallback) IdmGroupPermission(eu.bcvsolutions.idm.core.security.api.domain.IdmGroupPermission) IdmApplication(eu.bcvsolutions.idm.IdmApplication) EntityEventManager(eu.bcvsolutions.idm.core.api.service.EntityEventManager) Rollback(org.springframework.test.annotation.Rollback) Transactional(org.springframework.transaction.annotation.Transactional) GrantedAuthority(org.springframework.security.core.GrantedAuthority) IdmJwtAuthentication(eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto)

Example 27 with IdmJwtAuthentication

use of eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication in project CzechIdMng by bcvsolutions.

the class OAuthAuthenticationManager method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!(authentication instanceof IdmJwtAuthentication)) {
        throw new IdmAuthenticationException("Unsupported granted authority " + authentication.getClass().getName());
    }
    // 
    IdmJwtAuthentication idmJwtAuthentication = verifyAuthentication(authentication);
    // Set logged user to workflow engine
    workflowIdentityService.setAuthenticatedUserId(idmJwtAuthentication.getCurrentUsername());
    // set authentication
    securityService.setAuthentication(idmJwtAuthentication);
    // 
    return idmJwtAuthentication;
}
Also used : IdmAuthenticationException(eu.bcvsolutions.idm.core.security.api.exception.IdmAuthenticationException) IdmJwtAuthentication(eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication)

Example 28 with IdmJwtAuthentication

use of eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication in project CzechIdMng by bcvsolutions.

the class JwtAuthenticationMapper method fromDto.

/**
 * Converts dto to authentication.
 *
 * @param token
 * @return
 */
public IdmJwtAuthentication fromDto(IdmTokenDto token) {
    Assert.notNull(token, "Token is required.");
    // 
    List<GrantedAuthority> grantedAuthorities = getDtoAuthorities(token).stream().map(authority -> new DefaultGrantedAuthority(authority.getAuthority())).collect(Collectors.toList());
    // 
    IdmJwtAuthentication authentication = new IdmJwtAuthentication(new IdmIdentityDto(token.getProperties().getUuid(PROPERTY_CURRENT_IDENTITY_ID), token.getProperties().getString(PROPERTY_CURRENT_USERNAME)), new IdmIdentityDto(token.getProperties().getUuid(PROPERTY_ORIGINAL_IDENTITY_ID), token.getProperties().getString(PROPERTY_ORIGINAL_USERNAME)), token.getExpiration(), token.getIssuedAt(), grantedAuthorities, token.getModuleId());
    authentication.setId(token.getId());
    // 
    return authentication;
}
Also used : ChronoField(java.time.temporal.ChronoField) IdmTokenDto(eu.bcvsolutions.idm.core.api.dto.IdmTokenDto) ZonedDateTime(java.time.ZonedDateTime) Autowired(org.springframework.beans.factory.annotation.Autowired) Hashing(com.google.common.hash.Hashing) ConfigurationService(eu.bcvsolutions.idm.core.api.service.ConfigurationService) IdmJwtAuthentication(eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication) MacSigner(org.springframework.security.jwt.crypto.sign.MacSigner) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) JwtHelper(org.springframework.security.jwt.JwtHelper) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) LoginService(eu.bcvsolutions.idm.core.security.api.service.LoginService) GrantedAuthoritiesFactory(eu.bcvsolutions.idm.core.security.api.service.GrantedAuthoritiesFactory) CoreException(eu.bcvsolutions.idm.core.api.exception.CoreException) DefaultGrantedAuthorityDto(eu.bcvsolutions.idm.core.security.api.dto.DefaultGrantedAuthorityDto) Collection(java.util.Collection) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) DefaultGrantedAuthority(eu.bcvsolutions.idm.core.security.api.domain.DefaultGrantedAuthority) IOException(java.io.IOException) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) IdmAuthenticationFilter(eu.bcvsolutions.idm.core.security.api.filter.IdmAuthenticationFilter) StandardCharsets(java.nio.charset.StandardCharsets) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ConfigurationMap(eu.bcvsolutions.idm.core.api.domain.ConfigurationMap) TokenManager(eu.bcvsolutions.idm.core.security.api.service.TokenManager) Jwt(org.springframework.security.jwt.Jwt) List(java.util.List) Component(org.springframework.stereotype.Component) ChronoUnit(java.time.temporal.ChronoUnit) CoreResultCode(eu.bcvsolutions.idm.core.api.domain.CoreResultCode) SignerVerifier(org.springframework.security.jwt.crypto.sign.SignerVerifier) IdmJwtAuthenticationDto(eu.bcvsolutions.idm.core.security.api.dto.IdmJwtAuthenticationDto) Lazy(org.springframework.context.annotation.Lazy) GuardedString(eu.bcvsolutions.idm.core.security.api.domain.GuardedString) Authentication(org.springframework.security.core.Authentication) Assert(org.springframework.util.Assert) DefaultGrantedAuthority(eu.bcvsolutions.idm.core.security.api.domain.DefaultGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) IdmJwtAuthentication(eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication) DefaultGrantedAuthority(eu.bcvsolutions.idm.core.security.api.domain.DefaultGrantedAuthority) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto)

Example 29 with IdmJwtAuthentication

use of eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication in project CzechIdMng by bcvsolutions.

the class DefaultJwtAuthenticationService method login.

/**
 * Create login response with filled token and authorities.
 *
 * @param loginDto login request
 * @param token cidmst token
 * @return login response
 */
private LoginDto login(LoginDto loginDto, IdmTokenDto token) {
    IdmJwtAuthentication authentication = jwtTokenMapper.fromDto(token);
    // 
    oauthAuthenticationManager.authenticate(authentication);
    // 
    LoginDto result = new LoginDto();
    result.setUsername(loginDto.getUsername());
    result.setSkipMustChange(loginDto.isSkipMustChange());
    result.setPassword(loginDto.getPassword());
    result.setAuthenticationModule(token.getModuleId());
    IdmJwtAuthenticationDto authenticationDto = jwtTokenMapper.toDto(token);
    result.setAuthentication(authenticationDto);
    result.setToken(jwtTokenMapper.writeToken(authenticationDto));
    result.setAuthorities(jwtTokenMapper.getDtoAuthorities(token));
    // 
    return result;
}
Also used : IdmJwtAuthentication(eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication) IdmJwtAuthenticationDto(eu.bcvsolutions.idm.core.security.api.dto.IdmJwtAuthenticationDto) LoginDto(eu.bcvsolutions.idm.core.security.api.dto.LoginDto)

Example 30 with IdmJwtAuthentication

use of eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication in project CzechIdMng by bcvsolutions.

the class JwtIdmAuthenticationFilter method authorize.

@Override
public boolean authorize(String token, HttpServletRequest request, HttpServletResponse response) {
    IdmJwtAuthenticationDto claims = null;
    try {
        Optional<Jwt> jwt = HttpFilterUtils.parseToken(token);
        if (!jwt.isPresent()) {
            return false;
        }
        HttpFilterUtils.verifyToken(jwt.get(), jwtTokenMapper.getVerifier());
        // authentication dto from request
        claims = jwtTokenMapper.getClaims(jwt.get());
        // we need to check expiration, before current (automatically prolonged) token is used by mapper
        if (claims.getExpiration() != null && claims.getExpiration().isBefore(ZonedDateTime.now())) {
            throw new ResultCodeException(CoreResultCode.AUTH_EXPIRED);
        }
        // resolve actual authentication from given authentication dto (token is loaded)
        IdmJwtAuthentication authentication = jwtTokenMapper.fromDto(claims);
        // set current authentication dto to context
        ctx.setToken(jwtTokenMapper.toDto(authentication));
        // try to authenticate
        Authentication auth = authenticationManager.authenticate(authentication);
        LOG.debug("User [{}] successfully logged in.", auth.getName());
        return auth.isAuthenticated();
    } catch (ResultCodeException ex) {
        String statusEnum = ex.getError().getError().getStatusEnum();
        if (CoreResultCode.TOKEN_NOT_FOUND.getCode().equals(statusEnum) || CoreResultCode.AUTHORITIES_CHANGED.getCode().equals(statusEnum) || CoreResultCode.AUTH_EXPIRED.getCode().equals(statusEnum)) {
            LOG.warn("Invalid token, reason: [{}]", ex.getMessage());
            ctx.setCodeEx(ex);
            // only expired or authorities changed
            ctx.setToken(claims);
        } else {
            // publish additional authentication requirement
            throw ex;
        }
    } catch (AuthenticationException ex) {
        LOG.warn("Invalid authentication, reason: [{}]", ex.getMessage());
        ctx.setAuthEx(ex);
    } catch (InvalidSignatureException | IOException | IllegalArgumentException ex) {
        // client sent some rubbish, just log and ignore
        LOG.warn("Invalid IdM auth token received.", ex);
    }
    return false;
}
Also used : InvalidSignatureException(org.springframework.security.jwt.crypto.sign.InvalidSignatureException) AuthenticationException(org.springframework.security.core.AuthenticationException) Jwt(org.springframework.security.jwt.Jwt) IdmJwtAuthentication(eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication) Authentication(org.springframework.security.core.Authentication) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) IdmJwtAuthentication(eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication) IdmJwtAuthenticationDto(eu.bcvsolutions.idm.core.security.api.dto.IdmJwtAuthenticationDto) IOException(java.io.IOException)

Aggregations

IdmJwtAuthentication (eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication)31 IdmIdentityDto (eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto)22 Test (org.junit.Test)14 ResultCodeException (eu.bcvsolutions.idm.core.api.exception.ResultCodeException)10 GrantedAuthority (org.springframework.security.core.GrantedAuthority)10 AbstractUnitTest (eu.bcvsolutions.idm.test.api.AbstractUnitTest)8 Collection (java.util.Collection)8 IdmTokenDto (eu.bcvsolutions.idm.core.api.dto.IdmTokenDto)7 GuardedString (eu.bcvsolutions.idm.core.security.api.domain.GuardedString)7 UUID (java.util.UUID)7 Collectors (java.util.stream.Collectors)7 Autowired (org.springframework.beans.factory.annotation.Autowired)7 ModuleService (eu.bcvsolutions.idm.core.api.service.ModuleService)6 IdmGroupPermission (eu.bcvsolutions.idm.core.security.api.domain.IdmGroupPermission)6 IdmAuthorityUtils (eu.bcvsolutions.idm.core.security.api.utils.IdmAuthorityUtils)6 Before (org.junit.Before)6 SecurityContextHolder (org.springframework.security.core.context.SecurityContextHolder)6 IdmJwtAuthenticationDto (eu.bcvsolutions.idm.core.security.api.dto.IdmJwtAuthenticationDto)4 LoginDto (eu.bcvsolutions.idm.core.security.api.dto.LoginDto)4 After (org.junit.After)4