0

私は現在、Spring Boot アプリケーションに取り組んでおり、アプリケーションのセキュリティを行うタスクがあります。彼らは、私が管理している他のアプリケーションで他のSpring Securityチュートリアルでセキュリティを作成することを考えていても、OAuth2トークン認証を使用することを提案しました。これは、さまざまなソースで見つけたチュートリアルに基づいて作成されています。

public class OAuthPermissionConfig extends ResourceServerConfigurerAdapter 

@Override
public void configure(HttpSecurity http) throws Exception {
    http.anonymous().disable()
            .authorizeRequests()
            .antMatchers("/pim/oauth/token").permitAll().and().formLogin()
            .and().authorizeRequests().antMatchers("/actuator/**", "/v2/api-docs", "/webjars/**",
            "/swagger-resources/configuration/ui", "/swagger-resources", "/swagger-ui.html",
            "/swagger-resources/configuration/security").hasAnyAuthority("ADMIN")
            .anyRequest().authenticated();
}





 public class CustomAuthenticationProvider implements AuthenticationProvider 

@Autowired
private ADService adService;

@Autowired
private UserService userService;

@Override
@Transactional
public Authentication authenticate(Authentication authentication) {
    try {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();
        User user = userService.getUserByUsername(username);
        userService.isUserAllowedToUseTheApplication(user);
        if (adService.isUserNearlyBlockedInAD(user)) {
            throw new BadCredentialsException(CustomMessages.TOO_MANY_LOGIN_FAILED);
        } else {
            adService.login(username, password);
        }
        List<GrantedAuthority> userAuthority = user.getRoles().stream()
                .map(p -> new SimpleGrantedAuthority(p.getId())).collect(Collectors.toList());
        return new LoginToken(user, password, userAuthority);
    } catch (NoSuchDatabaseEntryException | NullArgumentException | NamingException | EmptyUserRolesException e) {
        throw new BadCredentialsException(CustomMessages.INVALID_CREDENTIALS + " or " + CustomMessages.UNAUTHORIZED);
    }
}

@Override
public boolean supports(Class<?> authentication) {
    return authentication.equals(
            UsernamePasswordAuthenticationToken.class);
}





@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}




public class OAuthServerConfig extends AuthorizationServerConfigurerAdapter 

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private UserService userService;

@Autowired
private PasswordEncoder passwordEncoder;

@Bean
public TokenEnhancer tokenEnhancer() {
    return new CustomTokenEnhancer();
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
    endpoints.authenticationManager(authenticationManager).tokenEnhancer(tokenEnhancer());
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

    clients
            .inMemory()
            .withClient("pfjA@Dmin")
            .secret(passwordEncoder.encode("4gM~$laY{gnfShpa%8Pcjwcz-J.NVS"))
            .authorizedGrantTypes("password")
            .accessTokenValiditySeconds(UTILS.convertMinutesToSeconds(1440))
            .scopes("read", "write", "trust")
            .resourceIds("oauth2-resource");
}

@Override
public void configure(AuthorizationServerSecurityConfigurer security) {
    security.checkTokenAccess("isAuthenticated()").allowFormAuthenticationForClients();
}

ログインをテストするときは、次のパラメーターで postman を使用します。

http://localhost:8080/oauth/token?grant_type=パスワード

ヘッダー: 基本 btoa(pfjA@Dmin,4gM~$laY{gnfShpa%8Pcjwcz-J.NVS)

コンテンツタイプ: application/x-www-form-urlencoded

本文: form-data -> ユーザー名とパス。これは、データベースからの有効なユーザー資格情報である必要があります。資格情報が正しい場合、ユーザーは応答します

"access_token": "f0dd6eee-7a64-4079-bb1e-e2cbcca6d7bf",

"token_type": "ベアラー",

"expires_in": 86399,

"scope": "読み書き信頼"

ここで、他のすべてのリクエストにこのトークンを使用する必要があります。そうしないと、アプリケーションを使用する権限がありません。

私の質問: これは Spring Security の他のバージョンですか、それとも何ですか? OAuth2 認証について読みましたが、アプリケーションは Spring Security と OAuth2 の両方を持つことができると読みました。アプリのセキュリティを実装する方法に何か問題がある場合は、誰か説明してもらえますか?

どうもありがとうございました!

4

1 に答える 1