Search in sources :

Example 6 with UserPrincipal

use of org.thingsboard.server.service.security.model.UserPrincipal in project thingsboard by thingsboard.

the class JwtTokenFactory method parseRefreshToken.

public SecurityUser parseRefreshToken(RawAccessJwtToken rawAccessToken) {
    Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey());
    Claims claims = jwsClaims.getBody();
    String subject = claims.getSubject();
    List<String> scopes = claims.get(SCOPES, List.class);
    if (scopes == null || scopes.isEmpty()) {
        throw new IllegalArgumentException("Refresh Token doesn't have any scopes");
    }
    if (!scopes.get(0).equals(Authority.REFRESH_TOKEN.name())) {
        throw new IllegalArgumentException("Invalid Refresh Token scope");
    }
    boolean isPublic = claims.get(IS_PUBLIC, Boolean.class);
    UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME, subject);
    SecurityUser securityUser = new SecurityUser(new UserId(UUID.fromString(claims.get(USER_ID, String.class))));
    securityUser.setUserPrincipal(principal);
    return securityUser;
}
Also used : Claims(io.jsonwebtoken.Claims) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) UserId(org.thingsboard.server.common.data.id.UserId) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal)

Example 7 with UserPrincipal

use of org.thingsboard.server.service.security.model.UserPrincipal in project thingsboard by thingsboard.

the class RestAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.notNull(authentication, "No authentication data provided");
    Object principal = authentication.getPrincipal();
    if (!(principal instanceof UserPrincipal)) {
        throw new BadCredentialsException("Authentication Failed. Bad user principal.");
    }
    UserPrincipal userPrincipal = (UserPrincipal) principal;
    if (userPrincipal.getType() == UserPrincipal.Type.USER_NAME) {
        String username = userPrincipal.getValue();
        String password = (String) authentication.getCredentials();
        return authenticateByUsernameAndPassword(userPrincipal, username, password);
    } else {
        String publicId = userPrincipal.getValue();
        return authenticateByPublicId(userPrincipal, publicId);
    }
}
Also used : UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal)

Example 8 with UserPrincipal

use of org.thingsboard.server.service.security.model.UserPrincipal in project thingsboard by thingsboard.

the class AuthController method activateUser.

