io.jsonwebtoken.impl.DefaultClaims Java Examples

The following examples show how to use io.jsonwebtoken.impl.DefaultClaims. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MachineLoginFilterTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testNotProceedRequestWhenNoWorkspaceIdClaim() throws Exception {
  final HttpServletRequest requestMock = getRequestMock();
  final KeyPairGenerator kpg = KeyPairGenerator.getInstance(SIGNATURE_ALGORITHM);
  kpg.initialize(KEY_SIZE);
  final KeyPair pair = kpg.generateKeyPair();
  final Claims badClaims = new DefaultClaims();
  badClaims.put(Constants.USER_ID_CLAIM, SUBJECT.getUserId());
  badClaims.put(Claims.ID, "84123-132-fn31");
  final String token =
      Jwts.builder()
          .setClaims(badClaims)
          .setHeader(HEADER)
          .signWith(RS512, pair.getPrivate())
          .compact();
  when(tokenExtractorMock.getToken(any(HttpServletRequest.class))).thenReturn(token);

  machineLoginFilter.doFilter(requestMock, responseMock, chainMock);

  verify(tokenExtractorMock, atLeastOnce()).getToken(any(HttpServletRequest.class));
  verify(responseMock)
      .sendError(
          401,
          "Machine token authentication failed: Unable to fetch signature key pair: no workspace id present in token");
}
 
Example #2
Source File: KeycloakEnvironmentInitializationFilterTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldThrowExceptionWhenNoEmailExistsAndUserDoesNotAlreadyExist() throws Exception {

  Map<String, Object> claimParams = new HashMap<>();
  claimParams.put("preferred_username", "username");
  Claims claims = new DefaultClaims(claimParams).setSubject("id2");
  DefaultJws<Claims> jws = new DefaultJws<>(new DefaultJwsHeader(), claims, "");
  // given
  when(tokenExtractor.getToken(any(HttpServletRequest.class))).thenReturn("token2");
  when(jwtParser.parseClaimsJws(anyString())).thenReturn(jws);
  when(userManager.getById(anyString())).thenThrow(NotFoundException.class);

  // when
  filter.doFilter(request, response, chain);

  verify(response)
      .sendError(
          eq(401),
          eq("Unable to authenticate user because email address is not set in keycloak profile"));
}
 
Example #3
Source File: KeycloakEnvironmentInitializationFilterTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldRetrieveTheEmailWhenItIsNotInJwtToken() throws Exception {

  Map<String, Object> claimParams = new HashMap<>();
  claimParams.put("preferred_username", "username");
  Claims claims = new DefaultClaims(claimParams).setSubject("id");
  DefaultJws<Claims> jws = new DefaultJws<>(new DefaultJwsHeader(), claims, "");
  UserImpl user = new UserImpl("id", "[email protected]", "username");
  keycloakSettingsMap.put(KeycloakConstants.USERNAME_CLAIM_SETTING, "preferred_username");
  // given
  when(tokenExtractor.getToken(any(HttpServletRequest.class))).thenReturn("token");
  when(jwtParser.parseClaimsJws(anyString())).thenReturn(jws);
  when(userManager.getById(anyString())).thenThrow(NotFoundException.class);
  when(userManager.getOrCreateUser(anyString(), anyString(), anyString())).thenReturn(user);
  keycloakAttributes.put("email", "[email protected]");

  try {
    // when
    filter.doFilter(request, response, chain);
  } catch (Exception e) {
    e.printStackTrace();
    throw e;
  }

  verify(userManager).getOrCreateUser("id", "[email protected]", "username");
}
 
Example #4
Source File: LoginContext.java    From Aooms with Apache License 2.0 5 votes vote down vote up
public AuthenticationInfo login(String username, String password){
    AuthenticationInfo authenticationInfo = loginService.login(username,password);

    //boolean success = true;
    if(authenticationInfo == null){
        // 返回一个Ghost用户
        //authenticationInfo = new AuthenticationInfo().ghost();
        //success = false;
        return null;
    }


    JwtBuilder jwtBuilder = Jwts.builder();
    jwtBuilder.setClaims(new DefaultClaims());
    jwtBuilder.claim(SSOAuthentication.CACHE_GROUP_PLACEHOLDER, cacheGroup);
    jwtBuilder.claim(SSOAuthentication.CACHE_TIMEOUT_PLACEHOLDER, timeout);
    SSOToken token = SSOToken.create(jwtBuilder)
            .setId(authenticationInfo.getSessionId())
            .setIssuer(Aooms.NAME)
            .setOrigin(TokenOrigin.HTML5)
            .setTime(System.currentTimeMillis());
    authenticationInfo.setToken(token.getToken());

    // 缓存
    cache(authenticationInfo);
    return authenticationInfo;
}
 
