Search in sources :

Example 6 with AccessToken

use of oidc.model.AccessToken in project OpenConext-oidcng by OpenConext.

the class TokenEndpoint method handleRefreshCodeGrant.

private ResponseEntity handleRefreshCodeGrant(RefreshTokenGrant refreshTokenGrant, OpenIDClient client) throws java.text.ParseException {
    String refreshTokenValue = refreshTokenGrant.getRefreshToken().getValue();
    RefreshToken refreshToken;
    SignedJWT signedJWT = null;
    boolean oldFormat = uuidPattern.matcher(refreshTokenValue).matches();
    if (oldFormat) {
        // Old refreshToken
        refreshToken = refreshTokenRepository.findByInnerValue(refreshTokenValue);
    } else {
        Optional<SignedJWT> optionalSignedJWT = tokenGenerator.parseAndValidateSignedJWT(refreshTokenValue);
        signedJWT = optionalSignedJWT.orElseThrow(() -> new UnauthorizedException("Invalid refresh_token value"));
        String jwtId = signedJWT.getJWTClaimsSet().getJWTID();
        refreshToken = refreshTokenRepository.findByJwtId(jwtId).orElseThrow(() -> new IllegalArgumentException("RefreshToken not found"));
    }
    if (!refreshToken.getClientId().equals(client.getClientId())) {
        throw new InvalidClientException("Client is not authorized for the refresh token");
    }
    if (refreshToken.isExpired(Clock.systemDefaultZone())) {
        throw new UnauthorizedException("Refresh token expired");
    }
    // New tokens will be issued
    refreshTokenRepository.delete(refreshToken);
    // It is possible that the access token is already removed by cron cleanup actions
    Optional<AccessToken> accessToken;
    if (oldFormat) {
        // It is possible that the access token is already removed by cron cleanup actions
        accessToken = accessTokenRepository.findOptionalAccessTokenByValue(refreshToken.getAccessTokenValue());
    } else {
        accessToken = accessTokenRepository.findById(refreshToken.getAccessTokenId());
    }
    accessToken.ifPresent(accessTokenRepository::delete);
    Optional<User> optionalUser;
    if (refreshToken.isClientCredentials()) {
        optionalUser = Optional.empty();
    } else if (oldFormat) {
        optionalUser = Optional.of(tokenGenerator.decryptAccessTokenWithEmbeddedUserInfo(refreshToken.getAccessTokenValue()));
    } else {
        optionalUser = Optional.of(tokenGenerator.decryptAccessTokenWithEmbeddedUserInfo(signedJWT));
    }
    Map<String, Object> body = tokenEndpointResponse(optionalUser, client, refreshToken.getScopes(), Collections.emptyList(), false, null, optionalUser.map(User::getUpdatedAt), Optional.empty());
    return new ResponseEntity<>(body, responseHttpHeaders, HttpStatus.OK);
}
Also used : User(oidc.model.User) SignedJWT(com.nimbusds.jwt.SignedJWT) ResponseEntity(org.springframework.http.ResponseEntity) RefreshToken(oidc.model.RefreshToken) AccessToken(oidc.model.AccessToken) UnauthorizedException(oidc.exceptions.UnauthorizedException) InvalidClientException(oidc.exceptions.InvalidClientException)

Example 7 with AccessToken

use of oidc.model.AccessToken in project OpenConext-oidcng by OpenConext.

the class TokenEndpoint method tokenEndpointResponse.

