Search in sources :

Example 16 with OAuth2Client

use of de.ids_mannheim.korap.oauth2.entity.OAuth2Client in project Kustvakt by KorAP.

the class OltuAuthorizationService method requestAuthorizationCode.

/**
 * Authorization code request does not require client
 * authentication, but only checks if the client id exists.
 *
 * @param request
 * @param authzRequest
 * @param username
 * @param authTime
 * @return redirect URI containing authorization code if
 *         successful.
 *
 * @throws KustvaktException
 * @throws OAuthSystemException
 */
public String requestAuthorizationCode(HttpServletRequest request, OAuthAuthzRequest authzRequest, String username, ZonedDateTime authenticationTime) throws OAuthSystemException, KustvaktException {
    String clientId = authzRequest.getClientId();
    OAuth2Client client = clientService.authenticateClientId(clientId);
    String redirectUriStr = authzRequest.getRedirectURI();
    String verifiedRedirectUri = verifyRedirectUri(client, redirectUriStr);
    URI redirectURI;
    try {
        redirectURI = new URI(verifiedRedirectUri);
    } catch (URISyntaxException e) {
        throw new KustvaktException(StatusCodes.INVALID_REDIRECT_URI, "Invalid redirect URI", OAuth2Error.INVALID_REQUEST);
    }
    String scope, code;
    try {
        checkResponseType(authzRequest.getResponseType());
        code = codeGenerator.createRandomCode();
        scope = createAuthorization(username, authzRequest.getClientId(), redirectUriStr, authzRequest.getScopes(), code, authenticationTime, null);
    } catch (KustvaktException e) {
        e.setRedirectUri(redirectURI);
        throw e;
    }
    OAuthResponse oAuthResponse;
    try {
        oAuthResponse = OAuthASResponse.authorizationResponse(request, Status.FOUND.getStatusCode()).setCode(code).setScope(scope).location(verifiedRedirectUri).buildQueryMessage();
    } catch (OAuthSystemException e) {
        // Should not happen
        KustvaktException ke = new KustvaktException(StatusCodes.OAUTH2_SYSTEM_ERROR, e.getMessage(), OAuth2Error.SERVER_ERROR);
        ke.setRedirectUri(redirectURI);
        throw ke;
    }
    return oAuthResponse.getLocationUri();
}
Also used : KustvaktException(de.ids_mannheim.korap.exceptions.KustvaktException) OAuth2Client(de.ids_mannheim.korap.oauth2.entity.OAuth2Client) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse)

Example 17 with OAuth2Client

use of de.ids_mannheim.korap.oauth2.entity.OAuth2Client in project Kustvakt by KorAP.

the class OltuTokenService method listUserRefreshToken.

public List<OAuth2TokenDto> listUserRefreshToken(String username, String superClientId, String superClientSecret, String clientId) throws KustvaktException {
    OAuth2Client client = clientService.authenticateClient(superClientId, superClientSecret);
    if (!client.isSuper()) {
        throw new KustvaktException(StatusCodes.CLIENT_AUTHORIZATION_FAILED, "Only super client is allowed.", OAuth2Error.UNAUTHORIZED_CLIENT);
    }
    List<RefreshToken> tokens = refreshDao.retrieveRefreshTokenByUser(username, clientId);
    List<OAuth2TokenDto> dtoList = new ArrayList<>(tokens.size());
    for (RefreshToken t : tokens) {
        OAuth2Client tokenClient = t.getClient();
        if (tokenClient.getId().equals(client.getId())) {
            continue;
        }
        OAuth2TokenDto dto = new OAuth2TokenDto();
        dto.setClientId(tokenClient.getId());
        dto.setClientName(tokenClient.getName());
        dto.setClientUrl(tokenClient.getUrl());
        dto.setClientDescription(tokenClient.getDescription());
        DateTimeFormatter f = DateTimeFormatter.ISO_DATE_TIME;
        dto.setCreatedDate(t.getCreatedDate().format(f));
        long difference = ChronoUnit.SECONDS.between(ZonedDateTime.now(), t.getExpiryDate());
        dto.setExpiresIn(difference);
        dto.setUserAuthenticationTime(t.getUserAuthenticationTime().format(f));
        dto.setToken(t.getToken());
        Set<AccessScope> accessScopes = t.getScopes();
        Set<String> scopes = new HashSet<>(accessScopes.size());
        for (AccessScope s : accessScopes) {
            scopes.add(s.getId().toString());
        }
        dto.setScope(scopes);
        dtoList.add(dto);
    }
    return dtoList;
}
Also used : KustvaktException(de.ids_mannheim.korap.exceptions.KustvaktException) OAuth2Client(de.ids_mannheim.korap.oauth2.entity.OAuth2Client) ArrayList(java.util.ArrayList) OAuth2TokenDto(de.ids_mannheim.korap.oauth2.dto.OAuth2TokenDto) RefreshToken(de.ids_mannheim.korap.oauth2.entity.RefreshToken) DateTimeFormatter(java.time.format.DateTimeFormatter) AccessScope(de.ids_mannheim.korap.oauth2.entity.AccessScope) HashSet(java.util.HashSet)

