Skip to content

Commit 7166e1f

Browse files
committed
UserDetails service has been implemented.
1 parent 64acebb commit 7166e1f

File tree

4 files changed

+157
-15
lines changed

4 files changed

+157
-15
lines changed

day-10/api/Security.md

Lines changed: 95 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
# 1. Bağımılılık
1+
# 1. Basic Authentication
2+
## 1.1. Dependency
23

34
Öncelikle projeye yeni bir bağımlılık eklenir.
45

@@ -13,7 +14,7 @@ Yukarıdkai bağımlılık ifadesiyle artık API güvenliği ilk adım atılır.
1314
* Logout olma şansı yoktur.
1415
* Kullanıcı adı ve şifresine müdahale edilemez.
1516

16-
# 2. Application Security Config
17+
## 1.2. Application Security Config
1718

1819
**security/config** gibi bir isimle yeni bir klasör projeye dahil edilir.
1920

@@ -34,7 +35,7 @@ public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {
3435
}
3536
```
3637

37-
# 3. Authentication Nasıl Yapılır?
38+
## 1.3. Authentication Nasıl Yapılır?
3839
Bu metot üzerinde authentication işleminin nasıl yapılması gerektiği tanımlanır. Basic Authentication ile API güvenliğini sağlayalım.
3940

4041
```java
@@ -56,4 +57,94 @@ public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {
5657
Bu işlem sonucunda herhangi bir kaynak üzerinden GET, POST, PUT ve DELETE işlemlerinin yapılması tavsiye edilir.
5758
User ve password bilgisi girilmeden hiçbir http isteği yanıtlanmaz iken; user ve password bilgisi bir Authorization header ifadesiyle gönderildiğinde yalnızca GET isteklerinin yanıtlandığı ancak POST, PUT ve DELETE gibi işlemlerin ise yanıtlanmadığı (Forbidden) yani yasaklandığı görülür.
5859

59-
![Basic Authentication](http://www.zafercomert.com/medya/java/springSecurity-BasicAuth.svg)
60+
![Basic Authentication](http://www.zafercomert.com/medya/java/springSecurity-BasicAuth.svg)
61+
62+
63+
# 2. UserDetailsService
64+
65+
## 2.1. UserDetailsService
66+
67+
**UserDetailService** üzerinden kullanıcı tanımları gerçekleştirebilir. Bu noktada kullanıcı bilgilerini tutmak üzere **InMemoryUserDetailsManager** kullanıyoruz.
68+
69+
Ancak **UserDetailService** implemente eden daha farklı sınıflar da vardır. Detaylar için resmi dokümantasyon incelenebilir [Interface UserDetailsService](https://docs.spring.io/spring-security/site/docs/3.2.8.RELEASE/apidocs/org/springframework/security/core/userdetails/UserDetailsService.html).
70+
71+
**UserDetailService** interface yapısını implemente eden sınıflar:
72+
73+
* CachingUserDetailsService,
74+
* InMemoryDaoImpl,
75+
* *InMemoryUserDetailsManager*,
76+
* JdbcDaoImpl,
77+
* JdbcUserDetailsManager,
78+
* LdapUserDetailsManager,
79+
* LdapUserDetailsService,
80+
* UserDetailsServiceWrapper
81+
82+
```java
83+
@Override
84+
@Bean
85+
protected UserDetailsService userDetailsService() {
86+
87+
UserDetails admin = User.builder()
88+
.username("admin")
89+
.password(passwordEncoder.encode("admin123456"))
90+
.roles("ADMIN")
91+
.build();
92+
93+
UserDetails editor = User.builder()
94+
.username("editor")
95+
.password(passwordEncoder.encode("editor123456"))
96+
.roles("EDITOR")
97+
.build();
98+
99+
UserDetails user = User.builder()
100+
.username("user")
101+
.password(passwordEncoder.encode("user123456"))
102+
.roles("USER")
103+
.build();
104+
105+
return new InMemoryUserDetailsManager(admin, editor, user);
106+
}
107+
```
108+
> UserDetailsService de bir konfigürasyon ifadesidir. Bu nedenle @Bean annotation yapısı mutlaka bu metodun üzerine eklenmelidir.
109+
110+
Uygulamanın bu haliyle yukarıda verilen kullanıcı adı ve şifreler ile artık API test edilebilir durumdadur.
111+
112+
## 2.2 PasswordEncoder
113+
114+
```java
115+
@Configuration
116+
public class PasswordConfig {
117+
118+
@Bean
119+
public PasswordEncoder passwordEncoder() {
120+
return new BCryptPasswordEncoder(10);
121+
}
122+
}
123+
```
124+
125+
Injection unutulmamalıdır:
126+
127+
```java
128+
private final PasswordEncoder passwordEncoder;
129+
130+
@Autowired
131+
public ApplicationSecurityConfig(PasswordEncoder passwordEncoder) {
132+
this.passwordEncoder = passwordEncoder;
133+
}
134+
```
135+
136+
## 2.3. configure Metodu Güncellenir.
137+
138+
```java
139+
@Override
140+
protected void configure(HttpSecurity http) throws Exception {
141+
http
142+
.authorizeRequests()
143+
.antMatchers("/", "/index", "/css/*", "/js/**").permitAll()
144+
.antMatchers("/api/**").hasAnyRole("ADMIN", "EDITOR")
145+
.anyRequest()
146+
.authenticated()
147+
.and()
148+
.httpBasic();
149+
}
150+
```
Lines changed: 48 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,59 @@
11
package com.bookstore.api.config;
22

3+
import org.springframework.context.annotation.Bean;
34
import org.springframework.context.annotation.Configuration;
45
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
56
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
67
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
8+
import org.springframework.security.core.userdetails.User;
9+
import org.springframework.security.core.userdetails.UserDetails;
10+
import org.springframework.security.core.userdetails.UserDetailsService;
11+
import org.springframework.security.crypto.password.PasswordEncoder;
12+
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
13+
14+
import lombok.RequiredArgsConstructor;
715

816
@Configuration
917
@EnableWebSecurity
18+
@RequiredArgsConstructor
1019
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {
11-
@Override
12-
protected void configure(HttpSecurity http) throws Exception {
13-
http
14-
.authorizeRequests()
15-
.anyRequest()
16-
.authenticated()
17-
.and()
18-
.httpBasic();
19-
}
20+
21+
private final PasswordEncoder passwordEncoder;
22+
23+
@Override
24+
protected void configure(HttpSecurity http) throws Exception {
25+
http
26+
.authorizeRequests()
27+
.antMatchers("/", "/index", "/css/*", "js/**").permitAll()
28+
.antMatchers("/api/**").hasAnyRole("ADMIN", "EDITOR")
29+
.anyRequest()
30+
.authenticated()
31+
.and()
32+
.httpBasic();
33+
}
34+
35+
@Override
36+
@Bean
37+
protected UserDetailsService userDetailsService() {
38+
39+
UserDetails admin = User.builder()
40+
.username("admin")
41+
.password(passwordEncoder.encode("admin123456"))
42+
.roles("ADMIN")
43+
.build();
44+
45+
UserDetails editor = User.builder()
46+
.username("editor")
47+
.password(passwordEncoder.encode("editor123456"))
48+
.roles("EDITOR")
49+
.build();
50+
51+
UserDetails user = User.builder()
52+
.username("user")
53+
.password(passwordEncoder.encode("user123456"))
54+
.roles("USER")
55+
.build();
56+
57+
return new InMemoryUserDetailsManager(admin, editor, user);
58+
}
2059
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.bookstore.api.config;
2+
3+
import org.springframework.context.annotation.Bean;
4+
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
6+
import org.springframework.security.crypto.password.PasswordEncoder;
7+
8+
@Configuration
9+
public class PasswordConfig {
10+
@Bean
11+
public PasswordEncoder passwordEncoder() {
12+
return new BCryptPasswordEncoder(10);
13+
}
14+
}

day-10/api/src/main/java/com/bookstore/api/controllers/AuthorController.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,13 @@
44

55
import org.springframework.http.HttpStatus;
66
import org.springframework.http.ResponseEntity;
7-
import org.springframework.web.bind.annotation.CrossOrigin;
87
import org.springframework.web.bind.annotation.DeleteMapping;
98
import org.springframework.web.bind.annotation.GetMapping;
109
import org.springframework.web.bind.annotation.PathVariable;
1110
import org.springframework.web.bind.annotation.PostMapping;
1211
import org.springframework.web.bind.annotation.PutMapping;
1312
import org.springframework.web.bind.annotation.RequestBody;
1413
import org.springframework.web.bind.annotation.RequestMapping;
15-
import org.springframework.web.bind.annotation.ResponseStatus;
1614
import org.springframework.web.bind.annotation.RestController;
1715

1816
import com.bookstore.api.entities.Author;

0 commit comments

Comments
 (0)