private Map<String, Object> tokenEndpointResponse(Optional<User> user, OpenIDClient client, List<String> scopes, List<String> idTokenClaims, boolean clientCredentials, String nonce, Optional<Long> authorizationTime, Optional<String> authorizationCodeId) {
    Map<String, Object> map = new LinkedHashMap<>();
    EncryptedTokenValue encryptedAccessToken = user.map(u -> tokenGenerator.generateAccessTokenWithEmbeddedUserInfo(u, client, scopes)).orElse(tokenGenerator.generateAccessToken(client, scopes));
    String sub = user.map(User::getSub).orElse(client.getClientId());
    String unspecifiedUrnHash = user.map(u -> KeyGenerator.oneWayHash(u.getUnspecifiedNameId(), this.salt)).orElse(null);
    AccessToken accessToken = new AccessToken(encryptedAccessToken.getJwtId(), sub, client.getClientId(), scopes, encryptedAccessToken.getKeyId(), accessTokenValidity(client), !user.isPresent(), authorizationCodeId.orElse(null), unspecifiedUrnHash);
    accessToken = accessTokenRepository.insert(accessToken);
    map.put("access_token", encryptedAccessToken.getValue());
    map.put("token_type", "Bearer");
    if (client.getGrants().contains(GrantType.REFRESH_TOKEN.getValue())) {
        EncryptedTokenValue encryptedRefreshToken = user.map(u -> tokenGenerator.generateRefreshTokenWithEmbeddedUserInfo(u, client)).orElse(tokenGenerator.generateRefreshToken(client));
        String refreshTokenValue = encryptedRefreshToken.getValue();
        refreshTokenRepository.insert(new RefreshToken(encryptedRefreshToken.getJwtId(), accessToken, refreshTokenValidity(client)));
        map.put("refresh_token", refreshTokenValue);
    }
    map.put("expires_in", client.getAccessTokenValidity());
    if (isOpenIDRequest(scopes) && !clientCredentials) {
        TokenValue tokenValue = tokenGenerator.generateIDTokenForTokenEndpoint(user, client, nonce, idTokenClaims, scopes, authorizationTime);
        map.put("id_token", tokenValue.getValue());
    }
    return map;
}
Also used : AuthorizationCodeRepository(oidc.repository.AuthorizationCodeRepository) CodeVerifierMissingException(oidc.exceptions.CodeVerifierMissingException) Date(java.util.Date) JOSEException(com.nimbusds.jose.JOSEException) ClientAuthentication(com.nimbusds.oauth2.sdk.auth.ClientAuthentication) User(oidc.model.User) MACVerifier(com.nimbusds.jose.crypto.MACVerifier) RefreshTokenGrant(com.nimbusds.oauth2.sdk.RefreshTokenGrant) Map(java.util.Map) ClientSecretJWT(com.nimbusds.oauth2.sdk.auth.ClientSecretJWT) CodeVerifier(com.nimbusds.oauth2.sdk.pkce.CodeVerifier) PostMapping(org.springframework.web.bind.annotation.PostMapping) APPLICATION_JSON(org.apache.http.entity.ContentType.APPLICATION_JSON) HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType) SignedJWT(com.nimbusds.jwt.SignedJWT) RestController(org.springframework.web.bind.annotation.RestController) Collectors(java.util.stream.Collectors) TokenRequest(com.nimbusds.oauth2.sdk.TokenRequest) List(java.util.List) OpenIDClientRepository(oidc.repository.OpenIDClientRepository) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Scope(oidc.model.Scope) Optional(java.util.Optional) TokenGenerator(oidc.secure.TokenGenerator) LogFactory(org.apache.commons.logging.LogFactory) Pattern(java.util.regex.Pattern) JWTAuthentication(com.nimbusds.oauth2.sdk.auth.JWTAuthentication) CodeChallengeMethod(com.nimbusds.oauth2.sdk.pkce.CodeChallengeMethod) AuthorizationCode(oidc.model.AuthorizationCode) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) GrantType(com.nimbusds.oauth2.sdk.GrantType) MessageDigest(java.security.MessageDigest) ServletUtils(com.nimbusds.oauth2.sdk.http.ServletUtils) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) RedirectMismatchException(oidc.exceptions.RedirectMismatchException) JWTAuthorizationGrantsException(oidc.exceptions.JWTAuthorizationGrantsException) UnknownClientException(oidc.exceptions.UnknownClientException) RefreshTokenRepository(oidc.repository.RefreshTokenRepository) Value(org.springframework.beans.factory.annotation.Value) LinkedHashMap(java.util.LinkedHashMap) CodeChallenge(com.nimbusds.oauth2.sdk.pkce.CodeChallenge) KeyGenerator(oidc.crypto.KeyGenerator) HttpServletRequest(javax.servlet.http.HttpServletRequest) TokenValue(oidc.model.TokenValue) InvalidClientException(oidc.exceptions.InvalidClientException) ParseException(com.nimbusds.oauth2.sdk.ParseException) PlainClientSecret(com.nimbusds.oauth2.sdk.auth.PlainClientSecret) OpenIDClient(oidc.model.OpenIDClient) MDCContext(oidc.log.MDCContext) JWTRequest(oidc.secure.JWTRequest) ClientCredentialsGrant(com.nimbusds.oauth2.sdk.ClientCredentialsGrant) HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) AuthorizationGrant(com.nimbusds.oauth2.sdk.AuthorizationGrant) AuthorizationCodeGrant(com.nimbusds.oauth2.sdk.AuthorizationCodeGrant) TokenAlreadyUsedException(oidc.exceptions.TokenAlreadyUsedException) InvalidGrantException(oidc.exceptions.InvalidGrantException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) AccessTokenRepository(oidc.repository.AccessTokenRepository) EncryptedTokenValue(oidc.model.EncryptedTokenValue) UserRepository(oidc.repository.UserRepository) HttpStatus(org.springframework.http.HttpStatus) AccessToken(oidc.model.AccessToken) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) UnauthorizedException(oidc.exceptions.UnauthorizedException) Clock(java.time.Clock) Log(org.apache.commons.logging.Log) ResponseEntity(org.springframework.http.ResponseEntity) NoSuchProviderException(java.security.NoSuchProviderException) Collections(java.util.Collections) AuthorizationEndpoint.validateScopes(oidc.endpoints.AuthorizationEndpoint.validateScopes) RefreshToken(oidc.model.RefreshToken) RefreshToken(oidc.model.RefreshToken) AccessToken(oidc.model.AccessToken) EncryptedTokenValue(oidc.model.EncryptedTokenValue) LinkedHashMap(java.util.LinkedHashMap) TokenValue(oidc.model.TokenValue) EncryptedTokenValue(oidc.model.EncryptedTokenValue)

