春のセキュリティ:データベースへの変換では、メモリ認証

iamjpcbau:

私は春に私のログイン作業を持っているために、メモリ内の認証を使用しています

しかし、私は、永続的なデータベースに今それを変更したいです

下のコードを参照してください。

JWTWebSecurityConfig

package com.sbc.cpex.security.jwt;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

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

    @Autowired
    private JwtUnAuthorizedResponseAuthenticationEntryPoint jwtUnAuthorizedResponseAuthenticationEntryPoint;

    @Autowired
    private UserDetailsService jwtInMemoryUserDetailsService;

    @Autowired
    private JwtTokenAuthorizationOncePerRequestFilter jwtAuthenticationTokenFilter;

    @Value("${jwt.get.token.uri}")
    private String authenticationPath;

    @Autowired
    DataSource dataSource;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

//      auth
//            .userDetailsService(jwtInMemoryUserDetailsService)
//            .passwordEncoder(passwordEncoderBean());

        auth.jdbcAuthentication().dataSource(dataSource)
        .usersByUsernameQuery("select username, password"
            + " from users where username=?")
        .passwordEncoder(passwordEncoderBean());
    }

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

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

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            .csrf().disable()
//            .csrf().and().cors().disable()
            .exceptionHandling().authenticationEntryPoint(jwtUnAuthorizedResponseAuthenticationEntryPoint).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests()
            .anyRequest().authenticated();

       httpSecurity
            .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        httpSecurity
            .headers()
            .frameOptions().sameOrigin()  //H2 Console Needs this setting
            .cacheControl(); //disable caching
    }

    @Override
    public void configure(WebSecurity webSecurity) throws Exception {
        webSecurity
            .ignoring()
            .antMatchers(
                HttpMethod.POST,
                authenticationPath
            )
            .antMatchers(HttpMethod.OPTIONS, "/**")
            .and()
            .ignoring()
            .antMatchers(
                HttpMethod.GET,
                "/" //Other Stuff You want to Ignore
            )
            .and()
            .ignoring()
            .antMatchers("/h2-console/**/**");//Should not be in Production!
    }
}

私がやった手順:これらの行アウト1.コメント

auth
    .userDetailsService(jwtInMemoryUserDetailsService)
    .passwordEncoder(passwordEncoderBean());
  1. jdbcauthのた​​めの次の行を追加します。
auth.jdbcAuthentication().dataSource(dataSource)
        .usersByUsernameQuery("select username, password"
            + " from users where username=?")
        .passwordEncoder(passwordEncoderBean());
  1. DataSourceConfigと呼ばれるクラスを作成します。
package com.sbc.cpex.security.jwt;

import javax.sql.DataSource;

import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DataSourceConfig {

    @Bean
    public DataSource getDataSource() {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create(); 
        dataSourceBuilder.username("test"); 
        dataSourceBuilder.password("pass"); 
        return dataSourceBuilder.build(); 
    }
}

しかし、私はこのエラーを取得しています

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'h2Console' defined in class path resource [org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.servlet.ServletRegistrationBean]: Factory method 'h2Console' threw exception; nested exception is java.lang.IllegalArgumentException: dataSource or dataSourceClassName or jdbcUrl is required.

私を啓発してください。TIA

Ananthapadmanabhan:

スタックトレース自体は自明です:

nested exception is java.lang.IllegalArgumentException: dataSource or dataSourceClassName or jdbcUrl is required.

あなたは、データソースのBeanを作成するときにデータソースのURLを提供する必要があります。スタックトレースから私はあなたがH2を使用していることを理解することができました。だから、あなたのようなBeanを作成することができます。

@Bean
public DataSource getDataSource() {
    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
    dataSourceBuilder.driverClassName("org.h2.Driver");
    dataSourceBuilder.url("jdbc:h2:mem:test");
    dataSourceBuilder.username("username");
    dataSourceBuilder.password("");
    return dataSourceBuilder.build();
}

あなたのコードでは、あなただけので、それがエラーを投げている、ユーザ名とパスワードの一部を提供しました。

それはクラスパスの走査中に依存性として見られるよう@iamjpcbau SpringbootはdatabseとしてH2を自動設定されます。あなたがデータソースBeanを提供してきたので、春には、自動的にH2を設定するためにそれを占めるが、URLは、あなたが受けているという例外が発生しており、不足しています。

あなたのプロジェクトに別のデータベースを構成するためにinorderを、介してデータベースを設定するapplication.propertiesか、application.ymlまたは手動で他のデータベースが設定されていないがあるので、あなたの対応するデータベースの構成は、代わりにH2.Nowの起動時に巻き取られるようにコンフィグレーションBeanを作成し、H2以来発見されましたクラスパス上に、春はデフォルトでこれを構成しています。

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=388303&siteId=1