Java 类io.jsonwebtoken.SignatureAlgorithm 实例源码

项目:OpenLRW    文件:JwtTokenFactory.java   
public JwtToken createRefreshToken(UserContext userContext) {
  if (StringUtils.isBlank(userContext.getTenantId())) 
    throw new IllegalArgumentException("Cannot create JWT Token without tenantId");

  if (StringUtils.isBlank(userContext.getOrgId())) 
    throw new IllegalArgumentException("Cannot create JWT Token without orgId");

    DateTime currentTime = new DateTime();

    Claims claims = Jwts.claims().setSubject(userContext.getOrgId());
    claims.put("scopes", userContext.getAuthorities().stream().map(s -> s.toString()).collect(Collectors.toList()));
    claims.put("tenant", userContext.getTenantId());

    String token = Jwts.builder()
      .setClaims(claims)
      .setIssuer(settings.getTokenIssuer())
      .setId(UUID.randomUUID().toString())
      .setIssuedAt(currentTime.toDate())
      .setExpiration(currentTime.plusMinutes(settings.getRefreshTokenExpTime()).toDate())
      .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey())
    .compact();

    return new AccessJwtToken(token, claims);
}
项目:yum    文件:JwtCodec.java   
public static String encode(String subject, ArrayList<String> roles) {
    // prepare expiration date according to application properties
    Date expDate = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(expDate);

    int unit;
    switch (applicationProperties.getTokenExpiration().getUnit()) {
        case "SECOND":
            unit = Calendar.SECOND;
            break;
        case "MINUTE":
            unit = Calendar.MINUTE;
            break;
        default:
            unit = Calendar.HOUR;
    }

    calendar.add(unit, applicationProperties.getTokenExpiration().getValue());
    expDate = calendar.getTime();

    return Jwts.builder().setSubject(subject).claim("roles", roles).setIssuedAt(new Date()).setExpiration(expDate)
            .signWith(SignatureAlgorithm.HS256, key).compact();

}
项目:users-service    文件:JwtServiceImpl.java   
private JwtToken createJWT(String id,
                           String issuer,
                           String subject,
                           String privileges,
                           long ttlMillis) {

    // The JWT signature algorithm we will be using to sign the token
    final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RS256;

    final long nowMillis = System.currentTimeMillis();
    final Date now = new Date(nowMillis);

    // We will sign our JWT with our ApiKey secret
    final Key signingKey = EncryptionUtil.getPrivateKey(
        env.getProperty("service.jwt.secret"));

    final Map<String, Object> claims = new HashMap<>();
    claims.put("privileges", privileges);

    // Let's set the JWT Claims
    final JwtBuilder builder = Jwts.builder()
        .setClaims(claims)
        .setId(id)
        .setIssuer(issuer)
        .setIssuedAt(now)
        .setSubject(subject)
        .signWith(signatureAlgorithm, signingKey);

    // If it has been specified, let's add the expiration
    if (ttlMillis >= 0) {
        long expMillis = nowMillis + ttlMillis;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp);
    }

    // Builds the JWT and serializes it to a compact, URL-safe string
    return new JwtToken(builder.compact());
}
项目:Java-9-Programming-Blueprints    文件:DeskDroidResource.java   
@POST
@Path("authorize")
@Consumes(MediaType.TEXT_PLAIN)
public Response getAuthorization(String clientCode) {
    if (clientCode != null && clientCode.equals(deskDroidService.code)) {

        String jwt = Jwts.builder()
                .setSubject("DeskDroid")
                .signWith(SignatureAlgorithm.HS512,
                        KeyGenerator.getKey(deskDroidService.getApplicationContext()))
                .compact();
        LocalBroadcastManager.getInstance(deskDroidService.getApplicationContext())
                .sendBroadcast(new Intent(DeskDroidService.CODE_ACCEPTED));

        return Response.ok(jwt).build();
    }

    return Response.status(Response.Status.UNAUTHORIZED).build();
}
项目:nectar-server    文件:NectarServerApplication.java   
@SuppressWarnings("unchecked")
private static void generateNewDeploymentToken(File tokenFile) throws IOException {
    deploymentHash = Util.computeSHA256(serverID);

    JSONObject root = new JSONObject();
    root.put("timestamp", System.currentTimeMillis());
    root.put("hash", deploymentHash);

    String jwt = Jwts.builder()
            .setPayload(root.toJSONString())
            .signWith(SignatureAlgorithm.ES384, configuration.getServerPrivateKey())
            .compact(); // Sign and build the JWT

    Util.putFileContents(jwt, tokenFile);

    logger.info("Generated new deployment token.");
}
项目:fangcloud-java-sdk    文件:YfyEnterpriseAuth.java   
/**
 * Get the enterprise token witch can used to invoke admin api,such as managing departments and groups
 *
 * @param enterpriseId Your enterprise id
 * @param expirationTimeSeconds Expiration time seconds in the future(can not be bigger than 60)
 * @return Detailed user access information
 * @throws YfyException
 */
