0
0
Spring Bootframework~10 mins

Why authorization matters in Spring Boot - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to check if a user has the right role before accessing a resource.

Spring Boot
if (authentication.getAuthorities().contains(new SimpleGrantedAuthority([1]))) {
    // allow access
}
Drag options to blanks, or click blank then click option'
A"ROLE_MANAGER"
B"ROLE_ADMIN"
C"GUEST"
D"USER"
Attempts:
3 left
💡 Hint
Common Mistakes
Using role names without 'ROLE_' prefix
Checking for a role the user does not have
2fill in blank
medium

Complete the code to restrict access to a method only to users with the ADMIN role using annotation.

Spring Boot
@PreAuthorize([1])
public void deleteUser(Long id) {
    // deletion logic
}
Drag options to blanks, or click blank then click option'
A"hasRole('ADMIN')"
B"hasRole('USER')"
C"hasAuthority('GUEST')"
D"permitAll()"
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong role name
Using permitAll() which allows everyone
3fill in blank
hard

Fix the error in the code that checks user roles in a service method.

Spring Boot
if (authentication.getAuthorities().stream().anyMatch(auth -> auth.getAuthority().equals([1]))) {
    // proceed
}
Drag options to blanks, or click blank then click option'
A"ROLE_ADMIN"
B"ADMIN"
C"ROLE_USER"
D"USER"
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the 'ROLE_' prefix
Using a role name that does not exist
4fill in blank
hard

Fill in the blank to create a method that returns true if the user has the ADMIN role and false otherwise.

Spring Boot
public boolean isAdmin(Authentication authentication) {
    return authentication.getAuthorities().stream()
        .anyMatch(auth -> auth.getAuthority().equals([1]));
}
Drag options to blanks, or click blank then click option'
A"ADMIN"
B"ROLE_USER"
C"USER"
D"ROLE_ADMIN"
Attempts:
3 left
💡 Hint
Common Mistakes
Using incomplete role names
Checking for the wrong role
5fill in blank
hard

Fill in the blanks to configure HTTP security to allow only ADMIN users to access '/admin/**' endpoints.

Spring Boot
http.authorizeHttpRequests()
    .requestMatchers([1])
    .hasRole([2])
    .anyRequest().authenticated();
Drag options to blanks, or click blank then click option'
A"/admin/**"
B"ADMIN"
C"USER"
D"/user/**"
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong URL patterns
Using full role names in hasRole() which expects role without prefix