SpringBoot2로 Rest api 만들기(8) – SpringSecurity를 이용한 api 인증 및 권한부여
This commit is contained in:
59
src/main/java/com/rest/api/controller/v1/SignController.java
Normal file
59
src/main/java/com/rest/api/controller/v1/SignController.java
Normal file
@@ -0,0 +1,59 @@
|
||||
package com.rest.api.controller.v1;
|
||||
|
||||
import com.rest.api.advice.exception.CEmailSigninFailedException;
|
||||
import com.rest.api.entity.User;
|
||||
import com.rest.api.filter.JwtTokenProvider;
|
||||
import com.rest.api.model.response.CommonResult;
|
||||
import com.rest.api.model.response.SingleResult;
|
||||
import com.rest.api.repo.UserJpaRepo;
|
||||
import com.rest.api.service.ResponseService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import io.swagger.annotations.ApiParam;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
@Api(tags = {"1. Sign"})
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping(value = "/v1")
|
||||
public class SignController {
|
||||
|
||||
private final UserJpaRepo userJpaRepo;
|
||||
private final JwtTokenProvider jwtTokenProvider;
|
||||
private final ResponseService responseService;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
@ApiOperation(value = "로그인", notes = "이메일 회원 로그인을 한다.")
|
||||
@GetMapping(value = "/signin")
|
||||
public SingleResult<String> signin(@ApiParam(value = "회원ID : 이메일", required = true) @RequestParam String id,
|
||||
@ApiParam(value = "비밀번호", required = true) @RequestParam String password) {
|
||||
|
||||
User user = userJpaRepo.findByUid(id).orElseThrow(CEmailSigninFailedException::new);
|
||||
if (!passwordEncoder.matches(password, user.getPassword()))
|
||||
throw new CEmailSigninFailedException();
|
||||
|
||||
return responseService.getSingleResult(jwtTokenProvider.createToken(user.getUsername(), user.getRoles()));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "가입", notes = "회원가입을 한다.")
|
||||
@GetMapping(value = "/signup")
|
||||
public CommonResult signin(@ApiParam(value = "회원ID : 이메일", required = true) @RequestParam String id,
|
||||
@ApiParam(value = "비밀번호", required = true) @RequestParam String password,
|
||||
@ApiParam(value = "이름", required = true) @RequestParam String name) {
|
||||
|
||||
userJpaRepo.save(User.builder()
|
||||
.uid(id)
|
||||
.password(passwordEncoder.encode(password))
|
||||
.name(name)
|
||||
.roles(Collections.singletonList("ROLE_USER"))
|
||||
.build());
|
||||
return responseService.getSuccessResult();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user