public YfyAuthFinish getEnterpriseToken(long enterpriseId, int expirationTimeSeconds) throws YfyException {
    Claims claims = new DefaultClaims();
    claims.put("yifangyun_sub_type", "enterprise");
    claims.setSubject(String.valueOf(enterpriseId));
    claims.setExpiration(getExpirationTimeSecondsInTheFuture(expirationTimeSeconds));
    claims.setIssuedAt(new Date());
    claims.setId(getGeneratedJwtId(16));
    final String compactJws = Jwts.builder().setHeader(headers).setClaims(claims).signWith(SignatureAlgorithm.RS256, key).compact();

    return YfyRequestUtil.doPostInAuth(
            requestConfig,
            YfyAppInfo.getHost().getAuth(),
            "oauth/token",
            new HashMap<String, String>() {{
                put("grant_type", "jwt");
                put("assertion", compactJws);
            }},
            YfyAuthFinish.class);
}
项目:fangcloud-java-sdk    文件:YfyEnterpriseAuth.java   
/**
 * Get the user token witch can used to invoke personal api,such as get folder information
 *
 * @param userId The user you want to operate with
 * @param expirationTimeSeconds Expiration time seconds in the future(can not be bigger than 60)
 * @return Detailed user access information
 * @throws YfyException
 */
public YfyAuthFinish getUserToken(long userId, int expirationTimeSeconds) throws YfyException {
    Claims claims = new DefaultClaims();
    claims.put("yifangyun_sub_type", "user");
    claims.setSubject(String.valueOf(userId));
    claims.setExpiration(getExpirationTimeSecondsInTheFuture(expirationTimeSeconds));
    claims.setIssuedAt(new Date());
    claims.setId(getGeneratedJwtId(16));
    final String compactJws = Jwts.builder().setHeader(headers).setClaims(claims).signWith(SignatureAlgorithm.RS256, key).compact();

    return YfyRequestUtil.doPostInAuth(
            requestConfig,
            YfyAppInfo.getHost().getAuth(),
            "oauth/token",
            new HashMap<String, String>() {{
                put("grant_type", "jwt");
                put("assertion", compactJws);
            }},
            YfyAuthFinish.class);
}
项目:jersey-jwt-springsecurity    文件:JwtTokenIssuer.java   
/**
 * Issue a JWT token
 *
 * @param authenticationTokenDetails
 * @return
 */
