2 Temmuz 2019 Salı

SpringSecurity OAuth2 Client OAuth2LoginConfigurer Sınıfı - Login İçin OAuth2 Sunucusu Yönlendirir

Giriş
Şu satırı dahil ederiz
import org.springframework.security.config.annotation.web.configurers.oauth2.client
.OAuth2LoginConfigurer;
OAuth2 sunucusuna bağlantı kurarak authentication (doğrulama) yapar. OAuth2 ilk çıktığında authorization (yetkilendirme) için kullanılıyordu. Daha sonra authentication (doğrulama) için de kullanılmaya başlandı. 

Yani Facebook, Google gibi OAuth2 doğrulaması yapan sunucuları client olarak kullanabilmeyi sağlar.

Açıklaması şöyle
http.oauth2Login() is used for Authenticating users using OpenID Connect. For example, it would be used as an alternative to formLogin().
Open ID ve OAuth2 Farkı
Bazı farklar şöyle
1. it introduces a completely new token (id_token) with radically different semantics than the OAuth 2.0 access_token and a standardized format that is understood by the Client as opposed to the access_token which is opaque to the Client

2. it "twists" the role of the Client, now becoming the "audience" (or: intended recipient) of a token (i.e. the id_token) whilst the audience of the access_token is still a remote entity (aka. Resource Server) and the Client is only the "presenter" of the latter

The 2nd item is the primary source of confusion between OAuth 2.0 and OpenID Connect.
Maven
Şu satırı dahil ederiz
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-oauth2-client</artifactId>
  <version>2.3.3.RELEASE</version>
</dependency>
application.properties Ayarları
SpringBoot github, facebook, google gibi OAuth2 sağlayıcıları için sadece application.properties dosyasına bazı ayarların girilmesi durumunda kolayca çalışıyor. SpringSecurity OAuth2 Login application.properties Ayarları yazısına bakabilirsiniz.

constructor
Örnek - Yeni
Şöyle yaparız
@Configuration
@EnableWebSecurity
public class SecurityConfig {
  @Bean
  public SecurityFilterChain securityFilterChain(HttpSecurity security) throws Exception {
    return security
      .csrf(AbstractHttpConfigurer::disable)
      .authorizeHttpRequests(auth->auth.anyRequest().authenticated())
      .oauth2Login(Customizer.withDefaults()).build();
    }
}

Örnek - Eski
Şöyle yaparız.
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http...
      .oauth2Login()
      ...
    }
}
Açıklaması şöyle. Yani diğer authentication login yöntemleri gibidir.
Here, we can see the oauth2Login() element is used in a similar manner to already known httpBasic() and formLogin() elements.
Örnek
Şöyle yaparız
@Override
public void configure(final HttpSecurity http) throws Exception {
  http.authorizeRequests()
    .antMatchers("/", "/login**", "/oauth2/authorization/**").permitAll()
    .anyRequest().authenticated()
    .and()
    .oauth2Login();
}
Açıklaması şöyle
In the configure method we are using antMatchers to allow (or later reject) access to certain endpoints. Like in the snippet above, “/”, “/login**”, “/oauth2/authorization/**” are allowed without any authentication. It is essential to give access to the “oauth2” path, otherwise your app will run into an endless loop of security checks.
Örnek
Şöyle yaparız. authenticated() olarak işaretli herhangi bir sayfaya istek gelirse, application.properties içinde tanımlı ne varsa (google, facebook, github vs) login için o sayfaya yönlendirir.
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  public void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf().disable().
      antMatcher("/**").authorizeRequests()
        .antMatchers("/", "/index.html").authenticated()
        .anyRequest().authenticated()
        .and()
        .oauth2Login().permitAll()
        .and().
        logout().logoutSuccessUrl("/");
    }
}
loginPage metodu
Örnek ver

defaultSuccessUrl metodu
Örnek ver

failureUrl metodu
Örnek ver

successHandler metodu
Örnek ver

1 Temmuz 2019 Pazartesi

SpringBatch FlatFileItemWriter Sınıfı

Giriş
CSV dosyası yazar.

setResource metodu
Şöyle yaparız.
@Bean
public FlatFileItemWriter<User> writer() {
  FlatFileItemWriter<User> writer = new FlatFileItemWriter<User>();
  writer.setResource(new ClassPathResource("users.csv"));
  writer.setLineAggregator(new DelimitedLineAggregator<User>() {
    {
      setDelimiter(",");
      setFieldExtractor(new BeanWrapperFieldExtractor<User>() {
        {
          setNames(new String[] { "id", "name" });
        }
      });
    }
  });
  return writer;
}

SpringBatch JobBuilderFactory Sınıfı

Giriş
Bu sınıfın tek metodu var. O da get() metodu

get metodu
JobBuilder nesnesi döner. JobBuilder ile şöyle yaparız.
jobBuilder.flow(mystep1())
  .end() {
  .build();
Örnek
Şöyle yaparız.
@Configuration
public class JobConfiguration {
  @Autowired
  private JobBuilderFactory jobBuilderFactory;

  @Bean
  public JdbcPagingItemReader<Customer> customerPagingItemReader(){
    ...
  }

  @Bean
  public StaxEventItemWriter<Customer> customerItemWriter() throws Exception{
    ...
  }

  @Bean
  public Step step1() throws Exception {
    ...
  }

  @Bean
  public Job job() throws Exception {
    return jobBuilderFactory.get("job")
      .start(step1())
      .build();
  }
}

SpringBatch StepBuilderFactory Sınıfı

Giriş
Bu sınıfın aynı JobBuilderFactory sınıfı gibi sadece get() metodu var. O yüzden çok bir özelliği yok.

get metodu - name
StepBuilder nesnesi döner.

Örnek
Şöyle yaparız.
@Bean
public Step step1() {
  return stepBuilderFactory.get("step1")
    .<User, User>chunk(10)
    .reader(reader())
    .processor(processor())
    .writer(writer())
    .build();
  }