Search in sources :

Example 1 with JWTClaimsSet

use of com.nimbusds.jwt.JWTClaimsSet in project cas by apereo.

the class TokenWebApplicationServiceResponseBuilder method generateToken.

/**
     * Generate token string.
     *
     * @param service    the service
     * @param parameters the parameters
     * @return the jwt
     */
protected String generateToken(final Service service, final Map<String, String> parameters) {
    try {
        final String ticketId = parameters.get(CasProtocolConstants.PARAMETER_TICKET);
        final Cas30ServiceTicketValidator validator = new Cas30ServiceTicketValidator(casProperties.getServer().getPrefix());
        final Assertion assertion = validator.validate(ticketId, service.getId());
        final JWTClaimsSet.Builder claims = new JWTClaimsSet.Builder().audience(service.getId()).issuer(casProperties.getServer().getPrefix()).jwtID(ticketId).issueTime(assertion.getAuthenticationDate()).subject(assertion.getPrincipal().getName());
        assertion.getAttributes().forEach(claims::claim);
        assertion.getPrincipal().getAttributes().forEach(claims::claim);
        if (assertion.getValidUntilDate() != null) {
            claims.expirationTime(assertion.getValidUntilDate());
        } else {
            final ZonedDateTime dt = ZonedDateTime.now().plusSeconds(ticketGrantingTicketExpirationPolicy.getTimeToLive());
            claims.expirationTime(DateTimeUtils.dateOf(dt));
        }
        final JWTClaimsSet claimsSet = claims.build();
        final JSONObject object = claimsSet.toJSONObject();
        return tokenCipherExecutor.encode(object.toJSONString());
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
Also used : Cas30ServiceTicketValidator(org.jasig.cas.client.validation.Cas30ServiceTicketValidator) JSONObject(net.minidev.json.JSONObject) ZonedDateTime(java.time.ZonedDateTime) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) Assertion(org.jasig.cas.client.validation.Assertion)

Example 2 with JWTClaimsSet

use of com.nimbusds.jwt.JWTClaimsSet in project SEPA by arces-wot.

the class AuthorizationManager method getToken.

/**
 * POST https://wot.arces.unibo.it:8443/oauth/token
 *
 * Content-Type: application/x-www-form-urlencoded
 * Accept: application/json
 * Authorization: Basic Basic64(id:secret)
 *
 * Response example:
 * { 	"access_token": "eyJraWQiOiIyN.........",
 * 		"token_type": "bearer",
 * 		"expires_in": 3600
 * }
 *
 * In case of error, the following applies:
 * {
 * 		"code": Error code,
 * 		"body": "Error details"
 *
 * }
 */
public Response getToken(String encodedCredentials) {
    logger.debug("Get token");
    // Decode credentials
    byte[] decoded = null;
    try {
        decoded = Base64.getDecoder().decode(encodedCredentials);
    } catch (IllegalArgumentException e) {
        logger.error("Not authorized");
        return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
    }
    String decodedCredentials = new String(decoded);
    String[] clientID = decodedCredentials.split(":");
    if (clientID == null) {
        logger.error("Wrong Basic authorization");
        return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
    }
    if (clientID.length != 2) {
        logger.error("Wrong Basic authorization");
        return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
    }
    String id = decodedCredentials.split(":")[0];
    String secret = decodedCredentials.split(":")[1];
    logger.debug("Credentials: " + id + " " + secret);
    // Verify credentials
    if (!credentials.containsKey(id)) {
        logger.error("Client id: " + id + " is not registered");
        return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
    }
    if (!credentials.get(id).equals(secret)) {
        logger.error("Wrong secret: " + secret + " for client id: " + id);
        return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
    }
    // Check is a token has been release for this client
    if (clientClaims.containsKey(id)) {
        // Do not return a new token if the previous one is not expired
        Date expires = clientClaims.get(id).getExpirationTime();
        Date now = new Date();
        logger.debug("Check token expiration: " + now + " > " + expires + " ?");
        if (now.before(expires)) {
            logger.warn("Token is not expired");
            return new ErrorResponse(0, HttpStatus.SC_BAD_REQUEST, "Token is not expired");
        }
    }
    // Prepare JWT with claims set
    JWTClaimsSet.Builder claimsSetBuilder = new JWTClaimsSet.Builder();
    long timestamp = new Date().getTime();
    /*
		 * 4.1.1.  "iss" (Issuer) Claim

	   The "iss" (issuer) claim identifies the principal that issued the
	   JWT.  The processing of this claim is generally application specific.
	   The "iss" value is a case-sensitive string containing a StringOrURI
	   value.  Use of this claim is OPTIONAL.*/
    claimsSetBuilder.issuer(AuthorizationManagerBeans.getIssuer());
    /* 4.1.2.  "sub" (Subject) Claim

	   The "sub" (subject) claim identifies the principal that is the
	   subject of the JWT.  The Claims in a JWT are normally statements
	   about the subject.  The subject value MUST either be scoped to be
	   locally unique in the context of the issuer or be globally unique.
	   The processing of this claim is generally application specific.  The
	   "sub" value is a case-sensitive string containing a StringOrURI
	   value.  Use of this claim is OPTIONAL.*/
    claimsSetBuilder.subject(AuthorizationManagerBeans.getSubject());
    /* 4.1.3.  "aud" (Audience) Claim

	   The "aud" (audience) claim identifies the recipients that the JWT is
	   intended for.  Each principal intended to process the JWT MUST
	   identify itself with a value in the audience claim.  If the principal
	   processing the claim does not identify itself with a value in the
	   "aud" claim when this claim is present, then the JWT MUST be
	   rejected.  In the general case, the "aud" value is an array of case-
	   sensitive strings, each containing a StringOrURI value.  In the
	   special case when the JWT has one audience, the "aud" value MAY be a
	   single case-sensitive string containing a StringOrURI value.  The
	   interpretation of audience values is generally application specific.
	   Use of this claim is OPTIONAL.*/
    ArrayList<String> audience = new ArrayList<String>();
    audience.add(AuthorizationManagerBeans.getHttpsAudience());
    audience.add(AuthorizationManagerBeans.getWssAudience());
    claimsSetBuilder.audience(audience);
    /* 4.1.4.  "exp" (Expiration Time) Claim

	   The "exp" (expiration time) claim identifies the expiration time on
	   or after which the JWT MUST NOT be accepted for processing.  The
	   processing of the "exp" claim requires that the current date/time
	   MUST be before the expiration date/time listed in the "exp" claim.
	   Implementers MAY provide for some small leeway, usually no more than
	   a few minutes, to account for clock skew.  Its value MUST be a number
	   containing a NumericDate value.  Use of this claim is OPTIONAL.*/
    claimsSetBuilder.expirationTime(new Date(timestamp + (AuthorizationManagerBeans.getTokenExpiringPeriod() * 1000)));
    /*4.1.5.  "nbf" (Not Before) Claim

	   The "nbf" (not before) claim identifies the time before which the JWT
	   MUST NOT be accepted for processing.  The processing of the "nbf"
	   claim requires that the current date/time MUST be after or equal to
	   the not-before date/time listed in the "nbf" claim.  Implementers MAY
	   provide for some small leeway, usually no more than a few minutes, to
	   account for clock skew.  Its value MUST be a number containing a
	   NumericDate value.  Use of this claim is OPTIONAL.*/
    claimsSetBuilder.notBeforeTime(new Date(timestamp - 1000));
    /* 4.1.6.  "iat" (Issued At) Claim

	   The "iat" (issued at) claim identifies the time at which the JWT was
	   issued.  This claim can be used to determine the age of the JWT.  Its
	   value MUST be a number containing a NumericDate value.  Use of this
	   claim is OPTIONAL.*/
    claimsSetBuilder.issueTime(new Date(timestamp));
    /*4.1.7.  "jti" (JWT ID) Claim

	   The "jti" (JWT ID) claim provides a unique identifier for the JWT.
	   The identifier value MUST be assigned in a manner that ensures that
	   there is a negligible probability that the same value will be
	   accidentally assigned to a different data object; if the application
	   uses multiple issuers, collisions MUST be prevented among values
	   produced by different issuers as well.  The "jti" claim can be used
	   to prevent the JWT from being replayed.  The "jti" value is a case-
	   sensitive string.  Use of this claim is OPTIONAL.*/
    claimsSetBuilder.jwtID(id + ":" + secret);
    JWTClaimsSet jwtClaims = claimsSetBuilder.build();
    // ******************************
    // Sign JWT with private RSA key
    // ******************************
    SignedJWT signedJWT;
    try {
        signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), JWTClaimsSet.parse(jwtClaims.toString()));
    } catch (ParseException e) {
        logger.error(e.getMessage());
        return new ErrorResponse(0, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Error on signing JWT (1)");
    }
    try {
        signedJWT.sign(signer);
    } catch (JOSEException e) {
        logger.error(e.getMessage());
        return new ErrorResponse(0, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Error on signing JWT (2)");
    }
    // Add the token to the released tokens
    clientClaims.put(id, jwtClaims);
    return new JWTResponse(signedJWT.serialize(), "bearer", AuthorizationManagerBeans.getTokenExpiringPeriod());
}
Also used : ArrayList(java.util.ArrayList) SignedJWT(com.nimbusds.jwt.SignedJWT) Date(java.util.Date) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParseException(java.text.ParseException) JOSEException(com.nimbusds.jose.JOSEException) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) JWSHeader(com.nimbusds.jose.JWSHeader) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse)

