Search in sources :

Example 6 with OAuth2Registration

use of org.thingsboard.server.common.data.oauth2.OAuth2Registration 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 7 with OAuth2Registration

use of org.thingsboard.server.common.data.oauth2.OAuth2Registration in project thingsboard by thingsboard.

the class GithubOAuth2ClientMapper method getOrCreateUserByClientPrincipal.

@Override
public SecurityUser getOrCreateUserByClientPrincipal(HttpServletRequest request, OAuth2AuthenticationToken token, String providerAccessToken, OAuth2Registration registration) {
    OAuth2MapperConfig config = registration.getMapperConfig();
    Map<String, String> githubMapperConfig = oAuth2Configuration.getGithubMapper();
    String email = getEmail(githubMapperConfig.get(EMAIL_URL_KEY), providerAccessToken);
    Map<String, Object> attributes = token.getPrincipal().getAttributes();
    OAuth2User oAuth2User = BasicMapperUtils.getOAuth2User(email, attributes, config);
    return getOrCreateSecurityUserFromOAuth2User(oAuth2User, registration);
}
Also used : OAuth2User(org.thingsboard.server.dao.oauth2.OAuth2User) OAuth2MapperConfig(org.thingsboard.server.common.data.oauth2.OAuth2MapperConfig) ToString(lombok.ToString)

Example 8 with OAuth2Registration

use of org.thingsboard.server.common.data.oauth2.OAuth2Registration in project thingsboard by thingsboard.

the class AbstractOAuth2ClientMapper method getOrCreateSecurityUserFromOAuth2User.

protected SecurityUser getOrCreateSecurityUserFromOAuth2User(OAuth2User oauth2User, OAuth2Registration registration) {
    OAuth2MapperConfig config = registration.getMapperConfig();
    UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, oauth2User.getEmail());
    User user = userService.findUserByEmail(TenantId.SYS_TENANT_ID, oauth2User.getEmail());
    if (user == null && !config.isAllowUserCreation()) {
        throw new UsernameNotFoundException("User not found: " + oauth2User.getEmail());
    }
    if (user == null) {
        userCreationLock.lock();
        try {
            user = userService.findUserByEmail(TenantId.SYS_TENANT_ID, oauth2User.getEmail());
            if (user == null) {
                user = new User();
                if (oauth2User.getCustomerId() == null && StringUtils.isEmpty(oauth2User.getCustomerName())) {
                    user.setAuthority(Authority.TENANT_ADMIN);
                } else {
                    user.setAuthority(Authority.CUSTOMER_USER);
                }
                TenantId tenantId = oauth2User.getTenantId() != null ? oauth2User.getTenantId() : getTenantId(oauth2User.getTenantName());
                user.setTenantId(tenantId);
                CustomerId customerId = oauth2User.getCustomerId() != null ? oauth2User.getCustomerId() : getCustomerId(user.getTenantId(), oauth2User.getCustomerName());
                user.setCustomerId(customerId);
                user.setEmail(oauth2User.getEmail());
                user.setFirstName(oauth2User.getFirstName());
                user.setLastName(oauth2User.getLastName());
                ObjectNode additionalInfo = objectMapper.createObjectNode();
                if (!StringUtils.isEmpty(oauth2User.getDefaultDashboardName())) {
                    Optional<DashboardId> dashboardIdOpt = user.getAuthority() == Authority.TENANT_ADMIN ? getDashboardId(tenantId, oauth2User.getDefaultDashboardName()) : getDashboardId(tenantId, customerId, oauth2User.getDefaultDashboardName());
                    if (dashboardIdOpt.isPresent()) {
                        additionalInfo.put("defaultDashboardFullscreen", oauth2User.isAlwaysFullScreen());
                        additionalInfo.put("defaultDashboardId", dashboardIdOpt.get().getId().toString());
                    }
                }
                if (registration.getAdditionalInfo() != null && registration.getAdditionalInfo().has("providerName")) {
                    additionalInfo.put("authProviderName", registration.getAdditionalInfo().get("providerName").asText());
                }
                user.setAdditionalInfo(additionalInfo);
                user = userService.saveUser(user);
                if (config.isActivateUser()) {
                    UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getTenantId(), user.getId());
                    userService.activateUserCredentials(user.getTenantId(), userCredentials.getActivateToken(), passwordEncoder.encode(""));
                }
            }
        } catch (Exception e) {
            log.error("Can't get or create security user from oauth2 user", e);
            throw new RuntimeException("Can't get or create security user from oauth2 user", e);
        } finally {
            userCreationLock.unlock();
        }
    }
    try {
        SecurityUser securityUser = new SecurityUser(user, true, principal);
        return (SecurityUser) new UsernamePasswordAuthenticationToken(securityUser, null, securityUser.getAuthorities()).getPrincipal();
    } catch (Exception e) {
        log.error("Can't get or create security user from oauth2 user", e);
        throw new RuntimeException("Can't get or create security user from oauth2 user", e);
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) OAuth2User(org.thingsboard.server.dao.oauth2.OAuth2User) User(org.thingsboard.server.common.data.User) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) OAuth2MapperConfig(org.thingsboard.server.common.data.oauth2.OAuth2MapperConfig) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) CustomerId(org.thingsboard.server.common.data.id.CustomerId) DashboardId(org.thingsboard.server.common.data.id.DashboardId) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) IOException(java.io.IOException) TenantId(org.thingsboard.server.common.data.id.TenantId) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) UserCredentials(org.thingsboard.server.common.data.security.UserCredentials)

