2017-12-31 91 views
-1

스프링 보안 OAuth2를 사용하여 Github 인증을 성공적으로 통과했습니다. 그러나 Github을 통해 얻은 사용자 역할은 USER_ROLE입니다.인증이 성공한 후에 역할을 변경할 수 있습니까?

그래서 사용자의 권한을 제어하기 위해 권한 부여가 성공한 후에 얻은 Github 사용자 정보를 판단하여 해당 역할을 수정할 수 있는지 궁금합니다.

예를 들어, getPrincipal()은 고유 한 "이름"을 가져옵니다. 그런 다음 "이름"(예 : "ADMIN")으로 역할을 수정하십시오. 마지막으로 @PreAuthorize ("hasRole ('ROLE_ADMIN')")를 사용하여 권한을 제어하십시오.

다른 해결책이 있습니까? 이 애플리케이션에서 Github의 OAuth2 인증 및 역할 기반 권한 관리를 통합하고자합니다.

답변

0

가장 쉬운 옵션은 현재 인증을 가져 와서 새 인스턴스를 만들고 SecurityContextHolder 내용을 직접 설정에 설명 된대로 SecurityContextHolder에 설정하는 것입니다. 여러 스레드에서 인증을 수행 할 때의 영향을 이해해야합니다 (reference to understand에서 읽음). 드디어 OAuth2ClientAuthenticationProcessingFilter 재건 및 successfulAuthentication 메소드를 재정의함으로써 해결

// update the current Authentication 
Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(auth.getAuthorities()); 
authorities.add(new GrantedAuthorityImpl('ROLE_NEWROLE')); 
Authentication newAuth = new UsernamePasswordToken(auth.getPrincipal(),auth.getCredentials(),authorities) 
SecurityContextHolder.getContext().setAuthentication(newAuth); 
+0

UsernamePasswordToken이 잘못되었습니다. OAuth와 다른 인증 방법은 다릅니다. 마지막으로 OAuth2ClientAuthenticationProcessingFilter를 다시 작성하고 successfulAuthentication 메소드를 재정 의하여 해결했습니다. 핵심은 첫 번째 단계는 인증이 성공한 후 프린시 펄에서 내 Github 계정인지 여부를 확인하는 것입니다. 그런 다음 SecurityContextHolder.getContext()에 의해 현재 성공적인 인증 OAuth2Authentication. GetAuthentication() get. 그런 다음 새 인증을 작성하고 SecurityContextHolder에 새 OAuth2Authentication을 작성하십시오. – Cciradih

0

: 현재 인증에 GrantedAuthority가 추가의 예는 아래에 주어진다.

중요한 점은 첫 번째 단계는 인증이 성공한 후 사용자가 내 Github 계정인지 확인하는 것입니다.

그런 다음 SecurityContextHolder.getContext(). getAuthentication()에 의한 현재 성공적인 인증 OAuth2Authentication이 가져옵니다. 그런 다음 새 인증을 작성하고 SecurityContextHolder에 새 OAuth2Authentication을 작성하십시오.

public class CustomOAuth2ClientAuthenticationProcessingFilter extends OAuth2ClientAuthenticationProcessingFilter { 
public CustomOAuth2ClientAuthenticationProcessingFilter(String defaultFilterProcessesUrl) { 
    super(defaultFilterProcessesUrl); 
} 

@Override 
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { 
    super.successfulAuthentication(request, response, chain, authResult); 
    if (authResult.getPrincipal().equals("cciradih")) { 
     OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication(); 
     SecurityContextHolder.getContext().setAuthentication(new OAuth2Authentication(oAuth2Authentication.getOAuth2Request(), new Authentication() { 
      @Override 
      public Collection<? extends GrantedAuthority> getAuthorities() { 
       return AuthorityUtils.createAuthorityList("ROLE_ADMIN", "ROLE_USER"); 
      } 

      @Override 
      public Object getCredentials() { 
       return oAuth2Authentication.getCredentials(); 
      } 

      @Override 
      public Object getDetails() { 
       return oAuth2Authentication.getUserAuthentication().getDetails(); 
      } 

      @Override 
      public Object getPrincipal() { 
       return oAuth2Authentication.getPrincipal(); 
      } 

      @Override 
      public boolean isAuthenticated() { 
       return oAuth2Authentication.getUserAuthentication().isAuthenticated(); 
      } 

      @Override 
      public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { 

      } 

      @Override 
      public String getName() { 
       return oAuth2Authentication.getName(); 
      } 
     })); 
    } 
} 
} 
관련 문제