Example #5
Source File: SimpleJwtTokenService.java    From onetwo with Apache License 2.0 5 votes vote down vote up
final protected Claims createClaimsFromToken(String token) {
	try {
		DefaultClaims claims = (DefaultClaims)Jwts.parser()
									.setSigningKey(jwtConfig.getSigningKey())
									.parse(token)
									.getBody();
		return claims;
	} catch (Exception e) {
		throw new ServiceException(JwtErrors.CM_ERROR_TOKEN, e).put("token", token);
	}
}
 
Example #6
Source File: KeycloakSigningKeyResolverTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test(expectedExceptions = MachineTokenJwtException.class)
public void shouldThrowMachineTokenExceptionOnMachineTokensWithClaims() {
  final Map<String, Object> param = new HashMap<>();
  param.put("kind", MACHINE_TOKEN_KIND);
  DefaultJwsHeader header = new DefaultJwsHeader(param);

  signingKeyResolver.resolveSigningKey(header, new DefaultClaims());
  verifyNoMoreInteractions(jwkProvider);
}
 
Example #7
Source File: KeycloakEnvironmentInitializationFilterTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private DefaultJws<Claims> createJws() {
  Map<String, Object> claimParams = new HashMap<>();
  claimParams.put("email", "[email protected]");
  claimParams.put("preferred_username", "username");
  Claims claims = new DefaultClaims(claimParams).setSubject("id2");
  return new DefaultJws<>(new DefaultJwsHeader(), claims, "");
}
 
