当前位置: 首页>>代码示例>>Java>>正文


Java Jwt类代码示例

本文整理汇总了Java中org.springframework.security.jwt.Jwt的典型用法代码示例。如果您正苦于以下问题:Java Jwt类的具体用法?Java Jwt怎么用?Java Jwt使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Jwt类属于org.springframework.security.jwt包,在下文中一共展示了Jwt类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getJwtTokenByClientCredentialForUser

import org.springframework.security.jwt.Jwt; //导入依赖的package包/类
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void getJwtTokenByClientCredentialForUser() throws JsonParseException, JsonMappingException, IOException {
    ResponseEntity<String> response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=user&password=password", null, String.class);
    String responseText = response.getBody();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);

    assertEquals("bearer", jwtMap.get("token_type"));
    assertEquals("read write", jwtMap.get("scope"));
    assertTrue(jwtMap.containsKey("access_token"));
    assertTrue(jwtMap.containsKey("expires_in"));
    assertTrue(jwtMap.containsKey("jti"));
    String accessToken = (String) jwtMap.get("access_token");

    Jwt jwtToken = JwtHelper.decode(accessToken);
    String claims = jwtToken.getClaims();
    HashMap claimsMap = new ObjectMapper().readValue(claims, HashMap.class);
    assertEquals("spring-boot-application", ((List<String>) claimsMap.get("aud")).get(0));
    assertEquals("trusted-app", claimsMap.get("client_id"));
    assertEquals("user", claimsMap.get("user_name"));
    assertEquals("read", ((List<String>) claimsMap.get("scope")).get(0));
    assertEquals("write", ((List<String>) claimsMap.get("scope")).get(1));
    assertEquals("ROLE_USER", ((List<String>) claimsMap.get("authorities")).get(0));
}
 
开发者ID:leftso,项目名称:demo-spring-boot-security-oauth2,代码行数:26,代码来源:GrantByResourceOwnerPasswordCredentialTest.java

示例2: getJwtTokenByClientCredentialForAdmin

import org.springframework.security.jwt.Jwt; //导入依赖的package包/类
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void getJwtTokenByClientCredentialForAdmin() throws JsonParseException, JsonMappingException, IOException {
    ResponseEntity<String> response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=admin&password=password", null, String.class);
    String responseText = response.getBody();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);

    assertEquals("bearer", jwtMap.get("token_type"));
    assertEquals("read write", jwtMap.get("scope"));
    assertTrue(jwtMap.containsKey("access_token"));
    assertTrue(jwtMap.containsKey("expires_in"));
    assertTrue(jwtMap.containsKey("jti"));
    String accessToken = (String) jwtMap.get("access_token");

    Jwt jwtToken = JwtHelper.decode(accessToken);
    String claims = jwtToken.getClaims();
    HashMap claimsMap = new ObjectMapper().readValue(claims, HashMap.class);
    assertEquals("spring-boot-application", ((List<String>) claimsMap.get("aud")).get(0));
    assertEquals("trusted-app", claimsMap.get("client_id"));
    assertEquals("admin", claimsMap.get("user_name"));
    assertEquals("read", ((List<String>) claimsMap.get("scope")).get(0));
    assertEquals("write", ((List<String>) claimsMap.get("scope")).get(1));
    assertEquals("ROLE_ADMIN", ((List<String>) claimsMap.get("authorities")).get(0));
}
 
开发者ID:leftso,项目名称:demo-spring-boot-security-oauth2,代码行数:26,代码来源:GrantByResourceOwnerPasswordCredentialTest.java

示例3: verifiedToken

import org.springframework.security.jwt.Jwt; //导入依赖的package包/类
@NotNull
public static Map<String, Object> verifiedToken(String token, String publicKey) {
    Jwt jwt = JwtHelper.decode(token);

    // Currently not sure how we should handle this because we have multiple
    // CF instances. We would need to have a central file for all UAA
    // instances
    // verifySignature(jwt, publicKey);

    Map<String, Object> tokenObj = tryExtractToken(jwt);
    if (tokenObj == null) {
        throw new AuthenticationServiceException("Error parsing JWT token/extracting claims");
    }

    verifyExpiration(tokenObj);
    return tokenObj;
}
 
