SpringBoot2로 Rest api 만들기(8) – SpringSecurity를 이용한 api 인증 및 권한부여

This commit is contained in:
kimyonghwa
2019-04-15 19:14:45 +09:00
parent ffd8fe10be
commit a7e3feb3bf
18 changed files with 397 additions and 45 deletions

View File

@@ -23,6 +23,8 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-freemarker'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'io.jsonwebtoken:jjwt:0.9.1'
implementation 'io.springfox:springfox-swagger2:2.6.1'
implementation 'io.springfox:springfox-swagger-ui:2.6.1'
implementation 'net.rakugakibox.util:yaml-resource-bundle:1.1'

View File

@@ -2,10 +2,18 @@ package com.rest.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
@SpringBootApplication
public class SpringRestApiApplication {
public static void main(String[] args) {
SpringApplication.run(SpringRestApiApplication.class, args);
}
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}

View File

@@ -1,5 +1,7 @@
package com.rest.api.advice;
import com.rest.api.advice.exception.CEmailSigninFailedException;
import com.rest.api.advice.exception.CInvalidJwtAuthenticationException;
import com.rest.api.advice.exception.CUserNotFoundException;
import com.rest.api.model.response.CommonResult;
import com.rest.api.service.ResponseService;
@@ -24,15 +26,29 @@ public class ExceptionAdvice {
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult defaultException(HttpServletRequest request, Exception e) {
e.printStackTrace();
return responseService.getFailResult(Integer.valueOf(getMessage("unKnown.code")), getMessage("unKnown.msg"));
}
@ExceptionHandler(CUserNotFoundException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult userNotFoundException(HttpServletRequest request, CUserNotFoundException e) {
protected CommonResult userNotFound(HttpServletRequest request, CUserNotFoundException e) {
return responseService.getFailResult(Integer.valueOf(getMessage("userNotFound.code")), getMessage("userNotFound.msg"));
}
@ExceptionHandler(CInvalidJwtAuthenticationException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult invalidJwtToken(HttpServletRequest request, CInvalidJwtAuthenticationException e) {
return responseService.getFailResult(Integer.valueOf(getMessage("invalidJwtToken.code")), getMessage("invalidJwtToken.msg"));
}
@ExceptionHandler(CEmailSigninFailedException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult emailSigninFailed(HttpServletRequest request, CEmailSigninFailedException e) {
return responseService.getFailResult(Integer.valueOf(getMessage("emailSigninFailed.code")), getMessage("emailSigninFailed.msg"));
}
private String getMessage(String code) {
return getMessage(code, null);
}

View File

@@ -0,0 +1,15 @@
package com.rest.api.advice.exception;
public class CEmailSigninFailedException extends RuntimeException {
public CEmailSigninFailedException(String msg, Throwable t) {
super(msg, t);
}
public CEmailSigninFailedException(String msg) {
super(msg);
}
public CEmailSigninFailedException() {
super();
}
}

View File

@@ -0,0 +1,15 @@
package com.rest.api.advice.exception;
public class CInvalidJwtAuthenticationException extends RuntimeException {
public CInvalidJwtAuthenticationException(String msg, Throwable t) {
super(msg, t);
}
public CInvalidJwtAuthenticationException(String msg) {
super(msg);
}
public CInvalidJwtAuthenticationException() {
super();
}
}

View File

@@ -28,7 +28,7 @@ public class MessageConfiguration implements WebMvcConfigurer {
}
@Bean // 지역설정을 변경하는 인터셉터. 요청시 파라미터에 lang 정보를 지정하면 언어가 변경됨.
private LocaleChangeInterceptor localeChangeInterceptor() {
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang");
return lci;

View File

@@ -0,0 +1,50 @@
package com.rest.api.config;
import com.rest.api.filter.JwtTokenFilter;
import com.rest.api.filter.JwtTokenProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@RequiredArgsConstructor
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final JwtTokenProvider jwtTokenProvider;
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().disable() // rest api 이므로 기본설정 사용안함. 기본설정은 비인증시 로그인폼 화면으로 리다이렉트 된다.
.csrf().disable() // rest api이므로 csrf 보안이 필요없으므로 disable처리.
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // jwt token으로 인증할것이므로 세션필요없으므로 생성안함.
.and()
.authorizeRequests() // 다음 리퀘스트에 대한 사용권한 체크
.antMatchers("/*/signin", "/*/signup").permitAll() // 가입 및 인증 주소는 누구나 접근가능
.antMatchers(HttpMethod.GET, "helloworld/**").permitAll() // hellowworld로 시작하는 GET요청 리소스는 누구나 접근가능
.anyRequest().authenticated() // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
.and()
.addFilterBefore(new JwtTokenFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); // jwt token 필터를 id/password 인증 필터 전에 넣어라.
}
@Override // ignore swagger security config
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs", "/swagger-resources/**",
"/swagger-ui.html", "/webjars/**", "/swagger/**");
}
}

View File

@@ -17,7 +17,7 @@ public class SwaggerConfiguration {
public Docket swaggerApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(swaggerInfo()).select()
.apis(RequestHandlerSelectors.basePackage("com.rest.api.controller"))
.paths(PathSelectors.any())
.paths(PathSelectors.ant("/v1/**"))
.build()
.useDefaultResponseMessages(false); // 기본으로 세팅되는 200,401,403,404 메시지를 표시 하지 않음
}

View 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();
}
}

View File

@@ -7,13 +7,11 @@ import com.rest.api.model.response.ListResult;
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 io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
@Api(tags = {"1. User"})
@Api(tags = {"2. User"})
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/v1")
@@ -22,6 +20,9 @@ public class UserController {
private final UserJpaRepo userJpaRepo;
private final ResponseService responseService; // 결과를 처리할 Service
@ApiImplicitParams({
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "회원 리스트 조회", notes = "모든 회원을 조회한다")
@GetMapping(value = "/users")
public ListResult<User> findAllUser() {
@@ -29,42 +30,40 @@ public class UserController {
return responseService.getListResult(userJpaRepo.findAll());
}
@ApiImplicitParams({
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "회원 단건 조회", notes = "userId로 회원을 조회한다")
@GetMapping(value = "/user/{userId}")
public SingleResult<User> findUserById(@ApiParam(value = "회원ID", required = true) @PathVariable int userId,
@ApiParam(value = "언어", defaultValue = "ko") @RequestParam String lang) {
@GetMapping(value = "/user/{msrl}")
public SingleResult<User> findUserById(@ApiParam(value = "회원번호", required = true) @PathVariable int msrl,
@ApiParam(value = "언어", defaultValue = "ko") @RequestParam String lang) {
// 결과데이터가 단일건인경우 getSingleResult를 이용해서 결과를 출력한다.
return responseService.getSingleResult(userJpaRepo.findById(userId).orElseThrow(CUserNotFoundException::new));
}
@ApiOperation(value = "회원 입력", notes = "회원을 입력한다")
@PostMapping(value = "/user")
public SingleResult<User> save(@ApiParam(value = "회원이름", required = true) @RequestParam String name,
@ApiParam(value = "회원이메일", required = true) @RequestParam String email) {
User user = new User();
user.setName(name);
user.setEmail(email);
return responseService.getSingleResult(userJpaRepo.save(user));
return responseService.getSingleResult(userJpaRepo.findById(msrl).orElseThrow(CUserNotFoundException::new));
}
@ApiImplicitParams({
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "회원 수정", notes = "회원정보를 수정한다")
@PutMapping(value = "/user")
public SingleResult<User> modify(
@ApiParam(value = "회원ID", required = true) @RequestParam int userId,
@ApiParam(value = "회원이름", required = true) @RequestParam String name,
@ApiParam(value = "회원이메일", required = true) @RequestParam String email) {
User user = new User();
user.setId(userId);
user.setName(name);
user.setEmail(email);
@ApiParam(value = "회원번호", required = true) @RequestParam int msrl,
@ApiParam(value = "회원이름", required = true) @RequestParam String name) {
User user = User.builder()
.msrl(msrl)
.name(name)
.build();
return responseService.getSingleResult(userJpaRepo.save(user));
}
@ApiImplicitParams({
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "회원 삭제", notes = "userId로 회원정보를 삭제한다")
@DeleteMapping(value = "/user/{userId}")
@DeleteMapping(value = "/user/{msrl}")
public CommonResult delete(
@ApiParam(value = "회원ID", required = true) @PathVariable int userId) {
userJpaRepo.deleteById(userId);
@ApiParam(value = "회원번호", required = true) @PathVariable int msrl) {
userJpaRepo.deleteById(msrl);
// 성공 결과 정보만 필요한경우 getSuccessResult()를 이용하여 결과를 출력한다.
return responseService.getSuccessResult();
}

View File

@@ -1,21 +1,67 @@
package com.rest.api.entity;
import lombok.Getter;
import lombok.Setter;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
@Entity
@Getter
@Setter
//@Table(name = "user")
public class User {
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "user")
public class User implements UserDetails {
@Id // pk
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int msrl;
@Column(nullable = false, unique = true, length = 30)
private String uid;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Column(nullable = false, length = 100)
private String password;
@Column(nullable = false, length = 100)
private String name;
private String email;
@ElementCollection(fetch = FetchType.EAGER)
@Builder.Default
private List<String> roles = new ArrayList<>();
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
}
@Override
public java.lang.String getUsername() {
return this.uid;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}

View File

@@ -0,0 +1,33 @@
package com.rest.api.filter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class JwtTokenFilter extends GenericFilterBean {
private JwtTokenProvider jwtTokenProvider;
// Jwt Provier 주입
public JwtTokenFilter(JwtTokenProvider jwtTokenProvider) {
this.jwtTokenProvider = jwtTokenProvider;
}
// Request로 들어오는 Jwt Token의 유효성을 검증하는 filter를 filterChain에 등록합니다.
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
String token = jwtTokenProvider.resolveToken((HttpServletRequest) request);
if (token != null && jwtTokenProvider.validateToken(token)) {
Authentication auth = jwtTokenProvider.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(auth);
}
filterChain.doFilter(request, response);
}
}

View File

@@ -0,0 +1,74 @@
package com.rest.api.filter;
import com.rest.api.advice.exception.CInvalidJwtAuthenticationException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Base64;
import java.util.Date;
import java.util.List;
@RequiredArgsConstructor
@Component
public class JwtTokenProvider { // JWT 토큰을 생성 및 검증 모듈
private String secretKey = "secret";
private long tokenValidMilisecond = 1000L * 60 * 60; // 1hour
private final UserDetailsService userDetailsService;
@PostConstruct
protected void init() {
secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes());
}
// Jwt 토큰 생성
public String createToken(String username, List<String> roles) {
Claims claims = Jwts.claims().setSubject(username);
claims.put("roles", roles);
Date now = new Date();
return Jwts.builder()
.setClaims(claims) // 데이터
.setIssuedAt(now) // 토큰 발행일자
.setExpiration(new Date(now.getTime() + tokenValidMilisecond)) // set Expire Time
.signWith(SignatureAlgorithm.HS256, secretKey) // 암호화 알고리즘, secret값 세팅
.compact();
}
// Jwt 토큰으로 인증 정보를 조회
public Authentication getAuthentication(String token) {
UserDetails userDetails = userDetailsService.loadUserByUsername(this.getUsername(token));
return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
}
// Jwt 토큰에서 회원 이름(ID) 추출
public String getUsername(String token) {
return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject();
}
// Request의 Header에서 token 파싱 : "X-AUTH-TOKEN: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJjb2Rlajk5QG5hdmVyLmNvbSIsInJvbGVzIjpbIlJPTEVfVVNFUiJdLCJpYXQiOjE1NTUzMTY1NzksImV4cCI6MTU1NTMyMDE3OX0.ftuRcpLZmMbKoxM3pQB5VA9As9Yamt10FN6Lbgu-pjVB3AGZDWfS9WRzGNbtZkKvSZH9swx3WgrHnONyrUoaqA"
public String resolveToken(HttpServletRequest req) {
return req.getHeader("X-AUTH-TOKEN");
}
// Jwt 토큰의 유효성 + 만료일자 확인
public boolean validateToken(String jwtToken) {
try {
Jws<Claims> claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwtToken);
return !claims.getBody().getExpiration().before(new Date());
} catch (Exception e) {
throw new CInvalidJwtAuthenticationException();
}
}
}

View File

@@ -3,5 +3,9 @@ package com.rest.api.repo;
import com.rest.api.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserJpaRepo extends JpaRepository<User, Integer> {
Optional<User> findByUid(String email);
}

View File

@@ -0,0 +1,19 @@
package com.rest.api.service.security;
import com.rest.api.advice.exception.CUserNotFoundException;
import com.rest.api.repo.UserJpaRepo;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
@RequiredArgsConstructor
@Service
public class CustomUserDetailService implements UserDetailsService {
private final UserJpaRepo userJpaRepo;
public UserDetails loadUserByUsername(String username) {
return userJpaRepo.findByUid(username).orElseThrow(CUserNotFoundException::new);
}
}

View File

@@ -8,7 +8,7 @@ spring:
username: sa
jpa:
database-platform: org.hibernate.dialect.H2Dialect
#properties.hibernate.hbm2ddl.auto: none
properties.hibernate.hbm2ddl.auto: update
showSql: true
messages:
basename: i18n/exception

View File

@@ -4,3 +4,9 @@ unKnown:
userNotFound:
code: "-1000"
msg: "This member not exist"
invalidJwtToken:
code: "-1001"
msg: "Authentication information is not valid."
emailSigninFailed:
code: "-1001"
msg: "Your account does not exist or your email or password is incorrect."

View File

@@ -4,3 +4,9 @@ unKnown:
userNotFound:
code: "-1000"
msg: "존재하지 않는 회원입니다."
invalidJwtToken:
code: "-1001"
msg: "인증 정보가 유효하지 않습니다."
emailSigninFailed:
code: "-1001"
msg: "계정이 존재하지 않거나 이메일 또는 비밀번호가 정확하지 않습니다."