Example #8
Source File: KeyStoreJwkKeyResolverTest.java    From athenz with Apache License 2.0 4 votes vote down vote up
@Test
public void testResolveSigningKey() throws Exception {
    // mocks
    KeyStore keyStoreMock = Mockito.spy(baseKeyStore);
    SigningKeyResolver jwksResolverMock = Mockito.spy(basejwksResolver);

    // instance
    KeyStoreJwkKeyResolver resolver = new KeyStoreJwkKeyResolver(null, "file:///", null);
    Field keyStoreField = resolver.getClass().getDeclaredField("keyStore");
    keyStoreField.setAccessible(true);
    Field providerField = resolver.getClass().getDeclaredField("jwksResolver");
    providerField.setAccessible(true);
    providerField.set(resolver, jwksResolverMock);

    // args
    DefaultJwsHeader jwsHeader = new DefaultJwsHeader();
    DefaultClaims claims = new DefaultClaims();

    // 1. null key store, find in JWKS
    PublicKey pk11 = Mockito.spy(basePublicKey);
    Mockito.when(jwksResolverMock.resolveSigningKey(jwsHeader, claims)).thenReturn(pk11);
    jwsHeader.setKeyId("11");
    claims.setIssuer(null);
    assertSame(resolver.resolveSigningKey(jwsHeader, claims), pk11);

    // set key store mock
    keyStoreField.set(resolver, keyStoreMock);

    // 2. invalid issuer, find in JWKS
    PublicKey pk21 = Mockito.spy(basePublicKey);
    Mockito.when(jwksResolverMock.resolveSigningKey(jwsHeader, claims)).thenReturn(pk21);
    jwsHeader.setKeyId("21");
    claims.setIssuer(null);
    assertSame(resolver.resolveSigningKey(jwsHeader, claims), pk21);
    PublicKey pk22 = Mockito.spy(basePublicKey);
    Mockito.when(jwksResolverMock.resolveSigningKey(jwsHeader, claims)).thenReturn(pk22);
    jwsHeader.setKeyId("22");
    claims.setIssuer("");
    assertSame(resolver.resolveSigningKey(jwsHeader, claims), pk22);
    PublicKey pk23 = Mockito.spy(basePublicKey);
    Mockito.when(jwksResolverMock.resolveSigningKey(jwsHeader, claims)).thenReturn(pk23);
    jwsHeader.setKeyId("23");
    claims.setIssuer("domain23-----service23");
    assertSame(resolver.resolveSigningKey(jwsHeader, claims), pk23);
    // 2. invalid domain, find in JWKS
    PublicKey pk24 = Mockito.spy(basePublicKey);
    Mockito.when(jwksResolverMock.resolveSigningKey(jwsHeader, claims)).thenReturn(pk24);
    jwsHeader.setKeyId("24");
    claims.setIssuer("domain24.service24");
    assertSame(resolver.resolveSigningKey(jwsHeader, claims), pk24);

    // 3. found in key store, skip JWKS
    PublicKey pk31 = null;

    try (PemReader reader = new PemReader(new FileReader(this.classLoader.getResource("jwt_public.key").getFile()))) {
        pk31 = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(reader.readPemObject().getContent()));
    }
    Mockito.when(jwksResolverMock.resolveSigningKey(jwsHeader, claims)).thenReturn(pk31);
    Mockito.when(keyStoreMock.getPublicKey("sys.auth", "service31", "31")).thenReturn("-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAy3c3TEePZZPaxqNU2xV4\nortsXrw1EXTNQj2QUgL8UOPaQS0lbHJtD1cbcCFnzfXRXTOGqh8l+XWTRIOlt4yU\n+mEhgR0/JKILTPwmS0fj3D1PT6IjZShuNyd4USVdcjfCRBRb9ExIptJyeTTUu0Uu\njWNEcGOWAkUZcsonmiEz7bIMVkGy5uYnWGbsKP51Zf/PFMb96RcHeE0ZUitIB4YK\n1bgHLyAEBJIka5mRC/jWq/mlq3jiP5RaVWbzQiJbrjuYWd1Vps/xnrABx6/4Ft/M\n0AnSQN0SYjc/nWT1yGPpCwtWmWUU5NNHd+w6TdgOjdu00wownwblovtEYED+rncb\n913qfBM98kNHyj357BSzlvhiwEH5Ayo9DTnx1j9HuJGZXzymVypuQXLu/tkHMEt+\nc4kytKJNi6MLiauy9xtXGLXgOvZUM8V0Z27Z6CTfCzWZ0nwnEWDdH+NJyusL6pJg\nEGUBh6E9fdJInV7YOCF+P9/19imPHrZ0blTXK1TDfKS/pCLOXO/OmmH+p+UxQ77O\npeP5wlt5Jem0ErSisl/Qxhh1OtJcLwFdA7uC7rOTMrSEGLO++5+CatsXj7BEK2l+\n3As8fJEkoWXd1+4KOUMfV/fnT/z6U8+bcsYn0nvWPl8XuMbwNWjqHYgqhl1RLA7M\n17HCydWCF50HI2XojtGgRN0CAwEAAQ==\n-----END PUBLIC KEY-----\n");
    jwsHeader.setKeyId("31");
    claims.setIssuer("sys.auth.service31");
    assertEquals(resolver.resolveSigningKey(jwsHeader, claims), pk31);
    // 3. NOT found in key store, find in JWKS
    PublicKey pk32 = Mockito.spy(basePublicKey);
    Mockito.when(jwksResolverMock.resolveSigningKey(jwsHeader, claims)).thenReturn(pk32);
    Mockito.when(keyStoreMock.getPublicKey("sys.auth", "service32", "32")).thenReturn(null);
    jwsHeader.setKeyId("32");
    claims.setIssuer("sys.auth.service32");
    assertSame(resolver.resolveSigningKey(jwsHeader, claims), pk32);
    // 3. found in key store but public key invalid, find in JWKS
    PublicKey pk33 = Mockito.spy(basePublicKey);
    Mockito.when(jwksResolverMock.resolveSigningKey(jwsHeader, claims)).thenReturn(pk33);
    Mockito.when(keyStoreMock.getPublicKey("sys.auth", "service33", "33")).thenReturn("");
    jwsHeader.setKeyId("33");
    claims.setIssuer("sys.auth.service33");
    assertSame(resolver.resolveSigningKey(jwsHeader, claims), pk33);
    PublicKey pk34 = Mockito.spy(basePublicKey);
    Mockito.when(jwksResolverMock.resolveSigningKey(jwsHeader, claims)).thenReturn(pk34);
    Mockito.when(keyStoreMock.getPublicKey("sys.auth", "service34", "34")).thenReturn("-----BEGIN PUBLIC KEY-----\ninvalid\n-----END PUBLIC KEY-----\n");
    jwsHeader.setKeyId("34");
    claims.setIssuer("sys.auth.service34");
    assertSame(resolver.resolveSigningKey(jwsHeader, claims), pk34);

    // 4. both NOT found
    jwsHeader.setKeyId("41");
    claims.setIssuer("sys.auth.service41");
    Mockito.when(jwksResolverMock.resolveSigningKey(jwsHeader, claims)).thenReturn(null);
    Mockito.when(keyStoreMock.getPublicKey("sys.auth", "service41", "41")).thenReturn(null);
    assertNull(resolver.resolveSigningKey(jwsHeader, claims));

    // 5. skip, empty key ID
    jwsHeader.setKeyId(null);
    claims.setIssuer(null);
    assertNull(resolver.resolveSigningKey(jwsHeader, claims));
    jwsHeader.setKeyId("");
    claims.setIssuer(null);
    assertNull(resolver.resolveSigningKey(jwsHeader, claims));
}
 
Example #9
Source File: RNPureJwtModule.java    From react-native-pure-jwt with MIT License 3 votes vote down vote up
private void getResponse(Jwt parsed, Promise callback) {
    ObjectMapper mapper = new ObjectMapper();

    Map<String, Object> headersMap = mapper.convertValue(parsed.getHeader(), DefaultClaims.class);
    Map<String, Object> payload = mapper.convertValue(parsed.getBody(), DefaultClaims.class);

    WritableMap response = Arguments.createMap();

    response.putMap("headers", Arguments.makeNativeMap(headersMap));
    response.putMap("payload", Arguments.makeNativeMap(payload));

    callback.resolve(response);
}
 
Example #10
Source File: Jwts.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Returns a new {@link Claims} instance to be used as a JWT body.
 *
 * @return a new {@link Claims} instance to be used as a JWT body.
 */
public static Claims claims() {
    return new DefaultClaims();
}