인프런 커뮤니티 질문&답변

은빛갈기님의 프로필 이미지

작성한 질문수

스프링 시큐리티 OAuth2

Spring Authorization Server - 기본 구성으로 시작하기 31:45

해결된 질문

22.10.31 10:51 작성

·

1.7K

0

안녕하세요.

임시코드 요청은 정상적으로 동작했습니다.

토큰요청시 uri 에 뜨는 code 를 복붙 하니

json 형태로 응답이 오는것이 아닌,

html 양식으로 응답이 왔습니다.

 

임시코드 요청

스크린샷 2022-10-31 오전 10.49.02.png

토큰 요청

스크린샷 2022-10-31 오전 10.45.30.png

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package io.security.oauth2.springsecurityoauth2authorization;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
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.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
public class DefaultSecurityConfig {
    public DefaultSecurityConfig() {
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests((authorizeRequest) -> {
            ((ExpressionUrlAuthorizationConfigurer.AuthorizedUrl)authorizeRequest.anyRequest()).authenticated();
        });
        httpSecurity.formLogin();
        return (SecurityFilterChain)httpSecurity.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withUsername("user").password("{noop}1234").authorities(new String[]{"ROLE_USER"}).build();
        return new InMemoryUserDetailsManager(new UserDetails[]{user});
    }
}

 

 

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package io.security.oauth2.springsecurityoauth2authorization;

import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.UUID;
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.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.ClientSettings;
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

@Configuration
public class AuthorizationServerConfig {
    public AuthorizationServerConfig() {
    }

    @Bean
    public SecurityFilterChain authSecurityFilterChain(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        http.exceptionHandling((exception) -> {
            exception.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"));
        });
        http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
        return (SecurityFilterChain)http.build();
    }

    @Bean
    public ProviderSettings providerSettings() {
        return ProviderSettings.builder().issuer("http://localhost:9000").build();
    }

    @Bean
    public RegisteredClientRepository registeredClientRepository() {
        RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString()).clientId("oauth2-client-app").clientSecret("{noop}secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN).authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).redirectUri("http://127.0.0.1:8081").scope("openid").scope("read").scope("write").clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build()).build();
        return new InMemoryRegisteredClientRepository(new RegisteredClient[]{registeredClient});
    }

    @Bean
    public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
        return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
    }

    @Bean
    public JWKSource<SecurityContext> jwkSource() throws NoSuchAlgorithmException {
        RSAKey rsaKey = this.generateRsa();
        JWKSet jwkSet = new JWKSet(rsaKey);
        return (jwkSelector, context) -> {
            return jwkSelector.select(jwkSet);
        };
    }

    private RSAKey generateRsa() throws NoSuchAlgorithmException {
        KeyPair keyPair = this.generateRsaKey();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)keyPair.getPrivate();
        RSAPublicKey rsaPublicKey = (RSAPublicKey)keyPair.getPublic();
        return (new RSAKey.Builder(rsaPublicKey)).privateKey(rsaPrivateKey).keyID(UUID.randomUUID().toString()).build();
    }

    private KeyPair generateRsaKey() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        return keyPair;
    }
}

 

 

답변 1

1

은빛갈기님의 프로필 이미지
은빛갈기
질문자

2022. 10. 31. 11:43

아래과정으로

해결했습니다.

 

Authorization 탭에서 아래와 같이 설정하고 send.

type - basic auth

client name - oauth2-client-app

password - secret

 

image