Search in sources :

Example 1 with UserPrincipal

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

the class RefreshTokenAuthenticationProvider method authenticateByUserId.

private SecurityUser authenticateByUserId(UserId userId) {
    User user = userService.findUserById(userId);
    if (user == null) {
        throw new UsernameNotFoundException("User not found by refresh token");
    }
    UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId());
    if (userCredentials == null) {
        throw new UsernameNotFoundException("User credentials not found");
    }
    if (!userCredentials.isEnabled()) {
        throw new DisabledException("User is not active");
    }
    if (user.getAuthority() == null)
        throw new InsufficientAuthenticationException("User has no authority assigned");
    UserPrincipal userPrincipal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
    SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), userPrincipal);
    return securityUser;
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) User(org.thingsboard.server.common.data.User) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) UserCredentials(org.thingsboard.server.common.data.security.UserCredentials) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal)

Example 2 with UserPrincipal

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

the class RefreshTokenAuthenticationProvider method authenticateByPublicId.

private SecurityUser authenticateByPublicId(String publicId) {
    CustomerId customerId;
    try {
        customerId = new CustomerId(UUID.fromString(publicId));
    } catch (Exception e) {
        throw new BadCredentialsException("Refresh token is not valid");
    }
    Customer publicCustomer = customerService.findCustomerById(customerId);
    if (publicCustomer == null) {
        throw new UsernameNotFoundException("Public entity not found by refresh token");
    }
    if (!publicCustomer.isPublic()) {
        throw new BadCredentialsException("Refresh token is not valid");
    }
    User user = new User(new UserId(EntityId.NULL_UUID));
    user.setTenantId(publicCustomer.getTenantId());
    user.setCustomerId(publicCustomer.getId());
    user.setEmail(publicId);
    user.setAuthority(Authority.CUSTOMER_USER);
    user.setFirstName("Public");
    user.setLastName("Public");
    UserPrincipal userPrincipal = new UserPrincipal(UserPrincipal.Type.PUBLIC_ID, publicId);
    SecurityUser securityUser = new SecurityUser(user, true, userPrincipal);
    return securityUser;
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) User(org.thingsboard.server.common.data.User) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) Customer(org.thingsboard.server.common.data.Customer) UserId(org.thingsboard.server.common.data.id.UserId) CustomerId(org.thingsboard.server.common.data.id.CustomerId) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) AuthenticationException(org.springframework.security.core.AuthenticationException) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal)

Example 3 with UserPrincipal

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

the class RefreshTokenAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.notNull(authentication, "No authentication data provided");
    RawAccessJwtToken rawAccessToken = (RawAccessJwtToken) authentication.getCredentials();
    SecurityUser unsafeUser = tokenFactory.parseRefreshToken(rawAccessToken);
    UserPrincipal principal = unsafeUser.getUserPrincipal();
    SecurityUser securityUser;
    if (principal.getType() == UserPrincipal.Type.USER_NAME) {
        securityUser = authenticateByUserId(unsafeUser.getId());
    } else {
        securityUser = authenticateByPublicId(principal.getValue());
    }
    return new RefreshAuthenticationToken(securityUser);
}
Also used : SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) RefreshAuthenticationToken(org.thingsboard.server.service.security.auth.RefreshAuthenticationToken) RawAccessJwtToken(org.thingsboard.server.service.security.model.token.RawAccessJwtToken) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal)

Example 4 with UserPrincipal

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

the class RestPublicLoginProcessingFilter 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");
    }
    PublicLoginRequest loginRequest;
    try {
        loginRequest = objectMapper.readValue(request.getReader(), PublicLoginRequest.class);
    } catch (Exception e) {
        throw new AuthenticationServiceException("Invalid public login request payload");
    }
    if (StringUtils.isBlank(loginRequest.getPublicId())) {
        throw new AuthenticationServiceException("Public Id is not provided");
    }
    UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.PUBLIC_ID, loginRequest.getPublicId());
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, "");
    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)

Example 5 with UserPrincipal

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

the class JwtTokenFactory method createAccessJwtToken.

/**
 * Factory method for issuing new JWT Tokens.
 */
public AccessJwtToken createAccessJwtToken(SecurityUser securityUser) {
    if (StringUtils.isBlank(securityUser.getEmail()))
        throw new IllegalArgumentException("Cannot create JWT Token without username/email");
    if (securityUser.getAuthority() == null)
        throw new IllegalArgumentException("User doesn't have any privileges");
    UserPrincipal principal = securityUser.getUserPrincipal();
    String subject = principal.getValue();
    Claims claims = Jwts.claims().setSubject(subject);
    claims.put(SCOPES, securityUser.getAuthorities().stream().map(s -> s.getAuthority()).collect(Collectors.toList()));
    claims.put(USER_ID, securityUser.getId().getId().toString());
    claims.put(FIRST_NAME, securityUser.getFirstName());
    claims.put(LAST_NAME, securityUser.getLastName());
    claims.put(ENABLED, securityUser.isEnabled());
    claims.put(IS_PUBLIC, principal.getType() == UserPrincipal.Type.PUBLIC_ID);
    if (securityUser.getTenantId() != null) {
        claims.put(TENANT_ID, securityUser.getTenantId().getId().toString());
    }
    if (securityUser.getCustomerId() != null) {
        claims.put(CUSTOMER_ID, securityUser.getCustomerId().getId().toString());
    }
    ZonedDateTime currentTime = ZonedDateTime.now();
    String token = Jwts.builder().setClaims(claims).setIssuer(settings.getTokenIssuer()).setIssuedAt(Date.from(currentTime.toInstant())).setExpiration(Date.from(currentTime.plusSeconds(settings.getTokenExpirationTime()).toInstant())).signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey()).compact();
    return new AccessJwtToken(token, claims);
}
Also used : Claims(io.jsonwebtoken.Claims) ZonedDateTime(java.time.ZonedDateTime) 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