io.jsonwebtoken.security.Keys Java Examples
The following examples show how to use
io.jsonwebtoken.security.Keys.
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: TokenProvider.java From e-commerce-microservice with Apache License 2.0 | 6 votes |
@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 #2
Source File: JwtAuthenticationFilter.java From jwt-security with MIT License | 6 votes |
@Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain, Authentication authentication) { var user = ((User) authentication.getPrincipal()); var roles = user.getAuthorities() .stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.toList()); var signingKey = SecurityConstants.JWT_SECRET.getBytes(); var token = Jwts.builder() .signWith(Keys.hmacShaKeyFor(signingKey), SignatureAlgorithm.HS512) .setHeaderParam("typ", SecurityConstants.TOKEN_TYPE) .setIssuer(SecurityConstants.TOKEN_ISSUER) .setAudience(SecurityConstants.TOKEN_AUDIENCE) .setSubject(user.getUsername()) .setExpiration(new Date(System.currentTimeMillis() + 864000000)) .claim("rol", roles) .compact(); response.addHeader(SecurityConstants.TOKEN_HEADER, SecurityConstants.TOKEN_PREFIX + token); }
Example #3
Source File: JwtOperator.java From light-security with Apache License 2.0 | 6 votes |
/** * 为指定用户生成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 #4
Source File: TokenProvider.java From alchemy with Apache License 2.0 | 6 votes |
@Override public void afterPropertiesSet() throws Exception { 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 #5
Source File: TokenProvider.java From e-commerce-microservice with Apache License 2.0 | 6 votes |
@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: JwtOperator.java From light-security with Apache License 2.0 | 6 votes |
/** * 为指定用户生成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 #7
Source File: TokenProvider.java From e-commerce-microservice with Apache License 2.0 | 6 votes |
@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 #8
Source File: Utils.java From samples-android with Apache License 2.0 | 6 votes |
public static String getJwt(String issuer, String nonce, Date expiredDate, Date issuedAt, String... audience) { JwtBuilder builder = Jwts.builder(); KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256); Map<String, Object> map = new HashMap<>(); map.put(Claims.AUDIENCE, Arrays.asList(audience)); return builder .addClaims(map) .claim("nonce", nonce) .setIssuer(issuer) .setSubject("sub") .setExpiration(expiredDate) .setIssuedAt(issuedAt) .signWith(keyPair.getPrivate(), SignatureAlgorithm.RS256) .compact(); }
Example #9
Source File: TokenProvider.java From jhipster-online with Apache License 2.0 | 6 votes |
@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 #10
Source File: TestUtils.java From okta-sdk-appauth-android with Apache License 2.0 | 6 votes |
public static String getValidTokenResponse(String baseUrl, String nonce) { KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256); Map<String,Object> additionalParameters = new HashMap<>(); additionalParameters.put("nonce", nonce); String jws = Jwts.builder() .setSubject(TEST_CLIENT_ID) .setAudience(TEST_CLIENT_ID) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + 24*60*60*1000)) .setIssuer(baseUrl+"/") .addClaims(additionalParameters) .signWith(keyPair.getPrivate()).compact(); return "{" + "\"access_token\":\"eyJraWQiOiJHYjl2VDBSS0xPWjYyYmN6WVFJckJtY0FBYkVUcDJaVTdudWVCVFlsUkdVIiwiYWxnIjoiUlMyNTYifQ.eyJ2ZXIiOjEsImp0aSI6IkFULlY4UmdqQUhabWFXUzkxZEFORHpJNmFFdVVFeDNHYUpXTVdzXzExMlRPRjAiLCJpc3MiOiJodHRwczovL2xvaGlrYS11bS5va3RhcHJldmlldy5jb20vb2F1dGgyL2RlZmF1bHQiLCJhdWQiOiJhcGk6Ly9kZWZhdWx0IiwiaWF0IjoxNTQ1NDAwMDIxLCJleHAiOjE1NDU0ODY0MjEsImNpZCI6IjBvYWhuemhzZWd6WWpxRVRjMGg3IiwidWlkIjoiMDB1aHR3c3JyaUFDNXVpNDcwaDciLCJzY3AiOlsib3BlbmlkIiwicHJvZmlsZSJdLCJzdWIiOiJpbWFydHNla2hhQGxvaGlrYS5jb20ifQ.Bp-r0st5yyMFLKqoheh3mUTH_JhqubfBWXABWwApBoB_QqMB05EDskIBAhKfyc3KGMynoBK7fftP1KwNBhznYBQWUeueyXb5oHhKkPDYj8ds5Leu4758gLIDW2Ybj_eWspCR6aC1-eGWQZ-IbMz_rEpElmYC9TTXRPFngderPvqNW3dFU7VNJN-NFI18qEMRNf8-bIS8Qp9M1cU0WGKGi1wFDdgPM3761_R8beGMlWvulyA9B6mxZUs7M-ZxivJIdFbCKoFvxBo54ZBWXeMe-moEJA_tzXEuZf-Rq0mETwma-zBDCUWN3unZ51KRqEAtnZzGKDnt58on-olztbj1eA\"," + "\"token_type\":\"Bearer\"," + "\"expires_in\":86400," + "\"scope\":\"openid profile\"," + "\"id_token\":\""+jws+"\"" + "}"; }
Example #11
Source File: JWTGenerator.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@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 #12
Source File: TokenProvider.java From ehcache3-samples with Apache License 2.0 | 6 votes |
@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 #13
Source File: TokenProvider.java From jhipster-registry with Apache License 2.0 | 6 votes |
@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 #14
Source File: AuthenticationProviderTokenTest.java From pulsar with Apache License 2.0 | 6 votes |
@Test public void testSerializeKeyPair() throws Exception { KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256); String privateKey = AuthTokenUtils.encodeKeyBase64(keyPair.getPrivate()); String publicKey = AuthTokenUtils.encodeKeyBase64(keyPair.getPublic()); String token = AuthTokenUtils.createToken(AuthTokenUtils.decodePrivateKey(Decoders.BASE64.decode(privateKey), SignatureAlgorithm.RS256), SUBJECT, Optional.empty()); @SuppressWarnings("unchecked") Jwt<?, Claims> jwt = Jwts.parser() .setSigningKey(AuthTokenUtils.decodePublicKey(Decoders.BASE64.decode(publicKey), SignatureAlgorithm.RS256)) .parse(token); assertNotNull(jwt); assertNotNull(jwt.getBody()); assertEquals(jwt.getBody().getSubject(), SUBJECT); }
Example #15
Source File: LTI13JJWTTest.java From sakai with Educational Community License v2.0 | 6 votes |
@Test public void testOne() throws NoSuchAlgorithmException, NoSuchProviderException { Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256); String jws = Jwts.builder().setSubject("Joe").signWith(key).compact(); assertEquals(83, jws.length()); Matcher m = base64url_pattern.matcher(jws); boolean good = m.find(); if (!good) { System.out.println("Bad JWS:\n" + jws); } assertTrue(good); String subject = Jwts.parser().setAllowedClockSkewSeconds(60).setSigningKey(key).parseClaimsJws(jws).getBody().getSubject(); assertEquals("Joe", subject); }
Example #16
Source File: TokenProvider.java From 21-points with Apache License 2.0 | 6 votes |
@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 #17
Source File: LTI13JJWTTest.java From sakai with Educational Community License v2.0 | 6 votes |
@Test public void testOne() throws NoSuchAlgorithmException, NoSuchProviderException { Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256); String jws = Jwts.builder().setSubject("Joe").signWith(key).compact(); assertEquals(83, jws.length()); Matcher m = base64url_pattern.matcher(jws); boolean good = m.find(); if (!good) { System.out.println("Bad JWS:\n" + jws); } assertTrue(good); String subject = Jwts.parser().setAllowedClockSkewSeconds(60).setSigningKey(key).parseClaimsJws(jws).getBody().getSubject(); assertEquals("Joe", subject); }
Example #18
Source File: TokenProvider.java From tutorials with MIT License | 6 votes |
@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 #19
Source File: LTI13JJWTTest.java From sakai with Educational Community License v2.0 | 5 votes |
@Test public void testThree() throws NoSuchAlgorithmException, NoSuchProviderException { Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256); String jws = Jwts.builder() .setIssuer("me").setSubject("Bob").setAudience("you") .signWith(key).compact(); String x = getBody(jws, key); assertEquals("{iss=me, sub=Bob, aud=you}", x); }
Example #20
Source File: TokenProviderUnitTest.java From tutorials with MIT License | 5 votes |
@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 #21
Source File: ApiUtils.java From auto-subtitle-tool with GNU General Public License v2.0 | 5 votes |
/** * 获取当前用户id */ public static Long currentUid(String jwt) { Key key = Keys.hmacShaKeyFor(EncryConstant.SECRET.getBytes()); Long userId = null; Date expireDate = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody().getExpiration(); if (expireDate.getTime() < new Date().getTime()) { throw new LoginException(ErrorCodeEnum.AUTHENTICATION_EXPIRE); } try { userId = Long.valueOf(Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody().getId()); } catch (JwtException e) { throw new LoginException(ErrorCodeEnum.UNAUTHORIZED); } return userId; }
Example #22
Source File: AuthenticationProviderTokenTest.java From pulsar with Apache License 2.0 | 5 votes |
@Test public void testAuthSecretKeyPairWithECDSA() throws Exception { KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.ES256); String privateKeyStr = AuthTokenUtils.encodeKeyBase64(keyPair.getPrivate()); String publicKeyStr = AuthTokenUtils.encodeKeyBase64(keyPair.getPublic()); AuthenticationProviderToken provider = new AuthenticationProviderToken(); Properties properties = new Properties(); // Use public key for validation properties.setProperty(AuthenticationProviderToken.CONF_TOKEN_PUBLIC_KEY, publicKeyStr); // Set that we are using EC keys properties.setProperty(AuthenticationProviderToken.CONF_TOKEN_PUBLIC_ALG, SignatureAlgorithm.ES256.getValue()); ServiceConfiguration conf = new ServiceConfiguration(); conf.setProperties(properties); provider.initialize(conf); // Use private key to generate token PrivateKey privateKey = AuthTokenUtils.decodePrivateKey(Decoders.BASE64.decode(privateKeyStr), SignatureAlgorithm.ES256); String token = AuthTokenUtils.createToken(privateKey, SUBJECT, Optional.empty()); // Pulsar protocol auth String subject = provider.authenticate(new AuthenticationDataSource() { @Override public boolean hasDataFromCommand() { return true; } @Override public String getCommandData() { return token; } }); assertEquals(subject, SUBJECT); provider.close(); }
Example #23
Source File: AuthenticationProviderTokenTest.java From pulsar with Apache License 2.0 | 5 votes |
@Test public void testAuthSecretKeyPair() throws Exception { KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256); String privateKeyStr = AuthTokenUtils.encodeKeyBase64(keyPair.getPrivate()); String publicKeyStr = AuthTokenUtils.encodeKeyBase64(keyPair.getPublic()); AuthenticationProviderToken provider = new AuthenticationProviderToken(); Properties properties = new Properties(); // Use public key for validation properties.setProperty(AuthenticationProviderToken.CONF_TOKEN_PUBLIC_KEY, publicKeyStr); ServiceConfiguration conf = new ServiceConfiguration(); conf.setProperties(properties); provider.initialize(conf); // Use private key to generate token PrivateKey privateKey = AuthTokenUtils.decodePrivateKey(Decoders.BASE64.decode(privateKeyStr), SignatureAlgorithm.RS256); String token = AuthTokenUtils.createToken(privateKey, SUBJECT, Optional.empty()); // Pulsar protocol auth String subject = provider.authenticate(new AuthenticationDataSource() { @Override public boolean hasDataFromCommand() { return true; } @Override public String getCommandData() { return token; } }); assertEquals(subject, SUBJECT); provider.close(); }
Example #24
Source File: TokenProvider.java From flair-registry with Apache License 2.0 | 5 votes |
@PostConstruct public void init() { String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret(); String base64secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret(); byte[] keyBytes; if (StringUtils.isEmpty(base64secret)) { log.info("The JWT key used is not Base64-encoded. " + "We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security."); if (StringUtils.isEmpty(secret)) { log.error("\n----------------------------------------------------------\n" + "Your JWT secret key is not set up, you will not be able to log into the JHipster.\n"+ "Please read the documentation at https://www.jhipster.tech/jhipster-registry/\n" + "----------------------------------------------------------"); throw new RuntimeException("No JWT secret key is configured, the application cannot start."); } keyBytes = secret.getBytes(StandardCharsets.UTF_8); } else { log.debug("Using a Base64-encoded JWT secret key"); keyBytes = Decoders.BASE64.decode(base64secret); } this.key = Keys.hmacShaKeyFor(keyBytes); this.tokenValidityInMilliseconds = 1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds(); this.tokenValidityInMillisecondsForRememberMe = 1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt() .getTokenValidityInSecondsForRememberMe(); }
Example #25
Source File: TokenProviderTest.java From jhipster-registry with Apache License 2.0 | 5 votes |
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 #26
Source File: TokenProviderTest.java From jhipster-registry with Apache License 2.0 | 5 votes |
@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 #27
Source File: JWTFilterTest.java From jhipster-registry with Apache License 2.0 | 5 votes |
@BeforeEach public void setup() { JHipsterProperties jHipsterProperties = new JHipsterProperties(); tokenProvider = new TokenProvider(jHipsterProperties); ReflectionTestUtils.setField(tokenProvider, "key", Keys.hmacShaKeyFor(Decoders.BASE64 .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"))); ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000); jwtFilter = new JWTFilter(tokenProvider); SecurityContextHolder.getContext().setAuthentication(null); }
Example #28
Source File: TokenProviderTest.java From ehcache3-samples with Apache License 2.0 | 5 votes |
@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 #29
Source File: JWTFilterTest.java From ehcache3-samples with Apache License 2.0 | 5 votes |
@Before public void setup() { JHipsterProperties jHipsterProperties = new JHipsterProperties(); tokenProvider = new TokenProvider(jHipsterProperties); ReflectionTestUtils.setField(tokenProvider, "key", Keys.hmacShaKeyFor(Decoders.BASE64 .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"))); ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000); jwtFilter = new JWTFilter(tokenProvider); SecurityContextHolder.getContext().setAuthentication(null); }
Example #30
Source File: LTI13JJWTTest.java From sakai with Educational Community License v2.0 | 5 votes |
@Test public void testFour() throws NoSuchAlgorithmException, NoSuchProviderException { String nonce = UUID.randomUUID().toString(); String client_id = "12345"; String subject = "Bob"; String locale = Locale.getDefault().getLanguage().replace('_', '-'); Matcher m = uuid_pattern.matcher(nonce); boolean good = m.find(); if (!good) { System.out.println("Bad UUID:\n" + nonce); } assertTrue(good); Date now = new Date(); Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256); String jws = Jwts.builder() .setIssuer(LTI_13_ISSUER) .setSubject(subject) .setAudience(client_id) .setIssuedAt(now) .setExpiration(new Date(now.getTime() + 600000L)) // Milliseconds .claim(LTI13ConstantsUtil.KEY_NONCE, nonce) .claim(LTI13ConstantsUtil.KEY_LOCALE, locale) .signWith(key) .compact(); String body = getBody(jws, key); good = body.contains(LTI_13_ISSUER); if (!good) { System.out.println("Bad body: " + body); } assertTrue(good); }