Java Code Examples for io.jsonwebtoken.security.Keys#hmacShaKeyFor()

The following examples show how to use io.jsonwebtoken.security.Keys#hmacShaKeyFor() . 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: JwtOperator.java    From light-security with Apache License 2.0 6 votes vote down vote up
/**
 * 为指定用户生成token
 *
 * @param user 用户信息
 * @return token
 */
public String generateToken(User user) {
    Map<String, Object> claims = new HashMap<>(3);
    claims.put(USER_ID, user.getId());
    claims.put(USERNAME, user.getUsername());
    claims.put(ROLES, user.getRoles());
    Date createdTime = new Date();
    Date expirationTime = this.getExpirationTime();

    byte[] keyBytes = this.lightSecurityProperties.getJwt().getSecret().getBytes();
    SecretKey key = Keys.hmacShaKeyFor(keyBytes);

    return Jwts.builder()
            .setClaims(claims)
            .setIssuedAt(createdTime)
            .setExpiration(expirationTime)
            .signWith(key)
            .compact();
}
 
Example 2
Source File: JwtOperator.java    From light-security with Apache License 2.0 6 votes vote down vote up
/**
 * 为指定用户生成token
 *
 * @param user 用户信息
 * @return token
 */
public String generateToken(User user) {
    Map<String, Object> claims = new HashMap<>(3);
    claims.put(USER_ID, user.getId());
    claims.put(USERNAME, user.getUsername());
    claims.put(ROLES, user.getRoles());
    Date createdTime = new Date();
    Date expirationTime = this.getExpirationTime();

    byte[] keyBytes = this.reactiveLightSecurityProperties.getJwt().getSecret().getBytes();
    SecretKey key = Keys.hmacShaKeyFor(keyBytes);

    return Jwts.builder()
            .setClaims(claims)
            .setIssuedAt(createdTime)
            .setExpiration(expirationTime)
            .signWith(key)
            .compact();
}
 
Example 3
Source File: TokenProvider.java    From 21-points with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() {
    byte[] keyBytes;
    String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret();
    if (!StringUtils.isEmpty(secret)) {
        log.warn("Warning: the JWT key used is not Base64-encoded. " +
            "We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security.");
        keyBytes = secret.getBytes(StandardCharsets.UTF_8);
    } else {
        log.debug("Using a Base64-encoded JWT secret key");
        keyBytes = Decoders.BASE64.decode(jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret());
    }
    this.key = Keys.hmacShaKeyFor(keyBytes);
    this.tokenValidityInMilliseconds =
        1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds();
    this.tokenValidityInMillisecondsForRememberMe =
        1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt()
            .getTokenValidityInSecondsForRememberMe();
}
 
Example 4
Source File: JWTGenerator.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
    //Warning if the secret is still the default one
    if ("s3cR3t4grAv1t3310AMS1g1ingDftK3y".equals(signingKeySecret)) {
        LOGGER.warn("");
        LOGGER.warn("##############################################################");
        LOGGER.warn("#                      SECURITY WARNING                      #");
        LOGGER.warn("##############################################################");
        LOGGER.warn("");
        LOGGER.warn("You still use the default jwt secret.");
        LOGGER.warn("This known secret can be used to impersonate anyone.");
        LOGGER.warn("Please change this value, or ask your administrator to do it !");
        LOGGER.warn("");
        LOGGER.warn("##############################################################");
        LOGGER.warn("");
    }

    // init JWT signing key
    key = Keys.hmacShaKeyFor(signingKeySecret.getBytes());
}
 
Example 5
Source File: TokenProvider.java    From e-commerce-microservice with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() {
    byte[] keyBytes;
    String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret();
    if (!StringUtils.isEmpty(secret)) {
        log.warn("Warning: the JWT key used is not Base64-encoded. " +
            "We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security.");
        keyBytes = secret.getBytes(StandardCharsets.UTF_8);
    } else {
        log.debug("Using a Base64-encoded JWT secret key");
        keyBytes = Decoders.BASE64.decode(jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret());
    }
    this.key = Keys.hmacShaKeyFor(keyBytes);
    this.tokenValidityInMilliseconds =
        1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds();
    this.tokenValidityInMillisecondsForRememberMe =
        1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt()
            .getTokenValidityInSecondsForRememberMe();
}
 
Example 6
Source File: TokenProviderTest.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setup() {
    tokenProvider = new TokenProvider( new JHipsterProperties());
    key = Keys.hmacShaKeyFor(Decoders.BASE64
        .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));

    ReflectionTestUtils.setField(tokenProvider, "key", key);
    ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", ONE_MINUTE);
}
 
Example 7
Source File: TokenProvider.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@PostConstruct
public void init() {
	String secret = applicationProperties.getSecurity().getAuthentication().getJwt().getBase64Secret();
	Assert.isTrue(StringUtil.isNotEmpty(secret), "jwt secret can not be empty");
	byte[] keyBytes = Decoders.BASE64.decode(secret);
	this.secretKey = Keys.hmacShaKeyFor(keyBytes);

	this.tokenValidityInMilliseconds =
		1000 * applicationProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds();
	this.tokenValidityInMillisecondsForRememberMe =
		1000 * applicationProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSecondsForRememberMe();
}
 
