0Pricing
GraphQL APIs with Spring Boot · Ders

Spring Security ile Kimlik Doğrulama

GraphQL uç noktalarınızı korumak ve kullanıcı kimlik doğrulamasını yönetmek için Spring Security'yi bütünleştirin.

Spring Security ile Kimlik Doğrulama, CoddyKit'te ücretsiz bir GraphQL APIs with Spring Boot dersidir. Bu, 4 dersinin 2. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, GraphQL APIs with Spring Boot öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. GraphQL APIs with Spring Boot kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

Why Auth for GraphQL?

Welcome! In this lesson, we'll integrate Spring Security with our GraphQL API. While GraphQL defines how to query and mutate data, it doesn't specify authentication or authorization.

Protecting your API is crucial to ensure only authorized users can access sensitive data and perform specific actions. Spring Security is a powerful and flexible framework for this.

Spring Security Basics

Spring Security is a comprehensive security framework for Spring applications. It provides authentication (verifying who you are) and authorization (what you're allowed to do).

  • Authentication: Verifies a user's identity (e.g., username/password).
  • Authorization: Determines if an authenticated user has permission to access a resource or perform an action.

We'll start with basic authentication, which is simple to set up for testing.

Add Security Dependency

First, we need to add the Spring Security starter dependency to our Spring Boot project. This brings in all the necessary components for security.

Add the following to your pom.xml file:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Don't forget to also include your GraphQL starter, e.g., spring-boot-starter-graphql if you haven't already.

Configure Basic In-Memory Auth

For a quick start, Spring Security can use in-memory user details. We define a SecurityFilterChain bean to configure the HTTP security rules.

This setup creates two users: 'user' and 'admin', both with a password 'password' (encoded using BCrypt) and different roles.

package com.coddykit;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
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.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .httpBasic();
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
        UserDetails user = User.builder()
            .username("user")
            .password(passwordEncoder.encode("password"))
            .roles("USER")
            .build();
        UserDetails admin = User.builder()
            .username("admin")
            .password(passwordEncoder.encode("password"))
            .roles("ADMIN", "USER")
            .build();
        return new InMemoryUserDetailsManager(user, admin);
    }

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

Protecting GraphQL Paths

Now, let's explicitly secure our GraphQL endpoints. We want to make sure that only authenticated users can access the /graphql endpoint where our API lives.

We can modify the SecurityFilterChain to specify access rules for specific paths. For example, requiring the 'USER' role to access GraphQL.

