16 Temmuz 2018 Pazartesi

SpringSecurity AuthenticationManager Arayüzü

Giriş
Şu satırı dahil ederiz
import org.springframework.security.authentication.AuthencticationManager;
Kendisine takılan AuthenticatonProvider nesnelerini kullanarak kullanıcıyı doğrular. Aslında bu arayüzü gerçekleştiren bir sınıf ProviderManager. Yani bu arayüzü gerçekleştirmeye gerek yok. Açıklaması şöyle
You can provide a list of your custom AuthenticationProvider instances as a chain to AuthenticationManager.

Exceptions that extends AccountStatusException:
- A DisabledException must be thrown if an account is disabled.
- A LockedException must be thrown if an account is locked.
- An AccountExpiredException must be thrown if the account has expired.
- A BadCredentialsException must be thrown if incorrect credentials are provided via authentication request.
authenticate metodu
Bu metod bir Authentication nesnesini parametre olarak alır ve yine Authentication nesnesini sonuç olarak döner. Authentication nesnesi örneğin UsernamePasswordAuthenticationToken sınıfı olabilir. Eğer authentication.isAuthenticated() çağrısı true dönerse bu token SecurityContextHolder nesnesinde saklanır.

Örnek
Şöyle yaparız
@Controller
public class DbLoginController {
    private final AuthenticationManager authenticationManager;
    ...
  @PostMapping("/form-login")
  public String doLogin(@ModelAttribute DbAuthCredentials credentials) {
    try {
      Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(credentials.getUserName(),
        credentials.getPassword()));
      if (authentication.isAuthenticated()) {
        SecurityContextHolder.getContext().setAuthentication(authentication);
      } else {
       throw new Exception("Unauthenticated");
      }
      ...
    }
}
Örnek
Şöyle yaparız.
@Service
public class SecurityServiceImpl implements SecurityService {

    private AuthenticationManager authenticationManager;

  @Override
  public void autoLogin(String email, String parole) {

    UserDetails userDetails = ...;
    UsernamePasswordAuthenticationToken authenticationToken =
       new UsernamePasswordAuthenticationToken(userDetails, parole,
                                               userDetails.getAuthorities());

    authenticationManager.authenticate(authenticationToken);

    if(authenticationToken.isAuthenticated()){
      SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }
  }
}

Hiç yorum yok:

Yorum Gönder