Example 8
Source File: TokenProviderTest.java    From e-commerce-microservice with Apache License 2.0 5 votes vote down vote up
private String createTokenWithDifferentSignature() {
    Key otherKey = Keys.hmacShaKeyFor(Decoders.BASE64
        .decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));

    return Jwts.builder()
        .setSubject("anonymous")
        .signWith(otherKey, SignatureAlgorithm.HS512)
        .setExpiration(new Date(new Date().getTime() + ONE_MINUTE))
        .compact();
}
 
Example 9
Source File: TokenProviderTest.java    From e-commerce-microservice with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    jHipsterProperties = Mockito.mock(JHipsterProperties.class);
    tokenProvider = new TokenProvider(jHipsterProperties);
    key = Keys.hmacShaKeyFor(Decoders.BASE64
        .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));

    ReflectionTestUtils.setField(tokenProvider, "key", key);
    ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", ONE_MINUTE);
}
 
Example 10
Source File: TokenProviderTest.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setup() {
    tokenProvider = new TokenProvider( new JHipsterProperties());
    key = Keys.hmacShaKeyFor(Decoders.BASE64
        .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));

    ReflectionTestUtils.setField(tokenProvider, "key", key);
    ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", ONE_MINUTE);
}
 
Example 11
Source File: JwtHelperTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that an expired token is detected.
 */
@Test
public void testIsExpired() {

    final SecretKey key = Keys.hmacShaKeyFor(secret);
    final String token = Jwts.builder()
                        .signWith(key, SignatureAlgorithm.HS256)
                        .setExpiration(Date.from(Instant.now().minus(Duration.ofSeconds(10))))
                        .compact();

    assertTrue(JwtHelper.isExpired(token, 10));
    assertFalse(JwtHelper.isExpired(token, 15));
}
 
Example 12
Source File: TokenProviderUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
private String createTokenWithDifferentSignature() {
    Key otherKey = Keys.hmacShaKeyFor(Decoders.BASE64
        .decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));

    return Jwts.builder()
        .setSubject("anonymous")
        .signWith(otherKey, SignatureAlgorithm.HS512)
        .setExpiration(new Date(new Date().getTime() + ONE_MINUTE))
        .compact();
}
 
Example 13
Source File: TokenProviderTest.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
private String createTokenWithDifferentSignature() {
    Key otherKey = Keys.hmacShaKeyFor(Decoders.BASE64
        .decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));

    return Jwts.builder()
        .setSubject("anonymous")
        .signWith(otherKey, SignatureAlgorithm.HS512)
        .setExpiration(new Date(new Date().getTime() + ONE_MINUTE))
        .compact();
}
 
Example 14
Source File: TokenProviderTest.java    From alchemy with Apache License 2.0 5 votes vote down vote up
private String createTokenWithDifferentSignature() {
    Key otherKey = Keys.hmacShaKeyFor(Decoders.BASE64
        .decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));

    return Jwts.builder()
        .setSubject("anonymous")
        .signWith(otherKey, SignatureAlgorithm.HS512)
        .setExpiration(new Date(new Date().getTime() + ONE_MINUTE))
        .compact();
}
 
Example 15
Source File: TokenProviderTest.java    From ehcache3-samples with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    jHipsterProperties = Mockito.mock(JHipsterProperties.class);
    tokenProvider = new TokenProvider(jHipsterProperties);
    key = Keys.hmacShaKeyFor(Decoders.BASE64
        .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));

    ReflectionTestUtils.setField(tokenProvider, "key", key);
    ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", ONE_MINUTE);
}
 
Example 16
Source File: UserAuthService.java    From auto-subtitle-tool with GNU General Public License v2.0 5 votes vote down vote up
private String generatorJWT(Long userId) {
    Key key = Keys.hmacShaKeyFor(EncryConstant.SECRET.getBytes());
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.add(Calendar.MONTH, 2);
    // 失效时间为2个月
    return Jwts.builder().setSubject(ROLE)
            .setId(String.valueOf(userId))
            .setIssuedAt(new Date())
            .setExpiration(calendar.getTime())
            .signWith(key)
            .compact();
}
 
Example 17
Source File: TokenProvider.java    From jwt-spring-security-demo with MIT License 4 votes vote down vote up
@Override
public void afterPropertiesSet() {
   byte[] keyBytes = Decoders.BASE64.decode(base64Secret);
   this.key = Keys.hmacShaKeyFor(keyBytes);
}
 
Example 18
Source File: JWTUtil.java    From spring-boot-webflux-jjwt with Apache License 2.0 4 votes vote down vote up
@PostConstruct
public void init(){
	this.key = Keys.hmacShaKeyFor(secret.getBytes());
}
 
Example 19
Source File: TokenProvider.java    From sk-admin with Apache License 2.0 4 votes vote down vote up
@Override
public void afterPropertiesSet() {
    byte[] keyBytes = Decoders.BASE64.decode(properties.getBase64Secret());
    this.key = Keys.hmacShaKeyFor(keyBytes);
}
 
Example 20
Source File: TokenUtil.java    From JwtPermission with Apache License 2.0 2 votes vote down vote up
/**
 * 把16进制的key解析成Key
 *
 * @param hexKey 16进制key
 * @return Key
 */
public static Key parseHexKey(String hexKey) {
    if (hexKey == null || hexKey.trim().isEmpty()) return null;
    return Keys.hmacShaKeyFor(Hex.decode(hexKey));
}