Package org.mitre.oauth2.repository.impl

Examples of org.mitre.oauth2.repository.impl.JpaOAuth2ClientRepository


      // now save it
      try {
        ClientDetailsEntity savedClient = clientService.saveNewClient(newClient);

        // generate the registration access token
        OAuth2AccessTokenEntity token = connectTokenService.createResourceAccessToken(savedClient);
        tokenService.saveAccessToken(token);

        // send it all out to the view

        RegisteredClient registered = new RegisteredClient(savedClient, token.getValue(), config.getIssuer() + "resource/" + UriUtils.encodePathSegment(savedClient.getClientId(), "UTF-8"));
        m.addAttribute("client", registered);
        m.addAttribute("code", HttpStatus.CREATED); // http 201

        return ClientInformationResponseView.VIEWNAME;
      } catch (UnsupportedEncodingException e) {
View Full Code Here




      try {
        // possibly update the token
        OAuth2AccessTokenEntity token = fetchValidRegistrationToken(auth, client);

        RegisteredClient registered = new RegisteredClient(client, token.getValue(), config.getIssuer() + "resource/" +  UriUtils.encodePathSegment(client.getClientId(), "UTF-8"));

        // send it all out to the view
        m.addAttribute("client", registered);
        m.addAttribute("code", HttpStatus.OK); // http 200
View Full Code Here

      try {
        // save the client
        ClientDetailsEntity savedClient = clientService.updateClient(oldClient, newClient);

        // possibly update the token
        OAuth2AccessTokenEntity token = fetchValidRegistrationToken(auth, savedClient);

        RegisteredClient registered = new RegisteredClient(savedClient, token.getValue(), config.getIssuer() + "resource/" + UriUtils.encodePathSegment(savedClient.getClientId(), "UTF-8"));

        // send it all out to the view
        m.addAttribute("client", registered);
        m.addAttribute("code", HttpStatus.OK); // http 200
View Full Code Here

  }
 
  private OAuth2AccessTokenEntity fetchValidRegistrationToken(OAuth2Authentication auth, ClientDetailsEntity client) {
   
    OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) auth.getDetails();
    OAuth2AccessTokenEntity token = tokenService.readAccessToken(details.getTokenValue());
   
    if (config.getRegTokenLifeTime() != null) {
   
      try {
        // Re-issue the token if it has been issued before [currentTime - validity]
        Date validToDate = new Date(System.currentTimeMillis() - config.getRegTokenLifeTime() * 1000);
        if(token.getJwt().getJWTClaimsSet().getIssueTime().before(validToDate)) {
          logger.info("Rotating the registration access token for " + client.getClientId());
          tokenService.revokeAccessToken(token);
          OAuth2AccessTokenEntity newToken = connectTokenService.createResourceAccessToken(client);
          tokenService.saveAccessToken(newToken);
          return newToken;
        } else {
          // it's not expired, keep going
          return token;
View Full Code Here

    if (client.getIdTokenSignedResponseAlg() != null) {
      signingAlg = client.getIdTokenSignedResponseAlg();
    }


    OAuth2AccessTokenEntity idTokenEntity = new OAuth2AccessTokenEntity();
    JWTClaimsSet idClaims = new JWTClaimsSet();

    // if the auth time claim was explicitly requested OR if the client always wants the auth time, put it in
    if (request.getExtensions().containsKey("max_age")
        || (request.getExtensions().containsKey("idtoken")) // TODO: parse the ID Token claims (#473) -- for now assume it could be in there
        || (client.getRequireAuthTime() != null && client.getRequireAuthTime())) {

      Date authTime = (Date) request.getExtensions().get(AuthenticationTimeStamper.AUTH_TIMESTAMP);
      if (authTime != null) {
        idClaims.setClaim("auth_time", authTime.getTime() / 1000);
      }
    }

    idClaims.setIssueTime(issueTime);

    if (client.getIdTokenValiditySeconds() != null) {
      Date expiration = new Date(System.currentTimeMillis() + (client.getIdTokenValiditySeconds() * 1000L));
      idClaims.setExpirationTime(expiration);
      idTokenEntity.setExpiration(expiration);
    }

    idClaims.setIssuer(configBean.getIssuer());
    idClaims.setSubject(sub);
    idClaims.setAudience(Lists.newArrayList(client.getClientId()));

    String nonce = (String)request.getExtensions().get("nonce");
    if (!Strings.isNullOrEmpty(nonce)) {
      idClaims.setCustomClaim("nonce", nonce);
    }

    Set<String> responseTypes = request.getResponseTypes();

    if (responseTypes.contains("token")) {
      // calculate the token hash
      Base64URL at_hash = IdTokenHashUtils.getAccessTokenHash(signingAlg, accessToken);
      idClaims.setClaim("at_hash", at_hash);
    }

    if (client.getIdTokenEncryptedResponseAlg() != null && !client.getIdTokenEncryptedResponseAlg().equals(Algorithm.NONE)
        && client.getIdTokenEncryptedResponseEnc() != null && !client.getIdTokenEncryptedResponseEnc().equals(Algorithm.NONE)
        && !Strings.isNullOrEmpty(client.getJwksUri())) {

      JwtEncryptionAndDecryptionService encrypter = encrypters.getEncrypter(client.getJwksUri());

      if (encrypter != null) {

        EncryptedJWT idToken = new EncryptedJWT(new JWEHeader(client.getIdTokenEncryptedResponseAlg(), client.getIdTokenEncryptedResponseEnc()), idClaims);

        encrypter.encryptJwt(idToken);

        idTokenEntity.setJwt(idToken);

      } else {
        logger.error("Couldn't find encrypter for client: " + client.getClientId());
      }

    } else {
     
      JWT idToken;
     
      if (signingAlg.equals(JWSAlgorithm.NONE)) {
        // unsigned ID token
        idToken = new PlainJWT(idClaims);

      } else {

        // signed ID token
        idToken = new SignedJWT(new JWSHeader(signingAlg), idClaims);
 
        if (signingAlg.equals(JWSAlgorithm.HS256)
            || signingAlg.equals(JWSAlgorithm.HS384)
            || signingAlg.equals(JWSAlgorithm.HS512)) {
          JwtSigningAndValidationService signer = symmetricCacheService.getSymmetricValidtor(client);
 
          // sign it with the client's secret
          signer.signJwt((SignedJWT) idToken);
        } else {
 
          // sign it with the server's key
          jwtService.signJwt((SignedJWT) idToken);
        }
      }
       

      idTokenEntity.setJwt(idToken);
    }

    idTokenEntity.setAuthenticationHolder(accessToken.getAuthenticationHolder());

    // create a scope set with just the special "id-token" scope
    //Set<String> idScopes = new HashSet<String>(token.getScope()); // this would copy the original token's scopes in, we don't really want that
    Set<String> idScopes = Sets.newHashSet(SystemScopeService.ID_TOKEN_SCOPE);
    idTokenEntity.setScope(idScopes);

    idTokenEntity.setClient(accessToken.getClient());

    return idTokenEntity;
  }
View Full Code Here

  }

  @Override
  public OAuth2AccessTokenEntity rotateRegistrationAccessTokenForClient(ClientDetailsEntity client) {
    // revoke any previous tokens
    OAuth2AccessTokenEntity oldToken = tokenService.getRegistrationAccessTokenForClient(client);
    if (oldToken != null) {
      Set<String> scope = oldToken.getScope();
      tokenService.revokeAccessToken(oldToken);
      return createAssociatedToken(client, scope);
    } else {
      return null;
    }
View Full Code Here

  }
 
  private OAuth2AccessTokenEntity createAssociatedToken(ClientDetailsEntity client, Set<String> scope) {
   
    // revoke any previous tokens that might exist, just to be sure
    OAuth2AccessTokenEntity oldToken = tokenService.getRegistrationAccessTokenForClient(client);
    if (oldToken != null) {
      tokenService.revokeAccessToken(oldToken);
    }
   
    // create a new token
   
    Map<String, String> authorizationParameters = Maps.newHashMap();
    OAuth2Request clientAuth = new OAuth2Request(authorizationParameters, client.getClientId(),
        Sets.newHashSet(new SimpleGrantedAuthority("ROLE_CLIENT")), true,
        scope, null, null, null, null);
    OAuth2Authentication authentication = new OAuth2Authentication(clientAuth, null);

    OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity();
    token.setClient(client);
    token.setScope(scope);

    AuthenticationHolderEntity authHolder = new AuthenticationHolderEntity();
    authHolder.setAuthentication(authentication);
    authHolder = authenticationHolderRepository.save(authHolder);
    token.setAuthenticationHolder(authHolder);

    JWTClaimsSet claims = new JWTClaimsSet();

    claims.setAudience(Lists.newArrayList(client.getClientId()));
    claims.setIssuer(configBean.getIssuer());
    claims.setIssueTime(new Date());
    claims.setExpirationTime(token.getExpiration());
    claims.setJWTID(UUID.randomUUID().toString()); // set a random NONCE in the middle of it

    JWSAlgorithm signingAlg = jwtService.getDefaultSigningAlgorithm();
    SignedJWT signed = new SignedJWT(new JWSHeader(signingAlg), claims);

    jwtService.signJwt(signed);

    token.setJwt(signed);

    return token;
  }
View Full Code Here

      Map<String,Boolean> entity = ImmutableMap.of("active", Boolean.FALSE);
      model.addAttribute("entity", entity);
      return JsonEntityView.VIEWNAME;
    }

        OAuth2AccessTokenEntity accessToken = null;
        OAuth2RefreshTokenEntity refreshToken = null;
    ClientDetailsEntity tokenClient;
    Set<String> scopes;
    UserInfo user;

    try {

      // check access tokens first (includes ID tokens)
      accessToken = tokenServices.readAccessToken(tokenValue);

      tokenClient = accessToken.getClient();
      scopes = accessToken.getScope();

            user = userInfoService.getByUsernameAndClientId(accessToken.getAuthenticationHolder().getAuthentication().getName(), tokenClient.getClientId());

    } catch (InvalidTokenException e) {
      logger.info("Verify failed; Invalid access token. Checking refresh token.");
      try {
View Full Code Here

  }

  @RequestMapping(value = "/access/{id}", method = RequestMethod.GET, produces = "application/json")
  public String getAccessTokenById(@PathVariable("id") Long id, ModelMap m, Principal p) {

    OAuth2AccessTokenEntity token = tokenService.getAccessTokenById(id);

    if (token == null) {
      logger.error("getToken failed; token not found: " + id);
      m.put("code", HttpStatus.NOT_FOUND);
      m.put("errorMessage", "The requested token with id " + id + " could not be found.");
      return JsonErrorView.VIEWNAME;
    } else if (!token.getAuthenticationHolder().getAuthentication().getName().equals(p.getName())) {
      logger.error("getToken failed; token does not belong to principal " + p.getName());
      m.put("code", HttpStatus.FORBIDDEN);
      m.put("errorMessage", "You do not have permission to view this token");
      return JsonErrorView.VIEWNAME;
    } else {
View Full Code Here

  }

  @RequestMapping(value = "/access/{id}", method = RequestMethod.DELETE, produces = "application/json")
  public String deleteAccessTokenById(@PathVariable("id") Long id, ModelMap m, Principal p) {

    OAuth2AccessTokenEntity token = tokenService.getAccessTokenById(id);

    if (token == null) {
      logger.error("getToken failed; token not found: " + id);
      m.put("code", HttpStatus.NOT_FOUND);
      m.put("errorMessage", "The requested token with id " + id + " could not be found.");
      return JsonErrorView.VIEWNAME;
    } else if (!token.getAuthenticationHolder().getAuthentication().getName().equals(p.getName())) {
      logger.error("getToken failed; token does not belong to principal " + p.getName());
      m.put("code", HttpStatus.FORBIDDEN);
      m.put("errorMessage", "You do not have permission to view this token");
      return JsonErrorView.VIEWNAME;
    } else {
View Full Code Here

TOP

Related Classes of org.mitre.oauth2.repository.impl.JpaOAuth2ClientRepository

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.