Search in sources :

Example 6 with JwtToken

use of org.thingsboard.server.common.data.security.model.JwtToken in project thingsboard by thingsboard.

the class TokenOutdatingService method isOutdated.

public boolean isOutdated(JwtToken token, UserId userId) {
    Claims claims = tokenFactory.parseTokenClaims(token).getBody();
    long issueTime = claims.getIssuedAt().getTime();
    return Optional.ofNullable(tokenOutdatageTimeCache.get(toKey(userId), Long.class)).map(outdatageTime -> {
        if (System.currentTimeMillis() - outdatageTime <= SECONDS.toMillis(jwtSettings.getRefreshTokenExpTime())) {
            return MILLISECONDS.toSeconds(issueTime) < MILLISECONDS.toSeconds(outdatageTime);
        } else {
            /*
                         * Means that since the outdating has passed more than
                         * the lifetime of refresh token (the longest lived)
                         * and there is no need to store outdatage time anymore
                         * as all the tokens issued before the outdatage time
                         * are now expired by themselves
                         * */
            tokenOutdatageTimeCache.evict(toKey(userId));
            return false;
        }
    }).orElse(false);
}
Also used : Cache(org.springframework.cache.Cache) JwtTokenFactory(org.thingsboard.server.service.security.model.token.JwtTokenFactory) RequiredArgsConstructor(lombok.RequiredArgsConstructor) CacheConstants(org.thingsboard.server.common.data.CacheConstants) EventListener(org.springframework.context.event.EventListener) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) UserAuthDataChangedEvent(org.thingsboard.server.common.data.security.event.UserAuthDataChangedEvent) Claims(io.jsonwebtoken.Claims) UserId(org.thingsboard.server.common.data.id.UserId) JwtToken(org.thingsboard.server.common.data.security.model.JwtToken) CacheManager(org.springframework.cache.CacheManager) Service(org.springframework.stereotype.Service) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) JwtSettings(org.thingsboard.server.config.JwtSettings) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Claims(io.jsonwebtoken.Claims)

Example 7 with JwtToken

use of org.thingsboard.server.common.data.security.model.JwtToken in project thingsboard by thingsboard.

the class UserController method getUserToken.

@ApiOperation(value = "Get User Token (getUserToken)", notes = "Returns the token of the User based on the provided User Id. " + "If the user who performs the request has the authority of 'SYS_ADMIN', it is possible to get the token of any tenant administrator. " + "If the user who performs the request has the authority of 'TENANT_ADMIN', it is possible to get the token of any customer user that belongs to the same tenant. ")
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
@RequestMapping(value = "/user/{userId}/token", method = RequestMethod.GET)
@ResponseBody
public JwtTokenPair getUserToken(@ApiParam(value = USER_ID_PARAM_DESCRIPTION) @PathVariable(USER_ID) String strUserId) throws ThingsboardException {
    checkParameter(USER_ID, strUserId);
    try {
        if (!userTokenAccessEnabled) {
            throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION, ThingsboardErrorCode.PERMISSION_DENIED);
        }
        UserId userId = new UserId(toUUID(strUserId));
        SecurityUser authUser = getCurrentUser();
        User user = checkUserId(userId, Operation.READ);
        UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
        UserCredentials credentials = userService.findUserCredentialsByUserId(authUser.getTenantId(), userId);
        SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal);
        JwtToken accessToken = tokenFactory.createAccessJwtToken(securityUser);
        JwtToken refreshToken = refreshTokenRepository.requestRefreshToken(securityUser);
        return new JwtTokenPair(accessToken.getToken(), refreshToken.getToken());
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : JwtToken(org.thingsboard.server.common.data.security.model.JwtToken) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) User(org.thingsboard.server.common.data.User) JwtTokenPair(org.thingsboard.server.service.security.model.JwtTokenPair) UserId(org.thingsboard.server.common.data.id.UserId) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) UserCredentials(org.thingsboard.server.common.data.security.UserCredentials) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 8 with JwtToken

use of org.thingsboard.server.common.data.security.model.JwtToken in project thingsboard by thingsboard.

the class TokenOutdatingTest method testOutdateOldUserTokens.

@Test
public void testOutdateOldUserTokens() throws Exception {
    JwtToken jwtToken = createAccessJwtToken(userId);
    // need to wait before outdating so that outdatage time is strictly after token issue time
    SECONDS.sleep(1);
    tokenOutdatingService.outdateOldUserTokens(userId);
    assertTrue(tokenOutdatingService.isOutdated(jwtToken, userId));
    SECONDS.sleep(1);
    JwtToken newJwtToken = tokenFactory.createAccessJwtToken(createMockSecurityUser(userId));
    assertFalse(tokenOutdatingService.isOutdated(newJwtToken, userId));
}
Also used : JwtToken(org.thingsboard.server.common.data.security.model.JwtToken) RawAccessJwtToken(org.thingsboard.server.service.security.model.token.RawAccessJwtToken) Test(org.junit.jupiter.api.Test)

Aggregations

JwtToken (org.thingsboard.server.common.data.security.model.JwtToken)8 SecurityUser (org.thingsboard.server.service.security.model.SecurityUser)5 ApiOperation (io.swagger.annotations.ApiOperation)3 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)3 User (org.thingsboard.server.common.data.User)3 ThingsboardException (org.thingsboard.server.common.data.exception.ThingsboardException)3 UserCredentials (org.thingsboard.server.common.data.security.UserCredentials)3 JwtTokenPair (org.thingsboard.server.service.security.model.JwtTokenPair)3 UserPrincipal (org.thingsboard.server.service.security.model.UserPrincipal)3 URISyntaxException (java.net.URISyntaxException)2 Test (org.junit.jupiter.api.Test)2 ResponseStatus (org.springframework.web.bind.annotation.ResponseStatus)2 UserId (org.thingsboard.server.common.data.id.UserId)2 UserAuthDataChangedEvent (org.thingsboard.server.common.data.security.event.UserAuthDataChangedEvent)2 RawAccessJwtToken (org.thingsboard.server.service.security.model.token.RawAccessJwtToken)2 Claims (io.jsonwebtoken.Claims)1 IOException (java.io.IOException)1 HashMap (java.util.HashMap)1 Optional (java.util.Optional)1