package com.coddykit;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
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.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable()) // Disable CSRF for API (consider for production)
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/graphql/**", "/graphiql/**").hasAnyRole("USER", "ADMIN")
                .anyRequest().authenticated()
            )
            .httpBasic();
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
        UserDetails user = User.builder()
            .username("user")
            .password(passwordEncoder.encode("password"))
            .roles("USER")
            .build();
        UserDetails admin = User.builder()
            .username("admin")
            .password(passwordEncoder.encode("password"))
            .roles("ADMIN", "USER")
            .build();
        return new InMemoryUserDetailsManager(user, admin);
    }

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

A Simple GraphQL Query

To test our security, let's create a very basic GraphQL query. This query will simply return a greeting message. We'll then try to access it with and without authentication.

This demonstrates a minimal GraphQL API that Spring Security will protect.

package com.coddykit;

import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;

@Controller
public class GreetingController {

    @QueryMapping
    public String hello() {
        return "Hello, secured GraphQL world!";
    }
}

Full Secure App Example

Here's a complete Spring Boot application integrating Spring Security with a GraphQL endpoint. Run this code, then try to access http://localhost:8080/graphql or /graphiql.

You should be prompted for a username and password (e.g., 'user'/'password'). Without them, access will be denied.

package com.coddykit;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
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.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.stereotype.Controller;

@SpringBootApplication
public class SecuredGraphQLApp {

    public static void main(String[] args) {
        SpringApplication.run(SecuredGraphQLApp.class, args);
    }
}

@Controller
class GreetingController {

    @QueryMapping
    public String hello() {
        return "Hello, secured GraphQL world!";
    }
}

@Configuration
@EnableWebSecurity
class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/graphql/**", "/graphiql/**").hasAnyRole("USER", "ADMIN")
                .anyRequest().authenticated()
            )
            .httpBasic();
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
        UserDetails user = User.builder()
            .username("user")
            .password(passwordEncoder.encode("password"))
            .roles("USER")
            .build();
        UserDetails admin = User.builder()
            .username("admin")
            .password(passwordEncoder.encode("password"))
            .roles("ADMIN", "USER")
            .build();
        return new InMemoryUserDetailsManager(user, admin);
    }

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

Custom UserDetailsService

In-memory users are great for development, but real applications need to load user data from a database or external service. This is where a custom UserDetailsService comes in.

You'd implement this interface to fetch user details (username, password, roles) based on the provided username. Spring Security then uses this to authenticate the user.

package com.coddykit;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;

@Service
public class MyCustomUserDetailsService implements UserDetailsService {

    private final PasswordEncoder passwordEncoder;

    public MyCustomUserDetailsService(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // In a real app, you'd fetch this from a DB
        // For demonstration, let's hardcode a user
        if ("coddy".equals(username)) {
            return User.builder()
                .username("coddy")
                .password(passwordEncoder.encode("secret")) // Stored encoded password
                .roles("USER")
                .build();
        } else {
            throw new UsernameNotFoundException("User not found: " + username);
        }
    }
}

Understanding PasswordEncoder

Never store passwords in plain text! PasswordEncoder is an interface for encoding and verifying passwords. BCryptPasswordEncoder is a strong, widely recommended implementation.

  • Encoding: Transforms a plain-text password into a secure hash.
  • Matching: Compares a raw password with an encoded one.

Spring Security automatically uses the PasswordEncoder bean you provide to handle password verification.

Security Integration Check

You've learned how to set up basic authentication for your GraphQL API. Let's test your understanding of the key components involved.

Lesson Recap: Secure Your API

Great job! You've learned how to integrate Spring Security to protect your GraphQL endpoints. We covered:

  • The importance of authentication for GraphQL APIs.
  • Adding the Spring Security dependency.
  • Configuring a SecurityFilterChain for basic authentication.
  • Protecting specific GraphQL paths.
  • Implementing a custom UserDetailsService for real-world user management.
  • Using PasswordEncoder for secure password handling.

This lays the foundation for building robust and secure GraphQL APIs. Next, you'll explore authorization to control access to fields and operations!

Sıkça Sorulan Sorular

“Spring Security ile Kimlik Doğrulama” dersi ücretsiz mi?

Evet — “Spring Security ile Kimlik Doğrulama” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve GraphQL APIs with Spring Boot kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. GraphQL APIs with Spring Boot kursu toplamda 4 dersten oluşur.

“Spring Security ile Kimlik Doğrulama” dersinde ne öğreneceğim?

GraphQL uç noktalarınızı korumak ve kullanıcı kimlik doğrulamasını yönetmek için Spring Security'yi bütünleştirin. GraphQL APIs with Spring Boot ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

GraphQL APIs with Spring Boot öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te GraphQL APIs with Spring Boot, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 2. dersidir.

“Spring Security ile Kimlik Doğrulama” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu GraphQL APIs with Spring Boot dersinde kod yazıp çalıştırabilir miyim?

Evet. Her GraphQL APIs with Spring Boot dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. GraphQL'de Özel Hata Yönetimi
  2. Spring Security ile Kimlik Doğrulama
  3. Yönergeler ve Bağlam ile Yetkilendirme
  4. Hız Sınırlama ve Sorgu Derinliği Koruması
← GraphQL APIs with Spring Boot Sayfasına Dön