public String issueToken(AuthenticationTokenDetails authenticationTokenDetails) {

    return Jwts.builder()
            .setId(authenticationTokenDetails.getId())
            .setIssuer(settings.getIssuer())
            .setAudience(settings.getAudience())
            .setSubject(authenticationTokenDetails.getUsername())
            .setIssuedAt(Date.from(authenticationTokenDetails.getIssuedDate().toInstant()))
            .setExpiration(Date.from(authenticationTokenDetails.getExpirationDate().toInstant()))
            .claim(settings.getAuthoritiesClaimName(), authenticationTokenDetails.getAuthorities())
            .claim(settings.getRefreshCountClaimName(), authenticationTokenDetails.getRefreshCount())
            .claim(settings.getRefreshLimitClaimName(), authenticationTokenDetails.getRefreshLimit())
            .signWith(SignatureAlgorithm.HS256, settings.getSecret())
            .compact();
}
项目:fish-admin    文件:TokenAuthenticationService.java   
static void addAuthentication(HttpServletResponse response, String username) {

        // 生成JWT
        String JWT = Jwts.builder()
                // 保存权限(角色)
                .claim("authorities", "READ")
                // 用户名写入标题
                .setSubject(username)
                // 有效期设置
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                // 签名设置
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();

        // 将 JWT 写入 body
        try {
            response.setContentType("application/json");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getOutputStream().print("{\"token\":\"" + JWT + "\"}");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
项目:PepSIIrup-2017    文件:TokenAuthenticationService.java   
void addAuthentication(HttpServletResponse response, String username, Collection<? extends GrantedAuthority> authorities) throws IOException {
    List<String> roles = authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
    Claims claims = Jwts.claims()
            .setSubject(username)
            .setExpiration(new Date(System.currentTimeMillis() + expirationTime * 60 * 1000));
    claims.put(ROLE_KEY, roles.stream().collect(Collectors.joining(ROLE_DELIMITER)));

    String JWT = Jwts.builder()
            .setClaims(claims)
            .signWith(SignatureAlgorithm.HS512, secret)
            .compact();

    response.addHeader(headerString, headerStartWith + JWT);

    JwtAuthenticatedUser user = new JwtAuthenticatedUser(username, roles);

    PrintWriter printWriter = response.getWriter();
    printWriter.print(mapper.writeValueAsString(user));
    printWriter.flush();
}
项目:spring-mvc-react    文件:AuthorizationController.java   
@JsonView(Views.Public.class)
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity<?> login(@RequestBody LoginModel data) {
    User user = userService.getByUsername(data.getUsername());

    if (user == null) {
        return new ResponseEntity(new LoginResponseBody(false, null, "User with that name isn't exist"),
                HttpStatus.OK);
    }

    if (!Objects.equals(user.getPassword(), MD5.getHash(data.getPassword()))) {
        return new ResponseEntity(new LoginResponseBody(false, null, "wrong_password"),
                HttpStatus.OK);
    }

    String token = Jwts.builder()
            .setSubject(data.getUsername())
            .signWith(SignatureAlgorithm.HS512, key)
            .compact();

    return new ResponseEntity(new LoginResponseBody(true, token), HttpStatus.OK);
}
项目:spring-mvc-react    文件:AuthorizationController.java   
@JsonView(Views.Public.class)
@RequestMapping(value = "/register", method = RequestMethod.POST)
public ResponseEntity<?> register(@RequestBody LoginModel data) {

    User user = userService.getByUsername(data.getUsername());

    if (user != null) {
        return new ResponseEntity(new LoginResponseBody(false, null, "User with that name has already existed"),
                HttpStatus.OK);
    }

    User newUser = new User(data.getUsername(), MD5.getHash(data.getPassword()), new Date(), "active", 0);
    userService.addUser(newUser);

    String token = Jwts.builder()
            .setSubject(newUser.getUsername())
            .signWith(SignatureAlgorithm.HS512, key)
            .compact();

    return new ResponseEntity(new LoginResponseBody(true, token), HttpStatus.OK);
}
项目:xmanager    文件:JwtUtil.java   
/**
 * 创建jwt
 * @param id
 * @param subject
 * @param ttlMillis
 * @return
 * @throws Exception
 */
public String createJWT(String id, String subject, long ttlMillis) throws Exception {

    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);
    SecretKey key = generalKey();
    JwtBuilder builder = Jwts.builder()
            .setId(id)
            .setIssuedAt(now)
            .setSubject(subject)
            .signWith(signatureAlgorithm, key);
    if (ttlMillis >= 0) {
        long expMillis = nowMillis + ttlMillis;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp);
    }
    return builder.compact();
}
项目:sso-client    文件:SSOClientTest.java   
@Before
public void before(){
    String pk = org.apache.commons.codec.binary.Base64.encodeBase64String(keyPair.getPublic().getEncoded());

    stubFor(get("/oauth2/publickey").willReturn(aResponse().withStatus(200).withBody(pk)));

    JwtBuilder builder = jwtBuilder(System.currentTimeMillis()+3600*1000L)
            .signWith(SignatureAlgorithm.RS256,keyPair.getPrivate());
    jwtToken = builder.compact();

    SSOConfig config = new SSOConfig().autoConfigureUrls(baseUrl);
    config.setClientId("test");
    config.setClientSecret("test_secret");
    config.setResourceName("resourceName");
    config.setRedirectUri("http://www.example.com");
    client = new SSOClient(config);

    basicHeader = SSOUtils.encodeBasicAuthorizationHeader(config.getClientId(),config.getClientSecret());
}
项目:holon-core    文件:JwtUtils.java   
@SuppressWarnings("incomplete-switch")
private static String getAsymmetricKeyAlgorithm(SignatureAlgorithm sa) {
    switch (sa) {
    case ES256:
        return "EC";
    case ES384:
        return "EC";
    case ES512:
        return "EC";
    case PS256:
        return "RSA";
    case PS384:
        return "RSA";
    case PS512:
        return "RSA";
    case RS256:
        return "RSA";
    case RS384:
        return "RSA";
    case RS512:
        return "RSA";
    default:
        break;
    }
    return null;
}
项目:jersey-jwt    文件:AuthenticationTokenIssuer.java   
/**
 * Issue a JWT token
 *
 * @param authenticationTokenDetails
 * @return
 */