Example 9 with OAuth2Registration

use of org.thingsboard.server.common.data.oauth2.OAuth2Registration in project thingsboard by thingsboard.

the class BasicOAuth2ClientMapper method getOrCreateUserByClientPrincipal.

@Override
public SecurityUser getOrCreateUserByClientPrincipal(HttpServletRequest request, OAuth2AuthenticationToken token, String providerAccessToken, OAuth2Registration registration) {
    OAuth2MapperConfig config = registration.getMapperConfig();
    Map<String, Object> attributes = token.getPrincipal().getAttributes();
    String email = BasicMapperUtils.getStringAttributeByKey(attributes, config.getBasic().getEmailAttributeKey());
    OAuth2User oauth2User = BasicMapperUtils.getOAuth2User(email, attributes, config);
    return getOrCreateSecurityUserFromOAuth2User(oauth2User, registration);
}
Also used : OAuth2User(org.thingsboard.server.dao.oauth2.OAuth2User) OAuth2MapperConfig(org.thingsboard.server.common.data.oauth2.OAuth2MapperConfig)

Example 10 with OAuth2Registration

use of org.thingsboard.server.common.data.oauth2.OAuth2Registration in project thingsboard by thingsboard.

the class CustomOAuth2ClientMapper method getOrCreateUserByClientPrincipal.

@Override
public SecurityUser getOrCreateUserByClientPrincipal(HttpServletRequest request, OAuth2AuthenticationToken token, String providerAccessToken, OAuth2Registration registration) {
    OAuth2MapperConfig config = registration.getMapperConfig();
    OAuth2User oauth2User = getOAuth2User(token, providerAccessToken, config.getCustom());
    return getOrCreateSecurityUserFromOAuth2User(oauth2User, registration);
}
Also used : OAuth2User(org.thingsboard.server.dao.oauth2.OAuth2User) OAuth2MapperConfig(org.thingsboard.server.common.data.oauth2.OAuth2MapperConfig)

Aggregations

OAuth2MapperConfig (org.thingsboard.server.common.data.oauth2.OAuth2MapperConfig)8 OAuth2Registration (org.thingsboard.server.common.data.oauth2.OAuth2Registration)6 OAuth2User (org.thingsboard.server.dao.oauth2.OAuth2User)5 Arrays (java.util.Arrays)3 UUID (java.util.UUID)3 Collectors (java.util.stream.Collectors)3 MapperType (org.thingsboard.server.common.data.oauth2.MapperType)3 OAuth2CustomMapperConfig (org.thingsboard.server.common.data.oauth2.OAuth2CustomMapperConfig)3 OAuth2Info (org.thingsboard.server.common.data.oauth2.OAuth2Info)3 PlatformType (org.thingsboard.server.common.data.oauth2.PlatformType)3 IOException (java.io.IOException)2 Collections (java.util.Collections)2 List (java.util.List)2 Transactional (javax.transaction.Transactional)2 Test (org.junit.Test)2 Autowired (org.springframework.beans.factory.annotation.Autowired)2 OAuth2BasicMapperConfig (org.thingsboard.server.common.data.oauth2.OAuth2BasicMapperConfig)2 OAuth2ClientInfo (org.thingsboard.server.common.data.oauth2.OAuth2ClientInfo)2 OAuth2DomainInfo (org.thingsboard.server.common.data.oauth2.OAuth2DomainInfo)2 OAuth2MobileInfo (org.thingsboard.server.common.data.oauth2.OAuth2MobileInfo)2