@PostMapping("/register") public Result register(@RequestBody RegisterForm registerForm) { if (registerForm == null || StringUtils.isBlank(registerForm.getUsername()) || StringUtils.isBlank(registerForm.getEmail()) || StringUtils.isBlank(registerForm.getPassword()) || StringUtils.isBlank(registerForm.getConfirmPassword())) { return Result.fail(ResultCode.PARAMS_ERROR); } if (!registerForm.getPassword().equals(registerForm.getConfirmPassword())) { return Result.fail("两次输入的密码不匹配"); } User user = new User(); BeanUtils.copyProperties(registerForm, user); String salt = UUID.nameUUIDFromBytes(user.getUsername().getBytes()).toString(); user.setSalt(salt); user.setPassword(EncryptUtils.encryptPassword(user.getPassword(), user.getCredential())); Role role = roleRepository.findByRoleName("user"); Assert.notNull(role, "role[user] is null!"); user.getRoles().add(role); userRepository.save(user); return Result.ok(); }
@Override public int save(User model) { logger.info("[UserService->save] start username is {} ...", model.getUsername()); Assert.hasText(model.getUsername(), "请输入用户名"); if (findBy("username", model.getUsername()) != null) { throw new ServiceException("用户名不允许重复"); } String password = model.getPassword(); model.setVersion(0); model.setUserType(UserType.USER.value()); String mysalt = new BCryptPasswordEncoder().encode(password); model.setPassword(BCrypt.hashpw(password, mysalt)); int rtn = super.save(model); userAuthorityService.grantNormalAuth(model.getId()); logger.info("[UserService->save] end username is {} ...", model.getUsername()); return rtn; }
@Override public int saveAndAssign(Order order, Long userId) { logger.info("[OrderServiceImpl->saveAndAssign] start ..."); Assert.notNull(userId, "用户不允许空"); order.setOrderStatus(OrderStatus.UNEXECUTED.getCode()); save(order); OrderTask orderTask = new OrderTask(); orderTask.setOrderId(order.getId()); orderTask.setUserId(userId); orderTask.setTaskStatus(OrderStatus.UNEXECUTED.getCode()); int rtn = orderTaskService.save(orderTask); logger.info("[OrderServiceImpl->saveAndAssign] end ..."); return rtn; }
public ForwardedUserFilter(String headerName, Function<HttpServletRequest, User> userFactory, Collection<String> requestAttributeNames) { Assert.hasText(headerName, "headerName cannot be null or empty."); Assert.notNull(userFactory, "userFactory function cannot be null."); this.headerName = headerName; this.userFactory = userFactory; //always ensure that the fully qualified interface name is accessible: LinkedHashSet<String> set = new LinkedHashSet<>(); set.add(User.class.getName()); if (!Collections.isEmpty(requestAttributeNames)) { set.addAll(requestAttributeNames); } this.requestAttributeNames = set; }
@Override public User apply(HttpServletRequest request) { String value = request.getHeader(headerName); Assert.hasText(value, "header value cannot be null or empty."); User user; try { user = headerValueToUser.apply(value); } catch (Exception e) { String msg = "Unable to determine request User based on " + headerName + " header value [" + value + "] when invoking headerValue-to-User conversion function: " + e.getMessage(); throw new IllegalStateException(msg, e); } Assert.state(user != null, "User instance returned from headerValue-to-User conversion " + "function cannot be null."); return user; }
/** * {@inheritDoc} */ @Override public String issueJwt(String subject, Map<String, Object> claims) { Assert.hasText(subject, "Subject can't be null or empty!!"); Instant now = Instant.now(); JwtBuilder jwtBuilder = Jwts.builder() .setHeaderParam(TYPE, JWT_TYPE) .setClaims(claims) .setSubject(subject) .setIssuer(this.jwtConfig.issuer()) .setIssuedAt(Date.from(now)) .setExpiration(Date.from(now.plus(this.jwtConfig.expirationTime(), MINUTES))) .setId(UUID.randomUUID().toString()); this.signWith(jwtBuilder); return jwtBuilder.compact(); }
/** * {@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; }
@Override public boolean isValid(byte[] data, byte[] signature) { if (key instanceof PublicKey) { Signature sig = createSignatureInstance(); PublicKey publicKey = (PublicKey) key; try { return doVerify(sig, publicKey, data, signature); } catch (Exception e) { String msg = "Unable to verify RSA signature using configured PublicKey. " + e.getMessage(); throw new SignatureException(msg, e); } } else { Assert.notNull(this.SIGNER, "RSA Signer instance cannot be null. This is a bug. Please report it."); byte[] computed = this.SIGNER.sign(data); return Arrays.equals(computed, signature); } }
/** * Generates a new secure-random secret key of a length suitable for creating and verifying HMAC signatures * according to the specified {@code SignatureAlgorithm} using the specified SecureRandom number generator. This * implementation returns secure-random key sizes as follows: * * <table> <caption>Key Sizes</caption> <thead> <tr> <th>Signature Algorithm</th> <th>Generated Key Size</th> </tr> </thead> <tbody> <tr> * <td>HS256</td> <td>256 bits (32 bytes)</td> </tr> <tr> <td>HS384</td> <td>384 bits (48 bytes)</td> </tr> <tr> * <td>HS512</td> <td>512 bits (64 bytes)</td> </tr> </tbody> </table> * * @param alg the signature algorithm that will be used with the generated key * @param random the secure random number generator used during key generation * @return a new secure-random secret key of a length suitable for creating and verifying HMAC signatures according * to the specified {@code SignatureAlgorithm} using the specified SecureRandom number generator. * @see #generateKey() * @see #generateKey(SignatureAlgorithm) * @since 0.5 */ public static SecretKey generateKey(SignatureAlgorithm alg, SecureRandom random) { Assert.isTrue(alg.isHmac(), "SignatureAlgorithm argument must represent an HMAC algorithm."); byte[] bytes; switch (alg) { case HS256: bytes = new byte[32]; break; case HS384: bytes = new byte[48]; break; default: bytes = new byte[64]; } random.nextBytes(bytes); return new SecretKeySpec(bytes, alg.getJcaName()); }
@Override public SignatureValidator createSignatureValidator(SignatureAlgorithm alg, Key key) { Assert.notNull(alg, "SignatureAlgorithm cannot be null."); Assert.notNull(key, "Signing Key cannot be null."); switch (alg) { case HS256: case HS384: case HS512: return new MacValidator(alg, key); case RS256: case RS384: case RS512: case PS256: case PS384: case PS512: return new RsaSignatureValidator(alg, key); case ES256: case ES384: case ES512: return new EllipticCurveSignatureValidator(alg, key); default: throw new IllegalArgumentException("The '" + alg.name() + "' algorithm cannot be used for signing."); } }
@Override public Signer createSigner(SignatureAlgorithm alg, Key key) { Assert.notNull(alg, "SignatureAlgorithm cannot be null."); Assert.notNull(key, "Signing Key cannot be null."); switch (alg) { case HS256: case HS384: case HS512: return new MacSigner(alg, key); case RS256: case RS384: case RS512: case PS256: case PS384: case PS512: return new RsaSigner(alg, key); case ES256: case ES384: case ES512: return new EllipticCurveSigner(alg, key); default: throw new IllegalArgumentException("The '" + alg.name() + "' algorithm cannot be used for signing."); } }
@Override public JwtBuilder claim(String name, Object value) { Assert.hasText(name, "Claim property name cannot be null or empty."); if (this.claims == null) { if (value != null) { ensureClaims().put(name, value); } } else { if (value == null) { this.claims.remove(name); } else { this.claims.put(name, value); } } return this; }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { StatelessToken token = (StatelessToken) authenticationToken; Assert.notNull(authenticationToken, "token is null!"); String username = (String) token.getPrincipal(); User user = userRepository.findByUsername(username); if (user == null) { throw new UnknownAccountException(String.format("user '%s' not found.", username)); } String accessToken = (String) token.getCredentials(); return new SimpleAuthenticationInfo(username, accessToken, getName()); }
@Override public int excute(Long orderId, Integer orderStatus) { Assert.notNull(orderId, "必须传入用户id"); Order order = findById(orderId); if (order == null) { throw new ServiceException("查无订单"); } order.setOrderStatus(orderStatus); int rtn = update(order); return rtn; }
public JwsToUserDetailsConverter(Function<String, Claims> claimsExtractor, Function<Claims, User> claimsUserFactory, Function<Claims, Collection<? extends GrantedAuthority>> authoritiesResolver) { Assert.notNull(claimsExtractor, "claimsExtractor cannot be null."); Assert.notNull(claimsUserFactory, "claimsUserFactory cannot be null."); this.claimsExtractor = claimsExtractor; this.claimsUserFactory = claimsUserFactory; this.authoritiesResolver = authoritiesResolver; }
public GuestFallbackUserFactory(Function<HttpServletRequest, User> delegate, Function<HttpServletRequest, User> guestFallback) { Assert.notNull(delegate, "delegate function cannot be null"); Assert.notNull(guestFallback, "guestFallback function cannot be null"); this.delegate = delegate; this.guestFallback = guestFallback; }
public ImmutablePhone(String number, String name, String description, boolean verified) { Assert.hasText(number, "number argument cannot be null or empty."); this.number = number; this.digitString = digitsOnly(number); this.name = name; this.description = description; this.verified = verified; }
public JwsClaimsExtractor(byte[] hmacSigningKeyBytes) { Assert.isTrue(hmacSigningKeyBytes != null && hmacSigningKeyBytes.length > 0, "hmacSigningKeyByte array argument cannot be null or empty."); this.signingKeyBytes = hmacSigningKeyBytes; this.signingKey = null; this.signingKeyResolver = null; }
static SignatureAlgorithm getAlgorithm(byte[] hmacSigningKeyBytes) { Assert.isTrue(hmacSigningKeyBytes != null && hmacSigningKeyBytes.length > 0, "hmacSigningBytes cannot be null or empty."); if (hmacSigningKeyBytes.length >= 64) { return SignatureAlgorithm.HS512; } else if (hmacSigningKeyBytes.length >= 48) { return SignatureAlgorithm.HS384; } else { //<= 32 return SignatureAlgorithm.HS256; } }
@Test public void encryptAndDecryptToken(){ final Map<String,Object> tokenData=new HashMap<String,Object>(){ { put("userName","Adarsh"); put("expire", DateTime.now().plusDays(1).getMillis()); } }; final String token = this.jwtTokenProvider.getTokenFromValue(tokenData); Assert.notNull(token,"Token is Empty"); LOGGER.info("Token ",token); final Map<String,Object> tokenDataDecrypt=this.jwtTokenProvider.getTokenValue(token); Assert.notNull(token,"Token is Empty"); LOGGER.info("Token Data ",tokenDataDecrypt); }
public JwtAuthenticationToken(UUID userId, String email, Collection<? extends GrantedAuthority> authorities) { Assert.notEmpty(authorities, "Cannot construct JWT with empty authorities"); this.userId = userId; this.email = email; this.roles = authorities; this.authenticated = true; }
@Override public Key resolveSigningKey(JwsHeader header, Claims claims) { SignatureAlgorithm alg = SignatureAlgorithm.forName(header.getAlgorithm()); Assert.isTrue(alg.isHmac(), "The default resolveSigningKey(JwsHeader, Claims) implementation cannot be " + "used for asymmetric key algorithms (RSA, Elliptic Curve). " + "Override the resolveSigningKey(JwsHeader, Claims) method instead and return a " + "Key instance appropriate for the " + alg.name() + " algorithm."); byte[] keyBytes = resolveSigningKeyBytes(header, claims); return new SecretKeySpec(keyBytes, alg.getJcaName()); }
@Override public Key resolveSigningKey(JwsHeader header, String plaintext) { SignatureAlgorithm alg = SignatureAlgorithm.forName(header.getAlgorithm()); Assert.isTrue(alg.isHmac(), "The default resolveSigningKey(JwsHeader, String) implementation cannot be " + "used for asymmetric key algorithms (RSA, Elliptic Curve). " + "Override the resolveSigningKey(JwsHeader, String) method instead and return a " + "Key instance appropriate for the " + alg.name() + " algorithm."); byte[] keyBytes = resolveSigningKeyBytes(header, plaintext); return new SecretKeySpec(keyBytes, alg.getJcaName()); }
public MacSigner(SignatureAlgorithm alg, Key key) { super(alg, key); Assert.isTrue(alg.isHmac(), "The MacSigner only supports HMAC signature algorithms."); if (!(key instanceof SecretKey)) { String msg = "MAC signatures must be computed and verified using a SecretKey. The specified key of " + "type " + key.getClass().getName() + " is not a SecretKey."; throw new IllegalArgumentException(msg); } }
@Override public JwtParser require(String claimName, Object value) { Assert.hasText(claimName, "claim name cannot be null or empty."); Assert.notNull(value, "The value cannot be null for claim name: " + claimName); expectedClaims.put(claimName, value); return this; }
/** * Asserts that payload is not null and calls {@link #doCompress(byte[]) doCompress} * * @param payload bytes to compress * @return compressed bytes * @throws CompressionException if {@link #doCompress(byte[]) doCompress} throws an IOException */ @Override public final byte[] compress(byte[] payload) { Assert.notNull(payload, "payload cannot be null."); try { return doCompress(payload); } catch (IOException e) { throw new CompressionException("Unable to compress payload.", e); } }
/** * Asserts the compressed bytes is not null and calls {@link #doDecompress(byte[]) doDecompress} * * @param compressed compressed bytes * @return decompressed bytes * @throws CompressionException if {@link #doDecompress(byte[]) doDecompress} throws an IOException */ @Override public final byte[] decompress(byte[] compressed) { Assert.notNull(compressed, "compressed bytes cannot be null."); try { return doDecompress(compressed); } catch (IOException e) { throw new CompressionException("Unable to decompress bytes.", e); } }
@Override public JwtBuilder signWith(SignatureAlgorithm alg, byte[] secretKey) { Assert.notNull(alg, "SignatureAlgorithm cannot be null."); Assert.notEmpty(secretKey, "secret key byte array cannot be null or empty."); Assert.isTrue(alg.isHmac(), "Key bytes may only be specified for HMAC signatures. If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead."); this.algorithm = alg; this.keyBytes = secretKey; return this; }
@Override public JwtBuilder signWith(SignatureAlgorithm alg, String base64EncodedSecretKey) { Assert.hasText(base64EncodedSecretKey, "base64-encoded secret key cannot be null or empty."); Assert.isTrue(alg.isHmac(), "Base64-encoded key bytes may only be specified for HMAC signatures. If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead."); byte[] bytes = TextCodec.BASE64.decode(base64EncodedSecretKey); return signWith(alg, bytes); }
@Override public JwtBuilder signWith(SignatureAlgorithm alg, Key key) { Assert.notNull(alg, "SignatureAlgorithm cannot be null."); Assert.notNull(key, "Key argument cannot be null."); this.algorithm = alg; this.key = key; return this; }
@Override public List<BaseStudy> findAllByClassName(@NotNull String className) { Assert.notNull("ClassName query cannot be null"); Assert.isTrue(Study.class.getSimpleName().equals(className) || HarmonizationStudy.class.getSimpleName().equals(className)); return executeRqlQuery(String.format("generic(eq(className,%s),limit(0,%s))", className, MAX_SIZE)); }
@NotNull BaseStudy fromDto(@NotNull Mica.StudyDtoOrBuilder dto) { Assert.isTrue(dto.hasExtension(Mica.CollectionStudyDto.type) || dto.hasExtension(Mica.HarmonizationStudyDto.type), "StudyDto must of a type extension."); BaseStudy study = dto.hasExtension(Mica.CollectionStudyDto.type) ? new Study() : new HarmonizationStudy(); if(dto.hasId()) study.setId(dto.getId()); if(dto.getNameCount() > 0) study.setName(localizedStringDtos.fromDto(dto.getNameList())); if(dto.getAcronymCount() > 0) study.setAcronym(localizedStringDtos.fromDto(dto.getAcronymList())); if(dto.hasLogo()) study.setLogo(attachmentDtos.fromDto(dto.getLogo())); if(dto.hasTimestamps()) TimestampsDtos.fromDto(dto.getTimestamps(), study); if(dto.getObjectivesCount() > 0) study.setObjectives(localizedStringDtos.fromDto(dto.getObjectivesList())); if(dto.hasOpal()) study.setOpal(dto.getOpal()); if(dto.getMembershipsCount() > 0) { Map<String, List<Membership>> memberships = Maps.newHashMap(); dto.getMembershipsList().forEach(e -> memberships.put(e.getRole(), e.getMembersList().stream().map(p -> new Membership(personDtos.fromDto(p), e.getRole())).collect(toList()))); study.setMemberships(memberships); } if (dto.getPopulationsCount() > 0) { study.setPopulations(dto.getPopulationsList().stream().map(populationDtos::fromDto) .collect(Collectors.toCollection(TreeSet<org.obiba.mica.study.domain.Population>::new))); } if (dto.hasContent() && !Strings.isNullOrEmpty(dto.getContent())) study.setModel(JSONUtils.toMap(dto.getContent())); else study.setModel(new HashMap<>()); return study; }
public RequestHeaderUserFactory(String headerName, Function<String, User> headerValueToUserConverter) { Assert.hasText(headerName, "headerName argument cannot be null or empty."); Assert.notNull(headerValueToUserConverter, "headerValueToUserConverter function cannot be null."); this.headerName = headerName; this.headerValueToUser = headerValueToUserConverter; }
public JwsClaimsExtractor(Key key) { Assert.notNull(key, "key argument cannot be null."); this.signingKey = key; this.signingKeyBytes = null; this.signingKeyResolver = null; }
public JwsClaimsExtractor(SigningKeyResolver signingKeyResolver) { Assert.notNull(signingKeyResolver, "signingKeyResolver argument cannot be null."); this.signingKeyResolver = signingKeyResolver; this.signingKeyBytes = null; this.signingKey = null; }
public ConfigJwkResolver(ResourceLoader resourceLoader) { Assert.notNull(resourceLoader); this.resourceLoader = resourceLoader; }
public ClaimValueResolver(Function<Claims, ?> delegate, boolean resultRequired) { Assert.notNull(delegate, "delegate function cannot be null."); this.delegate = delegate; this.resultRequired = resultRequired; }
public FallbackSigningKeyResolver(SigningKeyResolver delegate, Key fallbackKey) { Assert.notNull(delegate, "SigningKeyResolver argument cannot be null."); Assert.notNull(fallbackKey, "fallbackKey argument cannot be null."); this.delegate = delegate; this.fallbackKey = fallbackKey; }
public DefaultResource(InputStream is, String name) { Assert.notNull(is, "InputStream cannot be null."); Assert.hasText(name, "String name argument cannot be null or empty."); this.is = is; this.name = name; }