public String issueToken(AuthenticationTokenDetails authenticationTokenDetails) {

    return Jwts.builder()
            .setId(authenticationTokenDetails.getId())
            .setIssuer(settings.getIssuer())
            .setAudience(settings.getAudience())
            .setSubject(authenticationTokenDetails.getUsername())
            .setIssuedAt(Date.from(authenticationTokenDetails.getIssuedDate().toInstant()))
            .setExpiration(Date.from(authenticationTokenDetails.getExpirationDate().toInstant()))
            .claim(settings.getAuthoritiesClaimName(), authenticationTokenDetails.getAuthorities())
            .claim(settings.getRefreshCountClaimName(), authenticationTokenDetails.getRefreshCount())
            .claim(settings.getRefreshLimitClaimName(), authenticationTokenDetails.getRefreshLimit())
            .signWith(SignatureAlgorithm.HS256, settings.getSecret())
            .compact();
}
项目:MicroServiceDemo    文件:JwtTokenUtil.java   
public String generateToken(String username) {
    KeyUserInfo keyUserInfo = userRepository.findByEmail(username).get(0);
    if (keyUserInfo != null) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("roles", keyUserInfo.getRoles().toString());
        claims.put("id", keyUserInfo.getId());

        return TOKEN_PREFIX + " " + Jwts.builder()
                // subject是一种claims
                // setSubjects(...)
                .setClaims(claims)
                .setSubject(username)
                .setExpiration(new Date(currentTimeMillis() + EXPIRATIONTIME))
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }
    return null;
}
项目:product-management-system    文件:JwtService.java   
@Override
public TokenDto generate(final String username, final String password) {
    if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
        throw new BadCredentialsException("Input data can't be empty.");
    }
    final User user = userService.findByUsername(username);

    validateInputPassword(user.getPassword(), password);

    final Map<String, Object> tokenData = new HashMap<>();
    tokenData.put("username", user.getUsername());
    tokenData.put("password", user.getPassword());
    tokenData.put("create_date", LocalDateTime.now());
    final JwtBuilder jwtBuilder = Jwts.builder();
    jwtBuilder.setClaims(tokenData);
    final Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, expirationTime);
    jwtBuilder.setExpiration(calendar.getTime());
    final String token = jwtBuilder.signWith(SignatureAlgorithm.HS512, secretKey).compact();
    return new TokenDto(token, mapper.map(user, UserDto.class));
}
项目:infotaf    文件:JwtTokenFactory.java   
/**
 * Factory method for issuing new JWT Tokens.
 * 
 * @param username
 * @param roles
 * @return
 */