Example 18 with OAuth2Client

use of de.ids_mannheim.korap.oauth2.entity.OAuth2Client in project Kustvakt by KorAP.

the class OltuTokenService method requestAccessTokenWithRefreshToken.

/**
 * Revokes all access token associated with the given refresh
 * token, and creates a new access token and a new refresh
 * token with the same scopes. Thus, at one point of time,
 * there is only one active access token associated with
 * a refresh token.
 *
 * Client authentication is done using the given client
 * credentials.
 *
 * TODO: should create a new refresh token when the old refresh
 * token is used (DONE)
 *
 * @param refreshTokenStr
 * @param scopes
 * @param clientId
 * @param clientSecret
 * @return if successful, a new access token
 * @throws KustvaktException
 * @throws OAuthSystemException
 */
private OAuthResponse requestAccessTokenWithRefreshToken(String refreshTokenStr, Set<String> scopes, String clientId, String clientSecret) throws KustvaktException, OAuthSystemException {
    if (refreshTokenStr == null || refreshTokenStr.isEmpty()) {
        throw new KustvaktException(StatusCodes.MISSING_PARAMETER, "Missing parameters: refresh_token", OAuth2Error.INVALID_REQUEST);
    }
    OAuth2Client oAuth2Client = clientService.authenticateClient(clientId, clientSecret);
    RefreshToken refreshToken;
    try {
        refreshToken = refreshDao.retrieveRefreshToken(refreshTokenStr);
    } catch (NoResultException e) {
        throw new KustvaktException(StatusCodes.INVALID_REFRESH_TOKEN, "Refresh token is not found", OAuth2Error.INVALID_GRANT);
    }
    if (!clientId.equals(refreshToken.getClient().getId())) {
        throw new KustvaktException(StatusCodes.CLIENT_AUTHORIZATION_FAILED, "Client " + clientId + "is not authorized", OAuth2Error.INVALID_CLIENT);
    } else if (refreshToken.isRevoked()) {
        throw new KustvaktException(StatusCodes.INVALID_REFRESH_TOKEN, "Refresh token has been revoked", OAuth2Error.INVALID_GRANT);
    } else if (ZonedDateTime.now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE)).isAfter(refreshToken.getExpiryDate())) {
        throw new KustvaktException(StatusCodes.INVALID_REFRESH_TOKEN, "Refresh token is expired", OAuth2Error.INVALID_GRANT);
    }
    Set<AccessScope> requestedScopes = new HashSet<>(refreshToken.getScopes());
    if (scopes != null && !scopes.isEmpty()) {
        requestedScopes = scopeService.verifyRefreshScope(scopes, requestedScopes);
        scopes = scopeService.convertAccessScopesToStringSet(requestedScopes);
    }
    // revoke the refresh token and all access tokens associated to it
    revokeRefreshToken(refreshTokenStr);
    return createsAccessTokenResponse(scopes, requestedScopes, clientId, refreshToken.getUserId(), refreshToken.getUserAuthenticationTime(), clientService.isPublicClient(oAuth2Client));
// without new refresh token
// return createsAccessTokenResponse(scopes, requestedScopes,
// clientId,
// refreshToken.getUserId(),
// refreshToken.getUserAuthenticationTime(), refreshToken);
}
Also used : KustvaktException(de.ids_mannheim.korap.exceptions.KustvaktException) RefreshToken(de.ids_mannheim.korap.oauth2.entity.RefreshToken) OAuth2Client(de.ids_mannheim.korap.oauth2.entity.OAuth2Client) NoResultException(javax.persistence.NoResultException) AccessScope(de.ids_mannheim.korap.oauth2.entity.AccessScope) HashSet(java.util.HashSet)