Example 3 with JWTClaimsSet

use of com.nimbusds.jwt.JWTClaimsSet in project cas by apereo.

the class JWTServiceTicketResourceEntityResponseFactoryTests method verifyServiceTicketAsJwt.

@Test
public void verifyServiceTicketAsJwt() throws Exception {
    final AuthenticationResult result = CoreAuthenticationTestUtils.getAuthenticationResult(authenticationSystemSupport, CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword("casuser"));
    final TicketGrantingTicket tgt = centralAuthenticationService.createTicketGrantingTicket(result);
    final Service service = RegisteredServiceTestUtils.getService("jwtservice");
    final ResponseEntity<String> response = serviceTicketResourceEntityResponseFactory.build(tgt.getId(), service, result);
    assertNotNull(response);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertFalse(response.getBody().startsWith(ServiceTicket.PREFIX));
    final Object jwt = this.tokenCipherExecutor.decode(response.getBody());
    final JWTClaimsSet claims = JWTClaimsSet.parse(jwt.toString());
    assertEquals(claims.getSubject(), tgt.getAuthentication().getPrincipal().getId());
}
Also used : TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) Service(org.apereo.cas.authentication.principal.Service) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Test(org.junit.Test)

Example 4 with JWTClaimsSet

use of com.nimbusds.jwt.JWTClaimsSet in project cas by apereo.

