Security 로그인 권한

HUGO·2022년 10월 7일
0

JPA

목록 보기
6/6

SecurityConfig.java

// 회원 가입 환경 설정 => 로그인 로그아웃 다 만들고 업무 시작
package com.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

import com.example.service.SecurityLoginService;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    
    @Autowired SecurityLoginService securityLoginService;


    // 필터 설정 하기
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{


        // 권한에 대한 페이지 설정
        // 127.0.0.1:8080/ROOT/*** ADMIN
        // 127.0.0.1:8080/ROOT/*** SELLER
        http.authorizeRequests()
        .antMatchers("/admin", "/admin/**").hasAnyRole("ADMIN")     
        .antMatchers("/seller", "/seller/**").hasAnyRole("SELLER")
        .antMatchers("/customer", "/customer/**").hasAnyRole("CUSTOMER")
        .anyRequest().permitAll();

        // 로그인 설정
        http.formLogin().loginPage("/member/login.do")
        .loginProcessingUrl("/member/login.do")
        .usernameParameter("uid")
        .passwordParameter("upw")
        .defaultSuccessUrl("/")
        .permitAll();
        
        // 로그아웃 설정
        http.logout()
            .logoutUrl("/member/logout.do")
            .logoutSuccessUrl("/")
            .clearAuthentication(true)
            .invalidateHttpSession(true)
            .permitAll();

            // 직접 생성한 SecurityLoginService 등록
        http.userDetailsService(securityLoginService);

        return http.build();
    }


    // 비밀번호의 hash 알고리즘 설정
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

SecurityLoginService.java

package com.example.service;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.example.entity.Member;
import com.example.repository.MemberRepository;

@Service
public class SecurityLoginService implements UserDetailsService {

    @Autowired MemberRepository mRepository;
    
    // 0. 로그인 화면에서 전달되어 호출되는 오브라이드된 메소드
    // 1. 로그인에서 전송되는 항목은 아이디가 전송됨.
    // 2. 아이디를 이용해서 db에서아이디, 암호, 권한을 꺼냄
    // 3. UserDetails의 객체를 만들다음 반환하면 시큐리티 비교후에 로그인처리
    @Override
    public UserDetails loadUserByUsername(String username) 
        throws UsernameNotFoundException {
        System.out.println("---------SecurityLoginService-----------");
        System.out.println(username);
        
        Member member = mRepository.findById(username).orElse(null);
        if(member != null) {
            String[] str = { member.getRole() };
            Collection<GrantedAuthority> role =  AuthorityUtils.createAuthorityList(str);
            //아이디, 암호, 권한들..
            User user = new User(member.getUserid(), member.getUserpw(), role );        // role은 String으로 안받아짐
            return user;
        }
        else {
            String[] str = { "_" };
            Collection<GrantedAuthority> role =  AuthorityUtils.createAuthorityList(str);
            User user = new User("_", "_", role );
            return user;    
        }
    }
    
}

MemberController.java에 추가 작성

@GetMapping(value = "/login.do")
    public String loginGET(){
        return "member_login";
    }

member_login.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>로그인</title>
</head>
<a th:href="@{/home.do}"></a>
<body>
    <form th:action="@{/member/login.do}" method="post">
            로그인   : <input type="text" name="uid" /><br />   <!--name 값은 무조건 security 보고 맞춰야 함-->
            비밀번호 : <input type="password" name="upw" /><br />
        <input type="submit" value="로그인" />
    </form>
</body>
</html>
profile
갓 신생아 개발자 이야기

0개의 댓글