OAuth2 etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
OAuth2 etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

21 Eylül 2021 Salı

SpringSecurity OAuth2 Client ClientRegistration Sınıfı

Giriş
Şu satırı dahil ederiz
import org.springframework.security.oauth2.client.registration.ClientRegistration;
ClientRegistration Nedir?
Açıklaması şöyle
A client registration holds information, such as client id, client secret, authorization grant type, redirect URI, scope(s), authorization URI, token URI, and other details.
Örnek
Şöyle yaparız
private ClientRegistration createClientRegistration() {
  return ClientRegistration.withRegistrationId("onelogin")
      .clientId(oneLoginConfigs.getClientId())
      .clientSecret(oneLoginConfigs.getClientSecret())
      .clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
      .authorizationUri("https://company.onelogin.com/oidc/2/auth")
      .tokenUri("https://company.onelogin.com/oidc/2/token")
    
  .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
      .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}")
      .scope("openid", "profile", "email”)
      .userInfoUri("https://company.onelogin.com/oidc/2/me")
      .userNameAttributeName(IdTokenClaimNames.SUB)
      .jwkSetUri("https://company.onelogin.com/oidc/2/certs")
      .clientName("Zoo")
      .build();
}

SpringSecurity OAuth2 Client ClientRegistrationRepository Arayüzü

Giriş
Şu satırı dahil ederiz
import org.springframework.security.config.annotation.web.configurers.oauth2.client.
registration.ClientRegistrationRepository;
Bu arayüzden sadece InMemoryClientRegistrationRepository kalıtır

InMemoryClientRegistrationRepository Sınıfı
ClientRegistration yazısına bakabilirsiniz

constructor - ClientRegistration
Örnek
Şöyle yaparız
@Bean
public ClientRegistrationRepository clientRegistrationRepository() {
  return new InMemoryClientRegistrationRepository(createClientRegistration());
}

private ClientRegistration createClientRegistration() {
  ...
}

15 Aralık 2020 Salı

SpringSecurity OAuth2 AuthorizationServerConfigurerAdapter Sınıfı - Authorization Code Grant - Kullanmayın

Giriş 
"Spring Security OAuth" projesi artık deprecated. Bu yüzden bu sınıfı kullanmayın

Bu kullanımda "Authorization Code Grant" gerçekleştiriliyor.  OAuth2 Grant Tipleri yazısına bakabilirsiniz.

Bu akışta "confidential clients" yani güvenilen client' lara token verilir.

Bir örnek burada

Adımlar
1 Önce AuthorizationCode almamız gerekir
2. Authorization Code ile Access Token almamız gerekir

Kendi uygulamamızda "Login With Facebook" gibi bir link bulunur. Bu linke tıklanınca kullanıcı benim sunucuma gelir. Link şöyledir
localhost:8080/oauth/authorize?response_type=code&client_id=clientId&state=8781487s1
Link'in açıklaması şöyle
To get authorization code we need to request the server and redirect you to the auth server's login page if you're not authenticated. To get the code, we hit /oauth/authorize with a few required params.