开发者ID:evoila,项目名称:cfsummiteu2017,代码行数:18,代码来源:UaaFilterUtils.java

示例4: checkJwtClaims

import org.springframework.security.jwt.Jwt; //导入依赖的package包/类
protected JsonNode checkJwtClaims(ResponseEntity<String> responseEntity, String expectedAuthority) throws IOException {
    String responseBody = responseEntity.getBody();

    assertThat(HttpStatus.OK, is(responseEntity.getStatusCode()));

    JsonNode responseBodyJsonNode = new ObjectMapper().readTree(responseBody);
    assertThat(responseBodyJsonNode.has("access_token"), is(true));

    String accessToken = responseBodyJsonNode.get("access_token").asText();
    Jwt jwt = JwtHelper.decode(accessToken);
    String jwtClaims = jwt.getClaims();
    JsonNode jwtClaimsJsonNode = new ObjectMapper().readTree(jwtClaims);
    assertThat(jwtClaimsJsonNode.get("aud").get(0).asText(), is("sw360-REST-API"));
    assertThat(jwtClaimsJsonNode.get("client_id").asText(), is("trusted-sw360-client"));

    JsonNode scopeNode = jwtClaimsJsonNode.get("scope");
    assertThat(scopeNode.get(0).asText(), is("sw360.read"));
    assertThat(scopeNode.get(1).asText(), is("sw360.write"));

    JsonNode authoritiesJsonNode = jwtClaimsJsonNode.get("authorities");
    assertThat(authoritiesJsonNode.get(0).asText(), is(expectedAuthority));
    assertThat(authoritiesJsonNode.size(), is(1));

    return jwtClaimsJsonNode;
}
 
开发者ID:sw360,项目名称:sw360rest,代码行数:26,代码来源:IntegrationTestBase.java

示例5: decode

import org.springframework.security.jwt.Jwt; //导入依赖的package包/类
protected Map<String, Object> decode(String token) {
	Jwt jwt = JwtHelper.decodeAndVerify(token, verifier);
	String content = jwt.getClaims();
	try {
		@SuppressWarnings("unchecked")
		Map<String, Object> map = objectMapper.readValue(content, Map.class);
		return map;
	}
	catch (Exception e) {
		throw new InvalidTokenException("Cannot convert access token to JSON", e);
	}
}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:13,代码来源:JwtTokenEnhancer.java

示例6: createFrom