public AccessJwtToken createAccessJwtToken(UserContext userContext) {
    if (StringUtils.isBlank(userContext.getUsername())) 
        throw new IllegalArgumentException("Cannot create JWT Token without username");

    if (userContext.getAuthorities() == null || userContext.getAuthorities().isEmpty()) 
        throw new IllegalArgumentException("User doesn't have any privileges");

    Claims claims = Jwts.claims().setSubject(userContext.getUsername());
    claims.put("scopes", userContext.getAuthorities().stream().map(s -> s.toString()).collect(Collectors.toList()));

    LocalDateTime currentTime = LocalDateTime.now();

    String token = Jwts.builder()
      .setClaims(claims)
      .setIssuer(AppConfig.prop.getProperty("security.tokenIssuer"))
      .setIssuedAt(Date.from(currentTime.atZone(ZoneId.systemDefault()).toInstant()))
      .setExpiration(Date.from(currentTime
          .plusMinutes(Long.parseLong(AppConfig.prop.getProperty("security.tokenExpirationTime")))
          .atZone(ZoneId.systemDefault()).toInstant()))
      .signWith(SignatureAlgorithm.HS512, AppConfig.prop.getProperty("security.tokenSigningKey"))
    .compact();

    return new AccessJwtToken(token, claims);
}
项目:infotaf    文件:JwtTokenFactory.java   
public JwtToken createRefreshToken(UserContext userContext) {
    if (StringUtils.isBlank(userContext.getUsername())) {
        throw new IllegalArgumentException("Cannot create JWT Token without username");
    }

    LocalDateTime currentTime = LocalDateTime.now();

    Claims claims = Jwts.claims().setSubject(userContext.getUsername());
    claims.put("scopes", Arrays.asList(Scopes.REFRESH_TOKEN.authority()));

    String token = Jwts.builder()
      .setClaims(claims)
      .setIssuer(AppConfig.prop.getProperty("security.tokenIssuer"))
      .setId(UUID.randomUUID().toString())
      .setIssuedAt(Date.from(currentTime.atZone(ZoneId.systemDefault()).toInstant()))
      .setExpiration(Date.from(currentTime
          .plusMinutes(Long.parseLong(AppConfig.prop.getProperty("security.refreshTokenExpTime")))
          .atZone(ZoneId.systemDefault()).toInstant()))
      .signWith(SignatureAlgorithm.HS512, AppConfig.prop.getProperty("security.tokenSigningKey"))
    .compact();

    return new AccessJwtToken(token, claims);
}
项目:stateless-shiro    文件:TokenRepositoryImpl.java   
@Override
public String createAuthenticationToken(String email) {
    LocalDate currentDate = LocalDate.now();
    LocalDate nextMoth = currentDate.plusMonths(1) ;
    Date date = Date.from(nextMoth.atStartOfDay(ZoneId.systemDefault()).toInstant());
    String jwtToken = Jwts.builder()
            .setSubject(email)
            .setExpiration(date)
            .signWith(
                    SignatureAlgorithm.HS256,
                    SECURET.getBytes()
           )
            .compact();

    DBAuthenticationToken dbAuthenticationToken = new DBAuthenticationToken(email, jwtToken) ;
    tokenMapper.insert(dbAuthenticationToken);
    return jwtToken;
}
项目:iotplatform    文件:JwtTokenFactory.java   
public JwtToken createRefreshToken(SecurityUser securityUser) {
  if (StringUtils.isBlank(securityUser.getEmail())) {
    throw new IllegalArgumentException("Cannot create JWT Token without username/email");
  }

  DateTime currentTime = new DateTime();

  UserPrincipal principal = securityUser.getUserPrincipal();
  Claims claims = Jwts.claims().setSubject(principal.getValue());
  claims.put(SCOPES, Arrays.asList(Authority.REFRESH_TOKEN.name()));
  claims.put(USER_ID, securityUser.getId().getId().toString());
  claims.put(IS_PUBLIC, principal.getType() == UserPrincipal.Type.PUBLIC_ID);

  String token = Jwts.builder().setClaims(claims).setIssuer(settings.getTokenIssuer())
      .setId(UUID.randomUUID().toString()).setIssuedAt(currentTime.toDate())
      .setExpiration(currentTime.plusSeconds(settings.getRefreshTokenExpTime()).toDate())
      .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey()).compact();

  return new AccessJwtToken(token, claims);
}
项目:jhipster-microservices-example    文件:TokenProviderTest.java   
private String createTokenWithDifferentSignature() {
    return Jwts.builder()
        .setSubject("anonymous")
        .signWith(SignatureAlgorithm.HS512, "e5c9ee274ae87bc031adda32e27fa98b9290da90")
        .setExpiration(new Date(new Date().getTime() + ONE_MINUTE))
        .compact();
}
项目:rest-api-jwt-spring-security    文件:JwtTokenUtil.java   
private String doGenerateToken(Map<String, Object> claims, String subject, String audience) {
    final Date createdDate = timeProvider.now();
    final Date expirationDate = calculateExpirationDate(createdDate);

    System.out.println("doGenerateToken " + createdDate);

    return Jwts.builder()
            .setClaims(claims)
            .setSubject(subject)
            .setAudience(audience)
            .setIssuedAt(createdDate)
            .setExpiration(expirationDate)
            .signWith(SignatureAlgorithm.HS512, secret)
            .compact();
}
项目:SistemaAlmoxarifado    文件:Token.java   
public static String Gerate(String issuer, int idSubject, int hours) {

        //The JWT signature algorithm we will be using to sign the token
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        //Hours to milliseconds
        long ttlMillis = hours * 3600000;
        String subject = String.valueOf(idSubject);

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //We will sign our JWT with our ApiKey secret
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(Parameters.TOKENKEY);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //Let's set the JWT Claims
        JwtBuilder builder = Jwts.builder().setIssuedAt(now)
                                    .setSubject(subject)
                                    .setIssuer(issuer)
                                    .signWith(signatureAlgorithm, signingKey);

        //if it has been specified, let's add the expiration
        if (ttlMillis >= 0) {
        long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }

        //Builds the JWT and serializes it to a compact, URL-safe string
        return builder.compact();
    }
