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


Java JwtHelper类代码示例

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


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

示例1: getJwtTokenByClientCredentialForUser

import org.springframework.security.jwt.JwtHelper; //导入依赖的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.JwtHelper; //导入依赖的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.JwtHelper; //导入依赖的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.JwtHelper; //导入依赖的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: authenticate

import org.springframework.security.jwt.JwtHelper; //导入依赖的package包/类
@Override
public Authentication authenticate(Authentication t)
        throws AuthenticationException {
    JWTToken jwtToken = (JWTToken) t;
    try {
    	String username = jwtToken.getClaims().getUsername();
    	String secret = usernameAuthBean.getUserSecret().get(username);
    	if (secret != null) {
    		MacSigner signer = new MacSigner(secret);
    		JwtHelper.decodeAndVerify(jwtToken.getToken(), signer);
    		jwtToken.setAuthenticated(Boolean.TRUE);
    		String role = usernameAuthBean.getUserRoles().get(username);
    		jwtToken.addRole(role);
    		
    	}
        
    } catch (InvalidSignatureException e) {
        return null;
    }
    return jwtToken;
}
 
开发者ID:fergarrui,项目名称:jwt-example,代码行数:22,代码来源:JwtAuthenticationProvider.java

示例6: decode

import org.springframework.security.jwt.JwtHelper; //导入依赖的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

示例7: rsaKeyCreatesValidRsaSignedTokens

import org.springframework.security.jwt.JwtHelper; //导入依赖的package包/类
@Test
public void rsaKeyCreatesValidRsaSignedTokens() throws Exception {
	String rsaKey = "-----BEGIN RSA PRIVATE KEY-----  \n"
			+ "MIIBywIBAAJhAOTeb4AZ+NwOtPh+ynIgGqa6UWNVe6JyJi+loPmPZdpHtzoqubnC \n"
			+ "wEs6JSiSZ3rButEAw8ymgLV6iBY02hdjsl3h5Z0NWaxx8dzMZfXe4EpfB04ISoqq\n"
			+ "hZCxchvuSDP4eQIDAQABAmEAqUuYsuuDWFRQrZgsbGsvC7G6zn3HLIy/jnM4NiJK\n"
			+ "t0JhWNeN9skGsR7bqb1Sak2uWqW8ZqnqgAC32gxFRYHTavJEk6LTaHWovwDEhPqc\n"
			+ "Zs+vXd6tZojJQ35chR/slUEBAjEA/sAd1oFLWb6PHkaz7r2NllwUBTvXL4VcMWTS\n"
			+ "pN+5cU41i9fsZcHw6yZEl+ZCicDxAjEA5f3R+Bj42htNI7eylebew1+sUnFv1xT8\n"
			+ "jlzxSzwVkoZo+vef7OD6OcFLeInAHzAJAjEAs6izolK+3ETa1CRSwz0lPHQlnmdM\n"
			+ "Y/QuR5tuPt6U/saEVuJpkn4LNRtg5qt6I4JRAjAgFRYTG7irBB/wmZFp47izXEc3\n"
			+ "gOdvA1hvq3tlWU5REDrYt24xpviA0fvrJpwMPbECMAKDKdiDi6Q4/iBkkzNMefA8\n"
			+ "7HX27b9LR33don/1u/yvzMUo+lrRdKAFJ+9GPE9XFA== \n" + "-----END RSA PRIVATE KEY----- ";
	tokenEnhancer.setSigningKey(rsaKey);
	OAuth2Authentication authentication = new OAuth2Authentication(createOAuth2Request("foo", null),
			userAuthentication);
	OAuth2AccessToken token = tokenEnhancer.enhance(new DefaultOAuth2AccessToken("FOO"), authentication);
	JwtHelper.decodeAndVerify(token.getValue(), new RsaVerifier(rsaKey));
}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:20,代码来源:JwtTokenEnhancerTests.java

示例8: createFrom

import org.springframework.security.jwt.JwtHelper; //导入依赖的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

示例9: getJwtTokenByTrustedClient

import org.springframework.security.jwt.JwtHelper; //导入依赖的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

示例10: extractJtiFromRefreshToken

import org.springframework.security.jwt.JwtHelper; //导入依赖的package包/类
private JWTCommon extractJtiFromRefreshToken(String original) {
  JWTCommon result = null;
  try {
    result = Serializer.createFromJson(JWTCommon.class, JwtHelper.decode(original).getClaims());
    while (result.getJti().length() > 36) {
      result = extractJtiFromRefreshToken(result.getJti());
    }
  } catch (Exception e) {
    result = new JWTCommon();
    result.setJti(original);
  }
  return result;

}
 
开发者ID:nandhusriram,项目名称:jwt_token_mongo_store,代码行数:15,代码来源:JWTMongoTokenStore.java

示例11: getAccessTokenMap

import org.springframework.security.jwt.JwtHelper; //导入依赖的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

示例12: decode

import org.springframework.security.jwt.JwtHelper; //导入依赖的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

示例13: extractTokenInformation

import org.springframework.security.jwt.JwtHelper; //导入依赖的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

示例14: JWTToken

import org.springframework.security.jwt.JwtHelper; //导入依赖的package包/类
public JWTToken(String token) throws IOException {
    authorities = new ArrayList<>();
    this.token = token;
    this.jwt = JwtHelper.decode(token);
    ObjectMapper mapper = new ObjectMapper();
    this.claims = mapper.readValue(jwt.getClaims(), JwtPayload.class);
}
 
开发者ID:fergarrui,项目名称:jwt-example,代码行数:8,代码来源:JWTToken.java

示例15: authenticate

import org.springframework.security.jwt.JwtHelper; //导入依赖的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


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