Example 8 with AccessToken

use of oidc.model.AccessToken in project OpenConext-oidcng by OpenConext.

the class UserInfoEndpoint method userInfo.

private ResponseEntity<Map<String, Object>> userInfo(HttpServletRequest request) throws ParseException, IOException, java.text.ParseException {
    HTTPRequest httpRequest = ServletUtils.createHTTPRequest(request);
    UserInfoRequest userInfoRequest = UserInfoRequest.parse(httpRequest);
    String accessTokenValue = userInfoRequest.getAccessToken().getValue();
    MDCContext.mdcContext("action", "Userinfo", "accessTokenValue", accessTokenValue);
    Optional<SignedJWT> optionalSignedJWT = tokenGenerator.parseAndValidateSignedJWT(accessTokenValue);
    if (!optionalSignedJWT.isPresent()) {
        return errorResponse("Access Token not found");
    }
    SignedJWT signedJWT = optionalSignedJWT.get();
    String jwtId = signedJWT.getJWTClaimsSet().getJWTID();
    Optional<AccessToken> optionalAccessToken = accessTokenRepository.findByJwtId(jwtId);
    if (!optionalAccessToken.isPresent()) {
        return errorResponse("Access Token not found");
    }
    AccessToken accessToken = optionalAccessToken.get();
    if (accessToken.isExpired(Clock.systemDefaultZone())) {
        return errorResponse("Access Token expired");
    }
    if (accessToken.isClientCredentials()) {
        throw new InvalidGrantException("UserEndpoint not allowed for Client Credentials");
    }
    User user = tokenGenerator.decryptAccessTokenWithEmbeddedUserInfo(signedJWT);
    MDCContext.mdcContext(user);
    Map<String, Object> attributes = user.getAttributes();
    List<String> acrClaims = user.getAcrClaims();
    if (!CollectionUtils.isEmpty(acrClaims)) {
        attributes.put("acr", String.join(" ", acrClaims));
    }
    attributes.put("updated_at", user.getUpdatedAt());
    attributes.put("sub", user.getSub());
    return ResponseEntity.ok(new TreeMap(attributes));
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) User(oidc.model.User) UserInfoRequest(com.nimbusds.openid.connect.sdk.UserInfoRequest) SignedJWT(com.nimbusds.jwt.SignedJWT) TreeMap(java.util.TreeMap) InvalidGrantException(oidc.exceptions.InvalidGrantException) AccessToken(oidc.model.AccessToken)

Aggregations

AccessToken (oidc.model.AccessToken)8 SignedJWT (com.nimbusds.jwt.SignedJWT)4 RefreshToken (oidc.model.RefreshToken)4 HTTPRequest (com.nimbusds.oauth2.sdk.http.HTTPRequest)3 Date (java.util.Date)3 UnauthorizedException (oidc.exceptions.UnauthorizedException)3 User (oidc.model.User)3 ClientAuthentication (com.nimbusds.oauth2.sdk.auth.ClientAuthentication)2 PlainClientSecret (com.nimbusds.oauth2.sdk.auth.PlainClientSecret)2 IOException (java.io.IOException)2 LinkedHashMap (java.util.LinkedHashMap)2 List (java.util.List)2 Collectors.toList (java.util.stream.Collectors.toList)2 AbstractIntegrationTest (oidc.AbstractIntegrationTest)2 InvalidClientException (oidc.exceptions.InvalidClientException)2 InvalidGrantException (oidc.exceptions.InvalidGrantException)2 OpenIDClient (oidc.model.OpenIDClient)2 Test (org.junit.Test)2 ResponseEntity (org.springframework.http.ResponseEntity)2 JOSEException (com.nimbusds.jose.JOSEException)1