项目:springboot-rest-api-skeleton    文件:JwtTokenUtil.java   
private String doGenerateToken(Map<String, Object> claims) {
    final Date createdDate = (Date) claims.get(CLAIM_KEY_CREATED);
    final Date expirationDate = new Date(createdDate.getTime() + expiration * 1000);

    System.out.println("doGenerateToken " + createdDate);

    return Jwts.builder()
            .setClaims(claims)
            .setExpiration(expirationDate)
            .signWith(SignatureAlgorithm.HS512, secret)
            .compact();
}
项目:hauth-java    文件:JwtService.java   
public static void addAuthentication(HttpServletResponse response, String username) throws IOException {
    UserDetailsEntity userDetailsEntity = jwtService.userDetailsService.findById(username);

    if (userDetailsEntity == null) {
        logger.info("用户{}不存在:", username);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // 生成JWT
    String JWT = Jwts.builder().signWith(SignatureAlgorithm.HS256, SECRET)
            .setHeaderParam("alg", "HS256")
            .setHeaderParam("typ", "JWT")
            // 有效期设置
            .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
            // 用户名写入标题
            .setIssuer("hzwy23")
            .claim("UserId", userDetailsEntity.getUser_id())
            .claim("DomainId", userDetailsEntity.getDomain_id())
            .claim("OrgUnitId", userDetailsEntity.getOrg_unit_id())
            // 保存权限(角色)
            .claim("authorities", JWT_ROLES)
            // 签名设置
            .compact();
    responseJWT(response, JWT);

}
项目:Alpine    文件:JsonWebToken.java   
/**
 * Creates a new JWT for the specified principal. Token is signed using
 * the SecretKey with an HMAC 256 algorithm.
 *
 * @param principal the Principal to create the token for
 * @return a String representation of the generated token
 * @since 1.0.0
 */
public String createToken(Principal principal) {
    final Date today = new Date();
    final JwtBuilder jwtBuilder = Jwts.builder();
    jwtBuilder.setSubject(principal.getName());
    jwtBuilder.setIssuer("Alpine");
    jwtBuilder.setIssuedAt(today);
    jwtBuilder.setExpiration(addDays(today, 7));
    return jwtBuilder.signWith(SignatureAlgorithm.HS256, key).compact();
}
项目:single-sign-on-out-auth-jwt-cookie-redis-springboot-freemarker    文件:JwtUtil.java   
public static String generateToken(String signingKey, String subject) {
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);

    JwtBuilder builder = Jwts.builder()
            .setSubject(subject)
            .setIssuedAt(now)
            .signWith(SignatureAlgorithm.HS256, signingKey);

    String token = builder.compact();

    RedisUtil.INSTANCE.sadd(REDIS_SET_ACTIVE_SUBJECTS, subject);

    return token;
}
项目:digag-server    文件:JwtTokenUtil.java   
private String generateToken(Map<String, Object> claims) {
    return Jwts.builder()
            .setClaims(claims)
            .setExpiration(generateExpirationDate())
            .signWith(SignatureAlgorithm.HS512, secret)
            .compact();
}
项目:generator-spring-rest-jwt    文件:_JwtTokenUtil.java   
String generateToken(Map<String, Object> claims) {
    return Jwts.builder()
            .setClaims(claims)
            .setExpiration(generateExpirationDate())
            .signWith(SignatureAlgorithm.HS512, secret)
            .compact();
}
项目:lightrail-client-java    文件:LightrailClientTokenFactory.java   
public static String generate(String shopperId, Integer validitySeconds) throws IOException {

        JwtBuilder builder = Jwts.builder();
        String apiKey = Lightrail.apiKey;
        String secret = Lightrail.clientSecret;

        if (apiKey == null)
            throw new BadParameterException("Lightrail.apiKey is not set.");
        if (secret == null)
            throw new BadParameterException("Lightrail.clientSecret is not set.");

        String payload = apiKey.substring(apiKey.indexOf(".") + 1);
        payload = payload.substring(0, payload.indexOf("."));

        payload = new String(new BASE64Decoder().decodeBuffer(payload));
        JsonObject jsonObject = new Gson().fromJson(payload, JsonObject.class);
        String gui = jsonObject.get("g").getAsJsonObject().get("gui").getAsString();

        Map<String, Object> claims = new HashMap<String, Object>();
        Long iat = System.currentTimeMillis()/1000;
        claims.put("iat", iat);
        claims.put("shopperId", shopperId);

        Map<String, Object> gClaims = new HashMap<String, Object>();
        gClaims.put("gui", gui);
        claims.put("g", gClaims);

        if (validitySeconds != null) {
            Long exp = iat + validitySeconds;
            claims.put("exp", exp);
        }
        return builder.setClaims(claims)
                .setHeaderParam("typ", "JWT")
                .signWith(SignatureAlgorithm.HS256, secret.getBytes("UTF-8"))
                .compact();
    }