- response_type = must set to code (Required)
- client_id = clientId that we set up in auth server (Required)
- state = Some random value to maintain state between server and client(Optional)
- redirect_uri = optional 
Bu linki karşılayan kod için şöyle yaparız. Bu kod iki tane adrese hizmet verir. Bunlar şöyle
localhost:8080/oauth/authorize?...
localhost:8080/oauth/token?grant_type=authorization_code&...
localhost:8080/oauth/authorize?... adresine gelince kod önce bizi bir form login sayfasına yönlendirir. Eğer login başarılı ise bizi redirectUris() ile tanımlanan adrese yönlendirir. 8081 portunu dinleyen kendi uygulamama yönlendirdiği görülebilir.
@SuppressWarnings("deprecation")
@Configuration
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
  @Bean("passwordEncoder")
  BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

  @Override
  public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients
      .inMemory()
        .withClient("clientId") //Linkteki client_id değeri
        .secret(passwordEncoder().encode("client-secret"))
        .scopes("read", "write")
        .authorizedGrantTypes("authorization_code", "refresh_token")
        .redirectUris("http://localhost:8081/oauth/login/client-app")
        .autoApprove(true);
     }

  @Bean
  JwtTokenStore getAccessTokenConverter() {
    return new JwtTokenStore(JwtTokenEnhancer.getInstance());
  }
}
Kullanıcı tanımlama için şöyle yaparız
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Autowired
  @Qualifier("passwordEncoder")
  BCryptPasswordEncoder passwordEncoder;
  
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
      .withUser("username")
      .password(passwordEncoder.encode("password"))
      .roles("USER");
  }
  
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .anyRequest()
      .authenticated().and()
        .formLogin().permitAll()
      .and()
         .logout().permitAll();
    http.csrf().disable();
  }
}
Access Token Alma
Şöyle yaparız
POST /oauth/token?grant_type=authorization_code& code=X2KnGB& client_Id=clientId&state=8781487s1 HTTP/1.1
Host: localhost:8080
Authorization: Basic Y2xpZW50SWQ6Y2xpZW50LXNlY3JldA==
cache-control: no-cache
Çıktı olarak şunu alırız
{
  "access_token": "U9c7fB35jHh6vW-WsBd-VdfLcOs",
  "token_type": "bearer",
  "refresh_token": "hGMk8bgNwO7YHrKaCZkc380BB68",
  "expires_in": 43199,
  "scope": "read write"
}
Burada access token bir de public/private key ile de imzalanıyor. Bu gerekli mi bilmiyorum. Şöyle yaparız
public class JwtTokenEnhancer extends JwtAccessTokenConverter {
  private static final String PRIVATE_KEY = "Your private rsa key";
  private static final String PUBLIC_KEY = "Your public rsa key";
    
  public JwtTokenEnhancer(String publicKey, String privateKey) {
    super.setSigningKey(privateKey);
    super.setVerifierKey(publicKey);
  }
  public static JwtAccessTokenConverter getInstance() {
    return new JwtTokenEnhancer(JwtTokenEnhancer.PUBLIC_KEY, JwtTokenEnhancer.PRIVATE_KEY);
  }
}





25 Kasım 2020 Çarşamba

SpringSecurity OAuth2 Login application.properties Ayarları

Giriş
Facebook, GitHub, google ile login için kullanılabilir. Kaç tane OAuth2 Login sağlayıcı ayarladıysak giriş sayfasında görünür. Giriş sayfası şöyledir


Google
Örnek 
Şöyle yaparız. 
spring.security.oauth2.client.registration.google.client-id=<Client-Id>
spring.security.oauth2.client.registration.google.client-secret=<Client-Secrete>
Örnek
Şöyle yaparız
spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: google-client-id
            client-secret: google-client-secret
GitHub
Örnek 
Şöyle yaparız. 
spring.security.oauth2.client.registration.github.client-id=<Client-Id>
spring.security.oauth2.client.registration.github.client-secret=<Client-Secrete>
Örnek 
Şöyle yaparız. Client nesnesi Authorization Server'dan token alabilir.
spring:
  security:
    oauth2:
      client:
        registration:
          github:
            client-id: your-github-client-id
            client-secret: your-github-client-secret
Facebook
Örnek 
Şöyle yaparız. 
spring.security.oauth2.client.registration.facebook.client-id=<Client-Id>
spring.security.oauth2.client.registration.facebook.client-secret=<Client-Secrete>
spring.security.oauth2.client.registration.facebook.redirect-uri=http://localhost:8080/api/v1/myapp
Örnek
Şöyle yaparız
spring:
  security:
    oauth2:
      client:
        registration:
           facebook:
              clientId: myID
              clientSecret: mySecret
              accessTokenUri: https://graph.facebook.com/oauth/access_token
              userAuthorizationUri: https://www.facebook.com/dialog/oauth
              tokenName: oauth_token
              authenticationScheme: query
              clientAuthenticationScheme: form
              resource:
                 userInfoUri: https://graph.facebook.com/me

server:
  port: 8080

31 Mayıs 2020 Pazar

SpringSecurity OAuth2 AuthorizationServerConfigurerAdapter Sınıfı - Kendi OAuth2 Authorization Sunucumuz İçin

