Annexe TP Spring Security: Step 1
Annexe TP Spring Security: Step 1
Step 1
http://start.spring.io
Java version + Dependensies
Create a new package a new java class controller
@RestController
@RequestMapping ("api/v1/students")
@GetMapping (path="{studentId}")
return STUDENTS.stream()
.filter(student ->
studentId.equals(student.getStudentId()))
.findFirst()
.orElseThrow(()-> new IllegalStateException("Student"
+ studentId +"N'existe pas"));
}
}
1
Step 2: A form based authentication
Open pom.xml
Add <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Open pom.xml
Relaunche : localhost:8080/api/v1/students/1
Username : user
Password :
2
Step 4: Basic Authentication
@Configuration
@EnableWebSecurity
http
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
}
Step 5: Postman
Send a GET request to localhost:8080/api/v1/students/1 o
401 unauthorized
Send a GET request to localhost:8080/api/v1/students/1
o Authorization Type Basi Auth login password (200 OK)
3
Step 6: Whitlist some URLs
Go to ressources > statics > create new index.html file
<h1>ssss</h1> Update AppSecurityConfig
o .authorizeRequests()
.antMatchers("/", "index", "/css/*", "/js/*")
.permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic();
@Overrid
e @Bean
protected UserDetailsService userDetailsService()
{ UserDetails adamUser = User.builder()
.username("Adam")
.password("pwd")
.roles("STUDENT")
.build();
return new InMemoryUserDetailsManager(
adamUser
);
Error
4
Step 8: Password Encoder
Create a new Java class : PasswordConfig
@Configuration
Update AppSecurityConfig
@Overrid
e @Bean
protected UserDetailsService userDetailsService()
{ UserDetails adamUser = User.builder()
.username("Adam")
.password(passwordEncoder.encode("pwd"))
.roles("STUDENT")
.build();
It works just fine.
Add anchor point to see the passwordEncoder
5
Step 9: Roles & permissions
Chaque Rôle possède des permissions (Read, write, …)
Add a role (update AppSecurityConfig)
AppUserPermission(String permission) {
this.permission = permission;
}
AppUserRole(Set<AppUserPermission> permissions)
{ this.permissions = permissions;
}
6
Step 10: Role based auth
Update AppSecurityConfig
.hasRole(AppUserRole.Admin.name())
);
@GetMapping
public List<Student> getAllStudent(){
return STUDENTS;
}
@PostMapping
public void registerNewStudent (@RequestBody Student student)
{ System.out.println(student);
}
@DeleteMapping (path="{studentId}")
@PutMapping (path="{studentId}")
7
Try a PUT method to server > body > raw > JSON
Localhost……/students/1
Update AppSecurityConfig
http
.csrf().disable()
Restart a test postman POST and PUT
.antMatchers(HttpMethod.DELETE"/maganement/api/**").hasAuthority(COURSE_WRI
TE.name())
.antMatchers(HttpMethod.POST"/maganement/api/**").hasAuthority(COURSE_WRITE .name())
.antMatchers(HttpMethod.PUT"/maganement/api/**").hasAuthority(COURSE_WRITE.
name())
.antMatchers(HttpMethod.GET"/maganement/api/**").hasAnyRole(AppUserRole.ADM
IN.name(), AppUserRole.ADMINTREENEE.name())
Explore more next session
8
Step 14: CSRF Config
In postman Install interceptor
coockies Enable coockies capture
9
Delete csrf.disable()
Send a GET request, and Inspect
coockies XSRF-TOKEN and copy the value
10
Add .formLogin();
Right click, inspection > application > Cookies > JSESSIONID
11
Add new dependency in pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-
thymeleaf</artifactId> </dependency>
Go to ressources and create a new package > templates
o Create a new page >login.html > <h1>Login Page</h1>
Create a new package In the main arborescence > controller
o Create a new java class >
templateController @Controller
@RequestMapping("/")
public class TemplateController
{ @GetMapping ("login")
public String getLoginView() {
return "login";
}
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities()
{ return grantedAuthorities;
}
12
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return isAccountNonExpired;
}
@Override
public boolean isAccountNonLocked() {
return isAccountNonLocked;
}
@Override
public boolean isCredentialsNonExpired()
{ return isCredentialsNonExpired;
}
@Override
public boolean isEnabled() {
return isEnabled;
}
}
}
}
13
this.applicationUserDao = applicationUserDao;
}
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
return applicationUserDao
.SelectApplicationUserByUsername(username)
.orElseThrow(()-> new
UsernameNotFoundException(String.format("Username %s not found",
username)));
}
}
Create a Java Class > FakeApplicationUserDaoService
@Repository("fake")
public class FakeApplicationUserDaoService
implements ApplicationUserDao {
@Autowired
public FakeApplicationUserDaoService(PasswordEncoder
passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
@Override
public Optional<ApplicationUser>
SelectApplicationUserByUsername(String username) {
return getApplicationUsers()
.stream()
.filter(applicationUser ->
username.equals(applicationUser.getUsername()))
.findFirst();
}
);
return applicationUsers;
}
}
Update ApplicationUserServer
@Autowired
public ApplicationUserService(@Qualifier("fake")ApplicationUserDao
applicationUserDao) {
this.applicationUserDao = applicationUserDao;
}
Update AppSecurityConfig
o Delete userDetailsService*
14
private final ApplicationUserService applicationUserService;
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.authenticationProvider(daoAuthenticationProvider());
}
@Bean
15