项目:spring-boot-jwt    文件:JwtTokenProvider.java   
public String createToken(String username, List<Role> roles) {

    Claims claims = Jwts.claims().setSubject(username);
    claims.put("auth", roles.stream().map(s -> new SimpleGrantedAuthority(s.getAuthority())).filter(Objects::nonNull).collect(Collectors.toList()));

    Date now = new Date();
    Date validity = new Date(now.getTime() + validityInMilliseconds);

    return Jwts.builder()//
        .setClaims(claims)//
        .setIssuedAt(now)//
        .setExpiration(validity)//
        .signWith(SignatureAlgorithm.HS256, secretKey)//
        .compact();
  }
项目:TorgCRM-Server    文件:TokenProviderTest.java   
private String createTokenWithDifferentSignature() {
    return Jwts.builder()
        .setSubject("anonymous")
        .signWith(SignatureAlgorithm.HS512, "e5c9ee274ae87bc031adda32e27fa98b9290da90")
        .setExpiration(new Date(new Date().getTime() + ONE_MINUTE))
        .compact();
}
项目:ARCLib    文件:JwtTokenProvider.java   
public String generateToken(UserDetails user) {

        Map<String, Object> claims = handler.createClaims(user);

        Instant now = Instant.now();
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(Date.from(now))
                .setExpiration(Date.from(now.plusSeconds(expiration)))
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();

    }