Giriş
Bu sınıf maintenance modda.@EnableAuthorizationServer yazısına bakabilirsiniz.

Daha derli doplu bir yazı için Authorization Code Grant yazısına bakabilirsiniz

Örnek
Şöyle yaparız.
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends
  AuthorizationServerConfigurerAdapter {

  @Autowired
  private AuthenticationManager authenticationManager;

  @Autowired
  private UserDetailsService userDetailsService;

  @Autowired
  private PasswordEncoder passwordEncoder;

  @Autowired
  private TokenStore tokenStore;

  @Autowired
  private SecurityConfiguration securityConfiguration;
  ...
  
}
Bu sınıfın 3 temel metodu var

configure metodu - AuthorizationServerSecurityConfigurer
İmzası şöyle. Bu metod'da hep aynı şey yapılıyor.
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception;
Örnek
Şöyle yaparız.
@Override
public void configure(AuthorizationServerSecurityConfigurer security) {
  security.tokenKeyAccess("permitAll()")
    .checkTokenAccess("isAuthenticated()");
}
Örnek
Eğer kullanıcı bilgisi şifreli gelsin istersek şöyle yaparız. PasswordEncoder olarak örneğin BCryptPasswordEncoder kullanılabilir
@Override
public void configure(AuthorizationServerSecurityConfigurer security) {
  security.tokenKeyAccess("permitAll()")
    .checkTokenAccess("isAuthenticated()")
    .passwordEncoder(this.passwordEncoder);
}
Örnek
Şöyle yaparız
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer){
  oauthServer
    .tokenKeyAccess("permitAll()")
    .checkTokenAccess("permitAll()")
    .passwordEncoder(passwordEncoder)
    .allowFormAuthenticationForClients();
}
configure - ClientDetailsServiceConfigurer - Kullanıcı Bilgileri
İmzası şöyle. Kullanıcı bilgileri ve token ile ilgili ayarlar burada yapılır.
@Override
 public void configure(ClientDetailsServiceConfigurer clients) throws Exception;
authorizedGrantTypes "authorization_code", "client-credentials", "password","refresh_token" seçeneklerini alabilir.
Açıklama şöyle
grant_type means the client can get access_token by client username and password or refresh_token.
Örnek
Şöyle yaparız. Burada authorizedGrantTypes() metoduna "password" geçildiği için client şifresini gönderip token alabilir.
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  clients.inMemory().withClient("client")
    .secret(passwordEncoder.encode(("secret")))
    .authorizedGrantTypes("password")
    .scopes("webclient","mobileclient");
}
Örnek
Şöyle yaparız. Burada authorizedGrantTypes() metoduna "password" ve "refresh_token" geçildiği için client şifresini gönderip token alabilir. Token'ı yenileyebilir.
clients.inMemory()
  .withClient(...)
  .authorizedGrantTypes("password", "refresh_token")
  .scopes("mobile_app")
  .resourceIds(...)
  .accessTokenValiditySeconds(...)
  .refreshTokenValiditySeconds(...)
  .secret(...);
Örnek
Şöyle yaparız
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  //IN-memory authentication configuration
  clients.inMemory()
      .withClient("web-portal")
      .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
      .scopes("ui")
      .autoApprove(true)
      .secret(passwordEncoder.encode("password"))
      .redirectUris("http://localhost:8093/socialDiagnostica/login/oauth2/code/")
    .and()
      withClient("mobile-app")
      authorizedGrantTypes("client_credentials", "refresh_token", "password")
      scopes("ui")
      .autoApprove(true)
      .secret(passwordEncoder.encode("password"))
    .and()
      .withClient("social-diagnostica-service")
      .secret(passwordEncoder.encode("password"))
      .authorizedGrantTypes("client_credentials", "refresh_token")
      .scopes("server")
      .autoApprove(true);
//clients.jdbc(dataSource);
}
configure - AuthorizationServerEndpointsConfigurer - TokenStore ve AuthenticationManager Ayarları
Authorization için kullanılack endpoint'lerin ayarlarını yapabilmeyi sağlar.