the class JWTTicketGrantingTicketResourceEntityResponseFactoryTests method verifyTicketGrantingTicketAsJwtWithHeader.

@Test
public void verifyTicketGrantingTicketAsJwtWithHeader() throws Exception {
    final AuthenticationResult result = CoreAuthenticationTestUtils.getAuthenticationResult(authenticationSystemSupport, CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword("casuser"));
    final TicketGrantingTicket tgt = centralAuthenticationService.createTicketGrantingTicket(result);
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(TokenConstants.PARAMETER_NAME_TOKEN, Boolean.TRUE.toString());
    final ResponseEntity<String> response = ticketGrantingTicketResourceEntityResponseFactory.build(tgt, request);
    assertNotNull(response);
    assertEquals(HttpStatus.CREATED, response.getStatusCode());
    final Object jwt = this.tokenCipherExecutor.decode(response.getBody());
    final JWTClaimsSet claims = JWTClaimsSet.parse(jwt.toString());
    assertEquals(claims.getSubject(), tgt.getAuthentication().getPrincipal().getId());
}
Also used : TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 5 with JWTClaimsSet

use of com.nimbusds.jwt.JWTClaimsSet in project topcom-cloud by 545314690.

the class TokenManager method createToken.

default String createToken(Object userId) {
    try {
        JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();
        builder.issuer(getIssuer());
        builder.subject(userId.toString());
        builder.issueTime(new Date());
        builder.notBeforeTime(new Date());
        builder.expirationTime(new Date(System.currentTimeMillis() + getExpirationDate()));
        builder.jwtID(UUID.randomUUID().toString());
        JWTClaimsSet claimsSet = builder.build();
        JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);
        Payload payload = new Payload(claimsSet.toJSONObject());
        JWSObject jwsObject = new JWSObject(header, payload);
        JWSSigner signer = new MACSigner(getSharedKey());
        jwsObject.sign(signer);
        return jwsObject.serialize();
    } catch (JOSEException ex) {
        return null;
    }
}
Also used : MACSigner(com.nimbusds.jose.crypto.MACSigner) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) Date(java.util.Date)

Aggregations

JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)69 SignedJWT (com.nimbusds.jwt.SignedJWT)44 JWSHeader (com.nimbusds.jose.JWSHeader)23 Date (java.util.Date)19 Test (org.junit.Test)16 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)14 Test (org.junit.jupiter.api.Test)11 JOSEException (com.nimbusds.jose.JOSEException)9 ParseException (java.text.ParseException)9 SecretKey (javax.crypto.SecretKey)8 JWSSigner (com.nimbusds.jose.JWSSigner)7 MacAlgorithm (org.springframework.security.oauth2.jose.jws.MacAlgorithm)7 Instant (java.time.Instant)6 ArrayList (java.util.ArrayList)6 Map (java.util.Map)6 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)6 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)5 MACSigner (com.nimbusds.jose.crypto.MACSigner)5 BadJOSEException (com.nimbusds.jose.proc.BadJOSEException)5 JWT (com.nimbusds.jwt.JWT)5