项目:Taxi-Datalogger    文件:MqttAuthentication.java   
public char[] createJwt(String projectId)
    throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
  DateTime now = new DateTime();

  // Create a JWT to authenticate this device. The device will be disconnected after the token
  // expires, and will have to reconnect with a new token. The audience field should always
  // be set to the GCP project id.
  JwtBuilder jwtBuilder =
      Jwts.builder()
          .setIssuedAt(now.toDate())
          .setExpiration(now.plusMinutes(60).toDate())
          .setAudience(projectId);

  return jwtBuilder.signWith(SignatureAlgorithm.RS256, privateKey).compact().toCharArray();
}
项目:spring-io    文件:TokenProviderTest.java   
private String createTokenWithDifferentSignature() {
    return Jwts.builder()
        .setSubject("anonymous")
        .signWith(SignatureAlgorithm.HS512, "e5c9ee274ae87bc031adda32e27fa98b9290da90")
        .setExpiration(new Date(new Date().getTime() + ONE_MINUTE))
        .compact();
}
项目:spring-io    文件:TokenProviderTest.java   
private String createTokenWithDifferentSignature() {
    return Jwts.builder()
        .setSubject("anonymous")
        .signWith(SignatureAlgorithm.HS512, "e5c9ee274ae87bc031adda32e27fa98b9290da90")
        .setExpiration(new Date(new Date().getTime() + ONE_MINUTE))
        .compact();
}
项目:bxbot-ui-server    文件:JwtUtils.java   
private String generateToken(Map<String, Object> claims) {

        final Date issuedAtDate = (Date) claims.get(CLAIM_KEY_ISSUED_AT);
        final Date expirationDate = new Date(issuedAtDate.getTime() + (expirationInSecs * 1000));

        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(expirationDate)
                .setIssuedAt(issuedAtDate) // TODO Possible bug in jjwt - if this not set to override claims value, date is WAY in the future...
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }
项目:spring-jwt-starter    文件:JwtTokenUtil.java   
String generateToken(Map<String, Object> claims) {
    return Jwts.builder()
            .setClaims(claims)
            .setExpiration(generateExpirationDate())
            .signWith(SignatureAlgorithm.HS512, secret)
            .compact();
}