프로젝트 할때마다 로그인기능... 너무 지겨워서 다른 방법으로 사용자 인증 하는 방법을 찾아보다가 이 글을 쓰게 되었습니다.
바로 QR로 로그인하기!!
// QR 라이브러리
implementation group: 'com.google.zxing', name: 'core', version: '3.3.3'
// QR 라이브러리
implementation group: 'com.google.zxing', name: 'javase', version: '3.4.0'
// AWS S3
implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE'
spring:
jpa:
hibernate:
ddl-auto: create
show-sql: true
properties:
hibernate:
dialect: org.hibernate.dialect.Mysql8Dialect
defer-datasource-initialization: true
--data.sql 사용한다면--
sql:
init:
mode: always
--data.sql--
datasource:
url: jdbc:mysql://RDS 엔드포인트:3306/DB에서 사용할 스키마 이름
username: RDS 유저이름
password: RDS 비밀번호
driver-class-name: com.mysql.cj.jdbc.Driver
cloud:
aws:
credentials:
access-key: 발급받은 Access key
secret-key: 발급받은 Secret key
s3:
bucket: S3 버킷이름
region:
static: ap-northeast-2
stack:
auto: false
@RestController
public class QrController {
@GetMapping("/make")
public String makeQr() throws WriterException {
String url = "인증완료 화면이 있는 이미지 링크";
//QR 생성
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(url, BarcodeFormat.QR_CODE, 100, 100);
BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
//파일이 덮어씌워지는 것을 방지하기위해 날짜 데이터 추가
String datetimeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
String fileName = datetimeStr + "_QR.png";
String qrURL = qrService.uploadImageFileToAwsS3(bufferedImage, "png", fileName);
return qrURL;
}
}
@Configuration
public class AwsS3Config {
@Value("${cloud.aws.credentials.access-key}")
private String accessKey;
@Value("${cloud.aws.credentials.secret-key}")
private String secretKey;
@Value("${cloud.aws.region.static}")
private String region;
@Bean
public AmazonS3Client amazonS3Client() {
BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey, secretKey);
AmazonS3Client build = (AmazonS3Client) AmazonS3ClientBuilder.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.build();
return build;
}
}
@Slf4j
@Service
@RequiredArgsConstructor
public class QRService {
@Value("${cloud.aws.s3.bucket}")
private String bucket;
@Autowired
private AmazonS3Client amazonS3Client;
public String uploadImageFileToAwsS3(BufferedImage bufferedImage, String contentType, String fileName)
throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
String imgFileExt = contentType.substring(contentType.indexOf("/") + 1);
ImageIO.write(bufferedImage, imgFileExt, byteArrayOutputStream);
// set metadata
ObjectMetadata objectMetadata = new ObjectMetadata();
byte[] bytes = byteArrayOutputStream.toByteArray();
objectMetadata.setContentLength(bytes.length);
objectMetadata.setContentType(contentType);
try (InputStream inputStream = new ByteArrayInputStream(bytes)) {
return this.createFile(fileName, inputStream, objectMetadata);
} catch (IOException e) {
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "S3 이미지 업로드에 실패했습니다.");
}
}
// 이미지 업로드 후 S3 URL 제공
private String createFile(String fileName, InputStream inputStream, ObjectMetadata objectMetadata) {
amazonS3Client.putObject(new PutObjectRequest(bucket, fileName, inputStream, objectMetadata)
.withCannedAcl(CannedAccessControlList.PublicRead));
log.info("AmazonS3 putObject file complete!");
return amazonS3Client.getUrl(bucket, fileName).toString();
}
}
S3는 지워버려서 결과화면을 못 보여주는데 
S3에 저장된 큐알코드 이미지 링크가 리턴되고 받은 링크로 들어가면 큐알코드 화면이 보여집니다.
프론트에 링크를 전달하면 잘 꺼내와서 쓴다고 하네요~~ㅋㅋ
잘 읽었습니다. 좋은 정보 감사드립니다.