7 Mayıs 2018 Pazartesi

SpringSecurity AuthenticationEntryPoint Arayüzü - Authentication Başarısız İse Bu Sınıf Çağrılır

Giriş
Şu satırı dahil ederiz.
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
Bu arayüzden kalıtan BasicAuthenticationEntryPoint sınıfı var

Authentication Başarısız İse Bu Sınıf Çağrılır
Akış şöyle. Bu arayüzün ismi AuthenticationEntryPoint  ancak aslında Authentication başarısız ise çağrılır.














Authentication Zincirine Takmak
Örnek - HttpSecurity
Şöyle yaparız.
HttpSecurity http = ...;
http.authorizeRequests().antMatchers("/rest/user/login").permitAll();
http.csrf().disable()
  .authenticationProvider(authenticationProvider())
  .exceptionHandling()
  .authenticationEntryPoint(unauthorizedHandler)
Örnek - Basic Authentication
401 + Json  dönmek için kullanılabilir.

Şöyle yaparız.
http.httpBasic()
  .authenticationEntryPoint(restAuthenticationEntryPoint)
Döndürülen Değerler
Örnek

Açıklaması şöyle.
In a standard web application, the authentication process may be automatically triggered when the client tries to access a secured resource without being authenticated – this is usually done by redirecting to a login page so that the user can enter credentials. However, for a REST Web Service, this behavior doesn’t make much sense – Authentication should only be done by a request to the correct URI and all other requests should simply fail with a 401 UNAUTHORIZED status code if the user is not authenticated.

Spring Security handles this automatic triggering of the authentication process with the concept of an Entry Point
401 Unauthorized dönmek için şöyle yaparız.
@Component
public final class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

  @Override
  public void commence(final HttpServletRequest request,
                       final HttpServletResponse response,
                       final AuthenticationException authException) throws IOException {

    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
  }
}
Şöyle yaparız.
HttpSecurity http = ...

http //Authorization
  .csrf().disable()
  .exceptionHandling()
  .authenticationEntryPoint(restAuthenticationEntryPoint)
  .and()
Örnek
Hata mesajı olarak exception mesajını dönmek için şöyle yaparız.
@Component
public class UnauthorizedHandler implements AuthenticationEntryPoint {
  @Override
  public void commence(
            HttpServletRequest request,
            HttpServletResponse response,
            AuthenticationException authException) throws IOException {

    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
  }
}


Hiç yorum yok:

Yorum Gönder