Example 19 with OAuth2Client

use of de.ids_mannheim.korap.oauth2.entity.OAuth2Client in project Kustvakt by KorAP.

the class OltuTokenService method requestAccessTokenWithAuthorizationCode.

/**
 * Issues an access token for the specified client if the
 * authorization code is valid and client successfully
 * authenticates.
 *
 * @param code
 *            authorization code, required
 * @param redirectUri
 *            client redirect uri, required if specified in the
 *            authorization request
 * @param clientId
 *            client id, required
 * @param clientSecret
 *            client secret, required
 * @return an {@link OAuthResponse}
 * @throws OAuthSystemException
 * @throws KustvaktException
 */
private OAuthResponse requestAccessTokenWithAuthorizationCode(String code, String redirectUri, String clientId, String clientSecret) throws OAuthSystemException, KustvaktException {
    Authorization authorization = retrieveAuthorization(code, redirectUri, clientId, clientSecret);
    Set<String> scopes = scopeService.convertAccessScopesToStringSet(authorization.getScopes());
    OAuth2Client oAuth2Client = clientService.retrieveClient(clientId);
    return createsAccessTokenResponse(scopes, authorization.getScopes(), authorization.getClientId(), authorization.getUserId(), authorization.getUserAuthenticationTime(), clientService.isPublicClient(oAuth2Client));
}
Also used : Authorization(de.ids_mannheim.korap.oauth2.entity.Authorization) OAuth2Client(de.ids_mannheim.korap.oauth2.entity.OAuth2Client)

Example 20 with OAuth2Client

use of de.ids_mannheim.korap.oauth2.entity.OAuth2Client in project Kustvakt by KorAP.

the class OltuTokenService method revokeTokensViaSuperClient.

public void revokeTokensViaSuperClient(String username, OAuth2RevokeTokenSuperRequest revokeTokenRequest) throws KustvaktException {
    String superClientId = revokeTokenRequest.getSuperClientId();
    String superClientSecret = revokeTokenRequest.getSuperClientSecret();
    OAuth2Client superClient = clientService.authenticateClient(superClientId, superClientSecret);
    if (!superClient.isSuper()) {
        throw new KustvaktException(StatusCodes.CLIENT_AUTHENTICATION_FAILED);
    }
    String token = revokeTokenRequest.getToken();
    RefreshToken refreshToken = refreshDao.retrieveRefreshToken(token, username);
    if (!revokeRefreshToken(refreshToken)) {
        AccessToken accessToken = tokenDao.retrieveAccessToken(token, username);
        revokeAccessToken(accessToken);
    }
}
Also used : KustvaktException(de.ids_mannheim.korap.exceptions.KustvaktException) RefreshToken(de.ids_mannheim.korap.oauth2.entity.RefreshToken) OAuth2Client(de.ids_mannheim.korap.oauth2.entity.OAuth2Client) AccessToken(de.ids_mannheim.korap.oauth2.entity.AccessToken)

Aggregations

OAuth2Client (de.ids_mannheim.korap.oauth2.entity.OAuth2Client)29 KustvaktException (de.ids_mannheim.korap.exceptions.KustvaktException)17 ZonedDateTime (java.time.ZonedDateTime)9 RefreshToken (de.ids_mannheim.korap.oauth2.entity.RefreshToken)8 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)8 AccessToken (de.ids_mannheim.korap.oauth2.entity.AccessToken)7 AccessScope (de.ids_mannheim.korap.oauth2.entity.AccessScope)6 Predicate (javax.persistence.criteria.Predicate)6 ArrayList (java.util.ArrayList)4 HashSet (java.util.HashSet)3 Scope (com.nimbusds.oauth2.sdk.Scope)2 OAuth2TokenDto (de.ids_mannheim.korap.oauth2.dto.OAuth2TokenDto)2 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 DateTimeFormatter (java.time.format.DateTimeFormatter)2 NoResultException (javax.persistence.NoResultException)2 ResponseType (com.nimbusds.oauth2.sdk.ResponseType)1 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)1 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)1 RefreshToken (com.nimbusds.oauth2.sdk.token.RefreshToken)1