MapleStory Finger Point

๐ŸŸค JAVA/๐ŸŸค Spring

[Spring Security] ๊ถŒํ•œ ์ฒ˜๋ฆฌ

HYEJU01 2024. 12. 4. 18:42
 

๋ชฉ์ฐจ

 

     

     

    ( ์ œ๊ฐ€ ์ž‘์—…ํ–ˆ๋˜  ํ”„๋กœ์ ํŠธ ์ฝ”๋“œ ๊ธฐ๋ฐ˜์œผ๋กœ ์„ค๋ช…ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.)

     

    1. ๊ถŒํ•œ ์ž‘์—… (EmployeeDetails.java)

     

      // ๊ถŒํ•œ ๊ด€๋ จ ์ž‘์—…์„ ์œ„ํ•œ ๋ฉ”์„œ๋“œ
      @Override
      public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
    
        try {
          // Employee์˜ authorityGrade๋ฅผ UserRole Enum์œผ๋กœ ๋ณ€ํ™˜
          UserRole role = UserRole.valueOf(employee.getAuthorityGrade());
          // ๊ถŒํ•œ์— ROLE_ ์ ‘๋‘์‚ฌ ๋ถ™์—ฌ ์ถ”๊ฐ€
          authorities.add(new SimpleGrantedAuthority("ROLE_" + role.name()));
        } catch (IllegalArgumentException e) {
          // authorityGrade๊ฐ€ UserRole Enum์— ์ •์˜๋˜์ง€ ์•Š์€ ๊ฒฝ์šฐ ์—๋Ÿฌ ์ถœ๋ ฅ
          System.err.println("Invalid authorityGrade value: " + employee.getAuthorityGrade());
        }
    
        return authorities;
      }

     

     

     

    2. UserRole.java 

    ํ•ด๋‹น Enum ๊ณผ ๋™์ผ ๊ฐ’์ด DB ์— ๋“ค์–ด๊ฐ€๊ฒŒ ์ฒ˜๋ฆฌ

    package com.project.tobe.dto;
    
    import lombok.AllArgsConstructor;
    import lombok.Getter;
    
    @AllArgsConstructor
    @Getter
    public enum UserRole {
    
        S("๋Œ€ํ‘œ"),
        A("๋ถ€์žฅ"),
        B("๊ณผ์žฅ"),
        C("๋Œ€๋ฆฌ"),
        D("์‚ฌ์›");
    
      private String value;
    }

     

     

     

     

    3. SecurityConfig.java

     

    .antMatchers("/employee.do").hasAnyRole("S", "A") 
    // "/employee.do" ๊ฒฝ๋กœ๋Š” "A","S" ์—ญํ• ์„ ๊ฐ€์ง„ ์‚ฌ์šฉ์ž๋งŒ ์ ‘๊ทผ ๊ฐ€๋Šฅ

     

     

     

    S ๊ถŒํ•œ ๋กœ๊ทธ์ธ

     

     

     

     

    D ๊ถŒํ•œ ๋กœ๊ทธ์ธ 

     

    ์ง์› ๊ด€๋ฆฌ ํƒญ์ด ๋ณด์ด์ง€ ์•Š์Œ

     

     

     

    employee ํŽ˜์ด์ง€ ๊ฐ•์ œ ์ ‘๊ทผ์‹œ ์ ‘๊ทผ ๋ถˆ๊ฐ€ ์ฐฝ