本文整理汇总了Java中io.jsonwebtoken.Jws类的典型用法代码示例。如果您正苦于以下问题:Java Jws类的具体用法?Java Jws怎么用?Java Jws使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Jws类属于io.jsonwebtoken包,在下文中一共展示了Jws类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: authenticate
import io.jsonwebtoken.Jws; //导入依赖的package包/类
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
RawAccessJwtToken rawAccessToken = (RawAccessJwtToken) authentication.getCredentials();
Jws<Claims> jwsClaims = rawAccessToken.parseClaims(jwtSettings.getTokenSigningKey());
String orgId = jwsClaims.getBody().getSubject();
String tenantId = jwsClaims.getBody().get("tenant", String.class);
List<String> scopes = jwsClaims.getBody().get("scopes", List.class);
List<GrantedAuthority> authorities = scopes.stream()
.map(authority -> new SimpleGrantedAuthority(authority))
.collect(Collectors.toList());
UserContext context = UserContext.create(tenantId, orgId, authorities);
return new JwtAuthenticationToken(context, context.getAuthorities());
}
示例2: getAuthenticationFromToken
import io.jsonwebtoken.Jws; //导入依赖的package包/类
public String getAuthenticationFromToken(final String base64EncodedToken) throws JwtException {
// The library representations of the JWT should be kept internal to this service.
try {
final Jws<Claims> jws = parseTokenFromBase64EncodedString(base64EncodedToken);
if (jws == null) {
throw new JwtException("Unable to parse token");
}
// Additional validation that subject is present
if (StringUtils.isEmpty(jws.getBody().getSubject())) {
throw new JwtException("No subject available in token");
}
// TODO: Validate issuer against active IdentityProvider?
if (StringUtils.isEmpty(jws.getBody().getIssuer())) {
throw new JwtException("No issuer available in token");
}
return jws.getBody().getSubject();
} catch (JwtException e) {
logger.debug("The Base64 encoded JWT: " + base64EncodedToken);
final String errorMessage = "There was an error validating the JWT";
logger.error(errorMessage, e);
throw e;
}
}
示例3: parseTokenFromBase64EncodedString
import io.jsonwebtoken.Jws; //导入依赖的package包/类
private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
try {
return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {
@Override
public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
final String identity = claims.getSubject();
// Get the key based on the key id in the claims
final String keyId = claims.get(KEY_ID_CLAIM, String.class);
final Key key = keyService.getKey(keyId);
// Ensure we were able to find a key that was previously issued by this key service for this user
if (key == null || key.getKey() == null) {
throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
}
return key.getKey().getBytes(StandardCharsets.UTF_8);
}
}).parseClaimsJws(base64EncodedToken);
} catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException e) {
// TODO: Exercise all exceptions to ensure none leak key material to logs
final String errorMessage = "Unable to validate the access token.";
throw new JwtException(errorMessage, e);
}
}
示例4: parseRefreshToken
import io.jsonwebtoken.Jws; //导入依赖的package包/类
public SecurityUser parseRefreshToken(RawAccessJwtToken rawAccessToken) {
Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey());
Claims claims = jwsClaims.getBody();
String subject = claims.getSubject();
List<String> scopes = claims.get(SCOPES, List.class);
if (scopes == null || scopes.isEmpty()) {
throw new IllegalArgumentException("Refresh Token doesn't have any scopes");
}
if (!scopes.get(0).equals(Authority.REFRESH_TOKEN.name())) {
throw new IllegalArgumentException("Invalid Refresh Token scope");
}
boolean isPublic = claims.get(IS_PUBLIC, Boolean.class);
UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME,
subject);
SecurityUser securityUser = new SecurityUser(new UserId(UUID.fromString(claims.get(USER_ID, String.class))));
securityUser.setUserPrincipal(principal);
return securityUser;
}
示例5: loginSuccessfullAdmin
import io.jsonwebtoken.Jws; //导入依赖的package包/类
@Test
public void loginSuccessfullAdmin() throws Exception {
final UserLoginDto user = new UserLoginDto("admin", "admin");
final MvcResult result = mockMvc.perform(post(PREFIX + "/login")
.contentType(contentType).content(this.json(user)))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("token").exists())
.andReturn();
final String body = result.getResponse().getContentAsString();
final ObjectMapper mapper = new ObjectMapper();
final JsonNode node = mapper.readTree(body);
final String token = node.get("token").asText();
log.debug("Token: " + token);
final Jws<Claims> claims = Jwts.parser()
.setSigningKey(TEST_KEY)
.parseClaimsJws(token);
assertEquals("admin", claims.getBody().getSubject());
}
示例6: loginSuccessfullUser
import io.jsonwebtoken.Jws; //导入依赖的package包/类
@Test
public void loginSuccessfullUser() throws Exception {
final UserLoginDto user = new UserLoginDto("user", "user");
final MvcResult result = mockMvc.perform(post(PREFIX + "/login")
.contentType(contentType).content(this.json(user)))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("token").exists())
.andReturn();
final String body = result.getResponse().getContentAsString();
final ObjectMapper mapper = new ObjectMapper();
final JsonNode node = mapper.readTree(body);
final String token = node.get("token").asText();
log.debug("Token: " + token);
final Jws<Claims> claims = Jwts.parser()
.setSigningKey(TEST_KEY)
.parseClaimsJws(token);
assertEquals("user", claims.getBody().getSubject());
}
示例7: authenticate
import io.jsonwebtoken.Jws; //导入依赖的package包/类
@Override
public Authentication authenticate(final HttpServletRequest request) {
final String token = request.getHeader(authHeaderName);
final Optional<Jws<Claims>> tokenData = parseToken(token);
if (tokenData.isPresent()) {
try {
final User user = getUserFromToken(tokenData.get());
return new UserAuthentication(user);
} catch (UserNotFoundException e) {
log.warn(e.getMessage());
}
}
return null;
}
示例8: authenticate
import io.jsonwebtoken.Jws; //导入依赖的package包/类
@Override
public void authenticate(final JsonObject authRequest, final Handler<AsyncResult<HonoUser>> authenticationResultHandler) {
final DeliveryOptions options = new DeliveryOptions().setSendTimeout(AUTH_REQUEST_TIMEOUT_MILLIS);
vertx.eventBus().send(AuthenticationConstants.EVENT_BUS_ADDRESS_AUTHENTICATION_IN, authRequest, options, reply -> {
if (reply.succeeded()) {
JsonObject result = (JsonObject) reply.result().body();
String token = result.getString(AuthenticationConstants.FIELD_TOKEN);
log.debug("received token [length: {}] in response to authentication request", token.length());
try {
Jws<Claims> expandedToken = tokenValidator.expand(result.getString(AuthenticationConstants.FIELD_TOKEN));
authenticationResultHandler.handle(Future.succeededFuture(new HonoUserImpl(expandedToken, token)));
} catch (JwtException e) {
authenticationResultHandler.handle(Future.failedFuture(e));
}
} else {
authenticationResultHandler.handle(Future.failedFuture(reply.cause()));
}
});
}
示例9: parsePortalRequest
import io.jsonwebtoken.Jws; //导入依赖的package包/类
public PortalRequest parsePortalRequest(String portalRequestToken) {
final Jws<Claims> claims = parseEncrypteToken(portalRequestToken, PortalRequest.class);
final String username = claims.getBody().getSubject();
// Properties
@SuppressWarnings("unchecked")
final Map<String,String> properties = (Map<String, String>) claims.getBody().get(JwtClaims.PROPERTIES.getName());
// Attributes
@SuppressWarnings("unchecked")
final Map<String,List<String>> attributes = (Map<String, List<String>>) claims.getBody().get(JwtClaims.ATTRIBUTES.getName());
// Parameters
@SuppressWarnings("unchecked")
final Map<String,List<String>> parameters = (Map<String, List<String>>) claims.getBody().get(JwtClaims.PARAMETERS.getName());
PortalRequest rslt = new PortalRequest(portalRequestToken, properties, attributes, parameters);
logger.debug("Produced the following PortalRequest for user '{}': {}", username, rslt);
return rslt;
}
示例10: verifyJwt
import io.jsonwebtoken.Jws; //导入依赖的package包/类
/**
* {@inheritDoc}
*/
@Override
public boolean verifyJwt(String jwt) {
boolean verified = false;
try {
Assert.hasText(jwt, "JWT can't be null or empty!!");
JwtParser jwtParser = Jwts.parser().requireIssuer(this.jwtConfig.issuer());
this.setSigningKey(jwtParser);
Jws<Claims> claimsJws = jwtParser.parseClaimsJws(jwt);
verified = !this.jwtConfig.validateClaims() ||
this.claimsValidator != null && this.claimsValidator.validate(claimsJws.getBody());
} catch (RuntimeException ex) {
// For reducing noise in the logs, set this config to false.
if (this.jwtConfig.printJwtExceptionTrace()) {
LOGGER.error(ex.getMessage(), ex);
} else {
LOGGER.error(ex.getMessage());
}
}
return verified;
}
示例11: tokenFromStringJwt
import io.jsonwebtoken.Jws; //导入依赖的package包/类
public JwtAuthenticationToken tokenFromStringJwt(String rawJwt) {
DefaultJwtParser parser = ((DefaultJwtParser) Jwts.parser());
parser.setSigningKey(signingSecret);
try {
Jws<Claims> jws = parser.parseClaimsJws(rawJwt);
Claims claims = jws.getBody();
UUID userId = UUID.fromString((String) claims.get("user_id"));
String email = ((String) claims.get("email"));
Collection<? extends GrantedAuthority> roles = parseRolesFromClaims(claims);
return new JwtAuthenticationToken(userId, email, roles);
} catch (Exception e) {
log.info(String.format("Exception occurred parsing JWT [%s].\nException message: %s", rawJwt, e.getMessage()));
return null;
}
}
示例12: parseRefreshToken
import io.jsonwebtoken.Jws; //导入依赖的package包/类
public SecurityUser parseRefreshToken(RawAccessJwtToken rawAccessToken) {
Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey());
Claims claims = jwsClaims.getBody();
String subject = claims.getSubject();
List<String> scopes = claims.get(SCOPES, List.class);
if (scopes == null || scopes.isEmpty()) {
throw new IllegalArgumentException("Refresh Token doesn't have any scopes");
}
if (!scopes.get(0).equals(Authority.REFRESH_TOKEN.name())) {
throw new IllegalArgumentException("Invalid Refresh Token scope");
}
boolean isPublic = claims.get(IS_PUBLIC, Boolean.class);
UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME, subject);
SecurityUser securityUser = new SecurityUser(new UserId(UUID.fromString(claims.get(USER_ID, String.class))));
securityUser.setUserPrincipal(principal);
return securityUser;
}
示例13: parse
import io.jsonwebtoken.Jws; //导入依赖的package包/类
/**
* {@inheritDoc}
*/
@Override
public Jws<Claims> parse(String token, Asymmetric issuer) {
Jws<Claims> jws;
try {
Jwk jwk = jwkProvider.get(issuer.getKID());
byte[] publicKeyBytes = jwk.getPublicKey().getEncoded();
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);
jws = Jwts.parser()
.setAllowedClockSkewSeconds(issuer.getSkewSeconds())
.setSigningKey(pubKey)
.parseClaimsJws(token);
return jws;
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
throw new InvalidTokenException(e.getMessage());
}
}
示例14: loginReturnsValidTokenInHeader
import io.jsonwebtoken.Jws; //导入依赖的package包/类
@Test
public void loginReturnsValidTokenInHeader() throws Exception {
final String email = "[email protected]";
final String password = "lsdj=231lkjXsdlkj";
createUserHelper(email, password);
// Correct login returns a token
String authorizationToken = loginUser(email, password).andExpect(status().isOk()).andExpect(header().string
("Authorization", Matchers.not(Matchers.isEmptyOrNullString()))).andReturn().getResponse().getHeader
("Authorization");
// Token is valid
Assert.assertTrue(StringUtils.hasText(authorizationToken));
Assert.assertTrue(authorizationToken.startsWith("Bearer "));
String jwt = authorizationToken.substring(7, authorizationToken.length());
// Check claims
String serverSigningKey = appConfig.getJwtSecret();
Jws<Claims> claims = Jwts.parser().setSigningKey(serverSigningKey.getBytes()).parseClaimsJws(jwt);
Assert.assertEquals(claims.getBody().getSubject(), email);
Assert.assertTrue(claims.getBody().getExpiration().after(new Date()));
Assert.assertEquals(claims.getBody().get("auth", String.class), "ROLE_USER");
}
示例15: hasValidSessionCookie
import io.jsonwebtoken.Jws; //导入依赖的package包/类
@SuppressWarnings("unchecked")
public boolean hasValidSessionCookie() {
decrypt();
boolean valid = false;
if (StringUtils.isNotBlank(this.value)) {
try {
Jws<Claims> jwsClaims = Jwts.parser()
.setSigningKey(this.secret)
.parseClaimsJws(this.value);
Claims claims = jwsClaims.getBody();
Date expiration = claims.getExpiration();
if (expiration != null) {
this.sessionValues = claims.get(ClaimKey.DATA.toString(), Map.class);
this.authenticityToken = claims.get(ClaimKey.AUTHENTICITY.toString(), String.class);
this.expiresDate = dateToLocalDateTime(expiration);
valid = true;
}
} catch (Exception e) { //NOSONAR
LOG.error("Failed to parse JWS for seesion cookie", e);
}
}
return valid;
}