@RequestMapping(value = "/noauth/activate", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public JsonNode activateUser(@RequestBody JsonNode activateRequest, HttpServletRequest request) throws ThingsboardException {
    try {
        String activateToken = activateRequest.get("activateToken").asText();
        String password = activateRequest.get("password").asText();
        String encodedPassword = passwordEncoder.encode(password);
        UserCredentials credentials = userService.activateUserCredentials(activateToken, encodedPassword);
        User user = userService.findUserById(credentials.getUserId());
        UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
        SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal);
        String baseUrl = constructBaseUrl(request);
        String loginUrl = String.format("%s/login", baseUrl);
        String email = user.getEmail();
        try {
            mailService.sendAccountActivatedEmail(loginUrl, email);
        } catch (Exception e) {
            log.info("Unable to send account activation email [{}]", e.getMessage());
        }
        JwtToken accessToken = tokenFactory.createAccessJwtToken(securityUser);
        JwtToken refreshToken = refreshTokenRepository.requestRefreshToken(securityUser);
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode tokenObject = objectMapper.createObjectNode();
        tokenObject.put("token", accessToken.getToken());
        tokenObject.put("refreshToken", refreshToken.getToken());
        return tokenObject;
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : JwtToken(org.thingsboard.server.service.security.model.token.JwtToken) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) User(org.thingsboard.server.common.data.User) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) UserCredentials(org.thingsboard.server.common.data.security.UserCredentials) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal) ThingsboardException(org.thingsboard.server.exception.ThingsboardException) URISyntaxException(java.net.URISyntaxException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 9 with UserPrincipal

use of org.thingsboard.server.service.security.model.UserPrincipal in project thingsboard by thingsboard.

the class AuthController method resetPassword.

@RequestMapping(value = "/noauth/resetPassword", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public JsonNode resetPassword(@RequestBody JsonNode resetPasswordRequest, HttpServletRequest request) throws ThingsboardException {
    try {
        String resetToken = resetPasswordRequest.get("resetToken").asText();
        String password = resetPasswordRequest.get("password").asText();
        UserCredentials userCredentials = userService.findUserCredentialsByResetToken(resetToken);
        if (userCredentials != null) {
            String encodedPassword = passwordEncoder.encode(password);
            userCredentials.setPassword(encodedPassword);
            userCredentials.setResetToken(null);
            userCredentials = userService.saveUserCredentials(userCredentials);
            User user = userService.findUserById(userCredentials.getUserId());
            UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
            SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), principal);
            String baseUrl = constructBaseUrl(request);
            String loginUrl = String.format("%s/login", baseUrl);
            String email = user.getEmail();
            mailService.sendPasswordWasResetEmail(loginUrl, email);
            JwtToken accessToken = tokenFactory.createAccessJwtToken(securityUser);
            JwtToken refreshToken = refreshTokenRepository.requestRefreshToken(securityUser);
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode tokenObject = objectMapper.createObjectNode();
            tokenObject.put("token", accessToken.getToken());
            tokenObject.put("refreshToken", refreshToken.getToken());
            return tokenObject;
        } else {
            throw new ThingsboardException("Invalid reset token!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
        }
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : JwtToken(org.thingsboard.server.service.security.model.token.JwtToken) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) User(org.thingsboard.server.common.data.User) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ThingsboardException(org.thingsboard.server.exception.ThingsboardException) UserCredentials(org.thingsboard.server.common.data.security.UserCredentials) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ThingsboardException(org.thingsboard.server.exception.ThingsboardException) URISyntaxException(java.net.URISyntaxException)

Example 10 with UserPrincipal

use of org.thingsboard.server.service.security.model.UserPrincipal in project thingsboard by thingsboard.

the class RestLoginProcessingFilter method attemptAuthentication.

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    if (!HttpMethod.POST.name().equals(request.getMethod())) {
        if (log.isDebugEnabled()) {
            log.debug("Authentication method not supported. Request method: " + request.getMethod());
        }
        throw new AuthMethodNotSupportedException("Authentication method not supported");
    }
    LoginRequest loginRequest;
    try {
        loginRequest = objectMapper.readValue(request.getReader(), LoginRequest.class);
    } catch (Exception e) {
        throw new AuthenticationServiceException("Invalid login request payload");
    }
    if (StringUtils.isBlank(loginRequest.getUsername()) || StringUtils.isBlank(loginRequest.getPassword())) {
        throw new AuthenticationServiceException("Username or Password not provided");
    }
    UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, loginRequest.getUsername());
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, loginRequest.getPassword());
    return this.getAuthenticationManager().authenticate(token);
}
Also used : AuthMethodNotSupportedException(org.thingsboard.server.service.security.exception.AuthMethodNotSupportedException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) ServletException(javax.servlet.ServletException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) IOException(java.io.IOException) AuthMethodNotSupportedException(org.thingsboard.server.service.security.exception.AuthMethodNotSupportedException) AuthenticationException(org.springframework.security.core.AuthenticationException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal)

Aggregations

UserPrincipal (org.thingsboard.server.service.security.model.UserPrincipal)12 SecurityUser (org.thingsboard.server.service.security.model.SecurityUser)7 Claims (io.jsonwebtoken.Claims)4 User (org.thingsboard.server.common.data.User)4 AuthenticationException (org.springframework.security.core.AuthenticationException)3 UserId (org.thingsboard.server.common.data.id.UserId)3 UserCredentials (org.thingsboard.server.common.data.security.UserCredentials)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 IOException (java.io.IOException)2 URISyntaxException (java.net.URISyntaxException)2 ZonedDateTime (java.time.ZonedDateTime)2 ServletException (javax.servlet.ServletException)2 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)2 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)2 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)2 CustomerId (org.thingsboard.server.common.data.id.CustomerId)2 ThingsboardException (org.thingsboard.server.exception.ThingsboardException)2 AuthMethodNotSupportedException (org.thingsboard.server.service.security.exception.AuthMethodNotSupportedException)2 JwtToken (org.thingsboard.server.service.security.model.token.JwtToken)2