import org.springframework.security.jwt.Jwt; //导入依赖的package包/类
public static Claims createFrom(ObjectMapper jsonMapper, OAuth2AccessToken accessToken) {
    try {
        String idToken = accessToken.getAdditionalInformation().get("id_token").toString();
        Jwt decodedToken = JwtHelper.decode(idToken);
        return jsonMapper.readValue(decodedToken.getClaims(), Claims.class);

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
开发者ID:PacktPublishing,项目名称:OAuth-2.0-Cookbook,代码行数:11,代码来源:Claims.java

示例7: getJwtTokenByTrustedClient

import org.springframework.security.jwt.Jwt; //导入依赖的package包/类
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void getJwtTokenByTrustedClient() throws JsonParseException, JsonMappingException, IOException {
    ResponseEntity<String> response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?client_id=trusted-app&grant_type=client_credentials", null, String.class);
    String responseText = response.getBody();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);

    assertEquals("bearer", jwtMap.get("token_type"));
    assertEquals("read write", jwtMap.get("scope"));
    assertTrue(jwtMap.containsKey("access_token"));
    assertTrue(jwtMap.containsKey("expires_in"));
    assertTrue(jwtMap.containsKey("jti"));
    String accessToken = (String) jwtMap.get("access_token");

    Jwt jwtToken = JwtHelper.decode(accessToken);

    String claims = jwtToken.getClaims();
    logJson(claims);

    HashMap claimsMap = new ObjectMapper().readValue(claims, HashMap.class);
    assertEquals("spring-boot-application", ((List<String>) claimsMap.get("aud")).get(0));
    assertEquals("trusted-app", claimsMap.get("client_id"));
    assertEquals("read", ((List<String>) claimsMap.get("scope")).get(0));
    assertEquals("write", ((List<String>) claimsMap.get("scope")).get(1));
    List<String> authorities = (List<String>) claimsMap.get("authorities");
    assertEquals(1, authorities.size());
    assertEquals("ROLE_TRUSTED_CLIENT", authorities.get(0));
}
 
开发者ID:leftso,项目名称:demo-spring-boot-security-oauth2,代码行数:30,代码来源:GrantByClientCredentialTest.java

示例8: verifySignature

import org.springframework.security.jwt.Jwt; //导入依赖的package包/类
private static void verifySignature(Jwt jwt, String publicKey) {
    try {
        RsaVerifier rsaVerifier = new RsaVerifier(publicKey);
        jwt.verifySignature(rsaVerifier);
    } catch (Exception ex) {
        throw new AuthenticationServiceException("Error verifying signature of token");
    }
}
 
开发者ID:evoila,项目名称:cfsummiteu2017,代码行数:9,代码来源:UaaFilterUtils.java

示例9: tryExtractToken

import org.springframework.security.jwt.Jwt; //导入依赖的package包/类
public static Map<String, Object> tryExtractToken(Jwt jwt) {
    if (jwt.getClaims() == null)
        return null;

    try {
        return objectMapper.readValue(jwt.getClaims(), new TypeReference<HashMap<String, Object>>() {});
    } catch (IOException e) {
        log.error("Error parsing claims from JWT", e);
    }

    return null;
}
 
开发者ID:evoila,项目名称:cfsummiteu2017,代码行数:13,代码来源:UaaFilterUtils.java

示例10: getAccessTokenMap

import org.springframework.security.jwt.Jwt; //导入依赖的package包/类
private Map<String, Object> getAccessTokenMap() {
    final Map<String, Object> accessTokenMap;
    final OAuth2AccessToken accessToken = oauth2ClientContext.getAccessToken();
    final Jwt decode = JwtHelper.decode(accessToken.getValue());
    accessTokenMap = jsonParser.parseMap(decode.getClaims());
    return accessTokenMap;
}
 
开发者ID:eclipse,项目名称:hawkbit-extensions,代码行数:8,代码来源:UserPrincipalInfoTokenServices.java

示例11: decode

import org.springframework.security.jwt.Jwt; //导入依赖的package包/类
public UserJwtToken decode(String token) {
    try {
        Jwt jwt = JwtHelper.decodeAndVerify(token, verifier);
        String content = jwt.getClaims();
        return objectMapper.readValue(content, UserJwtToken.class);
    }
    catch (Exception e) {
        throw new IllegalArgumentException("Cannot decode access token from JSON", e);
    }
}
 
开发者ID:leon,项目名称:spring-oauth-social-microservice-starter,代码行数:11,代码来源:JwtService.java

示例12: extractTokenInformation

import org.springframework.security.jwt.Jwt; //导入依赖的package包/类
private Map<String, Object> extractTokenInformation(String token) {
  try {
    final Jwt jwt = JwtHelper.decode(token);

    final Map<String, Object> map = objectMapper.parseMap(jwt.getClaims());
    if (map.containsKey(EXP) && map.get(EXP) instanceof Integer) {
      Integer intValue = (Integer) map.get(EXP);
      map.put(EXP, Long.valueOf(intValue));
    }

    return map;
  } catch (RuntimeException mie) {
    return null;
  }
}
 
开发者ID:cloudfoundry-incubator,项目名称:credhub,代码行数:16,代码来源:AuditOAuth2AuthenticationExceptionHandler.java

示例13: authenticate

import org.springframework.security.jwt.Jwt; //导入依赖的package包/类
@Override
public Authentication authenticate(final Authentication authRequest) throws AuthenticationException {

    // Getting string token from authentication request object
    String token = Preconditions.notNull(StringUtils.trimToNull((String) authRequest.getCredentials()), ExceptionCode.AUTHENTICATION, "No jwt token present.");

    // Getting JWT object from string token
    Jwt jwt = JwtHelper.decode(token);

    // Getting payload of token
    String claims = jwt.getClaims();
    TokenPayload tokenPayload = this.gson.fromJson(claims, TokenPayload.class);

    // Checking if token already expired and throwing an AuthenticationException in this case
    checkIsExpired(tokenPayload.expirationTime);

    // Getting user id from token

    Long userId = Preconditions.notNull(tokenPayload.userId, ExceptionCode.AUTHENTICATION, "Token doesn't contains user id.");

    // Getting user from database
    HeapUser user = this.heapUserRepository.findOne(userId);

    // Validate token signature (to be sure that token doesn't change on client side)
    try {
        jwt.verifySignature(new MacSigner(user.getSecret()));
    } catch (Exception cause) {
        HeapException.throwNew(ExceptionCode.AUTHENTICATION, "Token verification failed.", cause);
    }

    // Return authenticated Authentication
    HeapUserDetails userDetails = new HeapUserDetails(user);
    userDetails.eraseCredentials();
    return new JwtAuthenticationToken(userDetails);
}
 
开发者ID:Heapy,项目名称:Heap,代码行数:36,代码来源:JwtAuthenticationProvider.java

示例14: loadAuthentication

import org.springframework.security.jwt.Jwt; //导入依赖的package包/类
@Override
@Cacheable(cacheNames = "tokenCache", key = "#accessToken")
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException {
    if (StringUtils.isBlank(jwtSignKey)) {
        return getOAuth2Authentication(accessToken);
    }
    Jwt jwtToken = JwtHelper.decode(accessToken);
    try {
        Map<String, Object> claims = objectMapper.readValue(jwtToken.getClaims(), new MapTypeReference());
        return claims.get("user") == null ? getOAuth2Authentication(accessToken) : getSSOAuthentication(accessToken);
    } catch (IOException e) {
        LOGGER.error("Token does not claim anything", e);
        throw new InvalidTokenException("Invalid JWT token, does not claim anything", e);
    }
}
 
开发者ID:hortonworks,项目名称:cloudbreak,代码行数:16,代码来源:CachedRemoteTokenService.java

示例15: getSSOAuthentication

import org.springframework.security.jwt.Jwt; //导入依赖的package包/类
private OAuth2Authentication getSSOAuthentication(String accessToken) {
    try {
        SignatureVerifier verifier = isAssymetricKey(jwtSignKey) ? new RsaVerifier(jwtSignKey) : new MacSigner(jwtSignKey);
        Jwt jwt = JwtHelper.decodeAndVerify(accessToken, verifier);
        Map<String, Object> claims = objectMapper.readValue(jwt.getClaims(), new MapTypeReference());
        Object userClaim = claims.get("user");
        Map<String, Object> tokenMap = new HashMap<>();
        Map<String, Object> userMap = objectMapper.readValue(userClaim.toString(), new MapTypeReference());
        String exp = claims.get("exp").toString();
        tokenMap.put("exp", Long.valueOf(exp));
        Object email = userMap.get("email");
        tokenMap.put("user_id", email);
        tokenMap.put("user_name", email);
        tokenMap.put("scope", Arrays.asList("cloudbreak.networks.read", "periscope.cluster", "cloudbreak.usages.user", "cloudbreak.recipes", "openid",
            "cloudbreak.templates.read", "cloudbreak.usages.account", "cloudbreak.events", "cloudbreak.stacks.read",
            "cloudbreak.blueprints", "cloudbreak.networks", "cloudbreak.templates", "cloudbreak.credentials.read",
            "cloudbreak.securitygroups.read", "cloudbreak.securitygroups", "cloudbreak.stacks", "cloudbreak.credentials",
            "cloudbreak.recipes.read", "cloudbreak.blueprints.read"));

        OAuth2AccessToken oAuth2AccessToken = jwtAccessTokenConverter.extractAccessToken(accessToken, tokenMap);
        if (oAuth2AccessToken.isExpired()) {
            throw new InvalidTokenException("The token has expired");
        }
        OAuth2Authentication oAuth2Authentication = jwtAccessTokenConverter.extractAuthentication(tokenMap);
        if (oAuth2Authentication != null) {
            LOGGER.info("JWT token verified for: {}", oAuth2Authentication.getPrincipal());
        }
        return oAuth2Authentication;
    } catch (IOException e) {
        LOGGER.error("Failed to parse the JWT token", e);
        throw new InvalidTokenException("The specified JWT token is invalid", e);
    }
}
 
开发者ID:hortonworks,项目名称:cloudbreak,代码行数:34,代码来源:CachedRemoteTokenService.java


注:本文中的org.springframework.security.jwt.Jwt类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。