Search in sources :

Example 1 with JwtToken

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

the class TokenOutdatingTest method testTokensOutdatageTimeRemovalFromCache.

@Test
public void testTokensOutdatageTimeRemovalFromCache() throws Exception {
    JwtToken jwtToken = createAccessJwtToken(userId);
    SECONDS.sleep(1);
    tokenOutdatingService.outdateOldUserTokens(userId);
    int refreshTokenExpirationTime = 5;
    jwtSettings.setRefreshTokenExpTime(refreshTokenExpirationTime);
    SECONDS.sleep(refreshTokenExpirationTime - 2);
    assertTrue(tokenOutdatingService.isOutdated(jwtToken, userId));
    assertNotNull(cacheManager.getCache(CacheConstants.TOKEN_OUTDATAGE_TIME_CACHE).get(userId.getId().toString()));
    SECONDS.sleep(3);
    assertFalse(tokenOutdatingService.isOutdated(jwtToken, userId));
    assertNull(cacheManager.getCache(CacheConstants.TOKEN_OUTDATAGE_TIME_CACHE).get(userId.getId().toString()));
}
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)

Example 2 with JwtToken

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

the class AuthController method activateUser.

@ApiOperation(value = "Activate User", notes = "Checks the activation token and updates corresponding user password in the database. " + "Now the user may start using his password to login. " + "The response already contains the [JWT](https://jwt.io) activation and refresh tokens, " + "to simplify the user activation flow and avoid asking user to input password again after activation. " + "If token is valid, returns the object that contains [JWT](https://jwt.io/) access and refresh tokens. " + "If token is not valid, returns '404 Bad Request'.")
@RequestMapping(value = "/noauth/activate", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public JwtTokenPair activateUser(@ApiParam(value = "Activate user request.") @RequestBody ActivateUserRequest activateRequest, @RequestParam(required = false, defaultValue = "true") boolean sendActivationMail, HttpServletRequest request) throws ThingsboardException {
    try {
        String activateToken = activateRequest.getActivateToken();
        String password = activateRequest.getPassword();
        systemSecurityService.validatePassword(TenantId.SYS_TENANT_ID, password, null);
        String encodedPassword = passwordEncoder.encode(password);
        UserCredentials credentials = userService.activateUserCredentials(TenantId.SYS_TENANT_ID, activateToken, encodedPassword);
        User user = userService.findUserById(TenantId.SYS_TENANT_ID, credentials.getUserId());
        UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
        SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal);
        userService.setUserCredentialsEnabled(user.getTenantId(), user.getId(), true);
        String baseUrl = systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), request);
        String loginUrl = String.format("%s/login", baseUrl);
        String email = user.getEmail();
        if (sendActivationMail) {
            try {
                mailService.sendAccountActivatedEmail(loginUrl, email);
            } catch (Exception e) {
                log.info("Unable to send account activation email [{}]", e.getMessage());
            }
        }
        sendEntityNotificationMsg(user.getTenantId(), user.getId(), EdgeEventActionType.CREDENTIALS_UPDATED);
        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) User(org.thingsboard.server.common.data.User) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) JwtTokenPair(org.thingsboard.server.service.security.model.JwtTokenPair) UserCredentials(org.thingsboard.server.common.data.security.UserCredentials) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal) URISyntaxException(java.net.URISyntaxException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 3 with JwtToken

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

the class AuthController method resetPassword.

@ApiOperation(value = "Reset password (resetPassword)", notes = "Checks the password reset token and updates the password. " + "If token is valid, returns the object that contains [JWT](https://jwt.io/) access and refresh tokens. " + "If token is not valid, returns '404 Bad Request'.")
@RequestMapping(value = "/noauth/resetPassword", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public JwtTokenPair resetPassword(@ApiParam(value = "Reset password request.") @RequestBody ResetPasswordRequest resetPasswordRequest, HttpServletRequest request) throws ThingsboardException {
    try {
        String resetToken = resetPasswordRequest.getResetToken();
        String password = resetPasswordRequest.getPassword();
        UserCredentials userCredentials = userService.findUserCredentialsByResetToken(TenantId.SYS_TENANT_ID, resetToken);
        if (userCredentials != null) {
            systemSecurityService.validatePassword(TenantId.SYS_TENANT_ID, password, userCredentials);
            if (passwordEncoder.matches(password, userCredentials.getPassword())) {
                throw new ThingsboardException("New password should be different from existing!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
            }
            String encodedPassword = passwordEncoder.encode(password);
            userCredentials.setPassword(encodedPassword);
            userCredentials.setResetToken(null);
            userCredentials = userService.replaceUserCredentials(TenantId.SYS_TENANT_ID, userCredentials);
            User user = userService.findUserById(TenantId.SYS_TENANT_ID, userCredentials.getUserId());
            UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
            SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), principal);
            String baseUrl = systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), request);
            String loginUrl = String.format("%s/login", baseUrl);
            String email = user.getEmail();
            mailService.sendPasswordWasResetEmail(loginUrl, email);
            eventPublisher.publishEvent(new UserAuthDataChangedEvent(securityUser.getId()));
            JwtToken accessToken = tokenFactory.createAccessJwtToken(securityUser);
            JwtToken refreshToken = refreshTokenRepository.requestRefreshToken(securityUser);
            return new JwtTokenPair(accessToken.getToken(), refreshToken.getToken());
        } else {
            throw new ThingsboardException("Invalid reset token!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
        }
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : JwtToken(org.thingsboard.server.common.data.security.model.JwtToken) User(org.thingsboard.server.common.data.User) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) JwtTokenPair(org.thingsboard.server.service.security.model.JwtTokenPair) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) UserCredentials(org.thingsboard.server.common.data.security.UserCredentials) UserAuthDataChangedEvent(org.thingsboard.server.common.data.security.event.UserAuthDataChangedEvent) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal) URISyntaxException(java.net.URISyntaxException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 4 with JwtToken

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

the class Oauth2AuthenticationSuccessHandler method onAuthenticationSuccess.

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
    OAuth2AuthorizationRequest authorizationRequest = httpCookieOAuth2AuthorizationRequestRepository.loadAuthorizationRequest(request);
    String callbackUrlScheme = authorizationRequest.getAttribute(TbOAuth2ParameterNames.CALLBACK_URL_SCHEME);
    String baseUrl;
    if (!StringUtils.isEmpty(callbackUrlScheme)) {
        baseUrl = callbackUrlScheme + ":";
    } else {
        baseUrl = this.systemSecurityService.getBaseUrl(TenantId.SYS_TENANT_ID, new CustomerId(EntityId.NULL_UUID), request);
    }
    try {
        OAuth2AuthenticationToken token = (OAuth2AuthenticationToken) authentication;
        OAuth2Registration registration = oAuth2Service.findRegistration(UUID.fromString(token.getAuthorizedClientRegistrationId()));
        OAuth2AuthorizedClient oAuth2AuthorizedClient = oAuth2AuthorizedClientService.loadAuthorizedClient(token.getAuthorizedClientRegistrationId(), token.getPrincipal().getName());
        OAuth2ClientMapper mapper = oauth2ClientMapperProvider.getOAuth2ClientMapperByType(registration.getMapperConfig().getType());
        SecurityUser securityUser = mapper.getOrCreateUserByClientPrincipal(request, token, oAuth2AuthorizedClient.getAccessToken().getTokenValue(), registration);
        JwtToken accessToken = tokenFactory.createAccessJwtToken(securityUser);
        JwtToken refreshToken = refreshTokenRepository.requestRefreshToken(securityUser);
        clearAuthenticationAttributes(request, response);
        getRedirectStrategy().sendRedirect(request, response, baseUrl + "/?accessToken=" + accessToken.getToken() + "&refreshToken=" + refreshToken.getToken());
    } catch (Exception e) {
        log.debug("Error occurred during processing authentication success result. " + "request [{}], response [{}], authentication [{}]", request, response, authentication, e);
        clearAuthenticationAttributes(request, response);
        String errorPrefix;
        if (!StringUtils.isEmpty(callbackUrlScheme)) {
            errorPrefix = "/?error=";
        } else {
            errorPrefix = "/login?loginError=";
        }
        getRedirectStrategy().sendRedirect(request, response, baseUrl + errorPrefix + URLEncoder.encode(e.getMessage(), StandardCharsets.UTF_8.toString()));
    }
}
Also used : JwtToken(org.thingsboard.server.common.data.security.model.JwtToken) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) OAuth2Registration(org.thingsboard.server.common.data.oauth2.OAuth2Registration) CustomerId(org.thingsboard.server.common.data.id.CustomerId) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) IOException(java.io.IOException)

Example 5 with JwtToken

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

the class RestAwareAuthenticationSuccessHandler method onAuthenticationSuccess.

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
    JwtToken accessToken = tokenFactory.createAccessJwtToken(securityUser);
    JwtToken refreshToken = refreshTokenRepository.requestRefreshToken(securityUser);
    Map<String, String> tokenMap = new HashMap<String, String>();
    tokenMap.put("token", accessToken.getToken());
    tokenMap.put("refreshToken", refreshToken.getToken());
    response.setStatus(HttpStatus.OK.value());
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    mapper.writeValue(response.getWriter(), tokenMap);
    clearAuthenticationAttributes(request);
}
Also used : JwtToken(org.thingsboard.server.common.data.security.model.JwtToken) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) HashMap(java.util.HashMap)

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