42-Securing-REST-Application Flashcards

1
Q

List out security concepts

A
Principal
Authentication
Authorization
Authority
Secure resource
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is authority?

A

Permission or credential enabling access. The most familiar example of authority is a role (string)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

List out 5 authentication mechanisms:

A
Basic
Digest
Form
X.509
OAuth
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is LDAP?

A

DAP: directory access protocol
LDAP: DAP using TCP/IP

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What does authorization do?

A

check if user has the required authority

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are the advantages of Spring Security?

A
  1. Portable: can use for any Spring project
  2. Separation of concerns
  3. Flexible & extensible: support many:
    a. authentication mechanisms
    b. storages
    c. customizable
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does AuthenticationManager do?

A
authenticate(Authentication) return full Authentication object if successful.
Throw AuthenticationException or sub-class if fails
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What inside Authentication?

A
  1. List of GrantedAuthority
  2. Principal: Object
  3. Credentials: Object
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What does AccessDecisionManager do?

A

Holding list of Voter to decide if the user allows accessing a secured resource

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

List out default voters in AccessDecisionManager

A
  1. RoleVoter: having the right role or not

2. AuthenticatedVoter: logged in as a valid user or not

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the result of AccessDecisionManager.decide()?

A
  1. AccessDeniedException: same as 403
  2. InsufficientAuthenticationException: same as 401
  3. successful otherwise
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

In the big picture of Spring Security, how do components work together to protects secured resources?

A
  1. AuthenticationManager populates SecurityContext with Authentication object
  2. Security Interceptor obtains SecurityContext and passes it to AccessDecisionManager to check
  3. If pass, allow access to the secured resource
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are the steps to setup Spring security in a web environment?

A
  1. Setup Filter Chain - Spring Boot does this for you
  2. Configure authorization rules
  3. Setup web authentication
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How springSecurityFilterChain works with DelegatingFilterProxy?

A
  1. DelegatingFilterProxy stays in front of DispatcherServlet
  2. DelegatingFilterProxy delegates request to springSecurityFilterChain to check authentication/authorization
  3. springSecurityFilterChain having a list of filters to check the permission
  4. If successful, DelegatingFilterProxy will forward the request to DispatcherServlet
    Note: all implement javax.servlet.Filter
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

List out default filters in springSecurityFilterChain

A
  1. SecurityContextPersistenceFilter
  2. LogoutFilter
  3. UsernamePasswordAuthenticationFilter
  4. ExceptionTranslationFilter
  5. FilterSecurityInterceptor: does the hard work of performing permission checking
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What does SecurityContextPersistenceFilter do?

A
  1. Finds security context in session and sets it for the current thread
  2. Stores security context back into session
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What does UsernamePasswordAuthenticationFilter do?

A

Puts Authentication into the SecurityContext on login request.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What does ExceptionTranslationFilter do?

A

Converts SpringSecurity exceptions into HTTP response or redirect

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the default username?

A

user

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How to configure custom security for your application?

A

@Configuration
@EnableWebSecurity // not need if Spring Boot
class ClassName extends WebSecurityConfigurerAdapter

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How to enable security in a web app?

A

Using @EnableWebSecurity if not using Spring Boot

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Ant style: /admin/* vs. /admin/**

A

/admin/** any path under /admin

/admin/* only matches /admin/xxx

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

antMatchers vs. mvcMatchers

A

Similar but there are some issue with antMatchers e.g. antMatchers(“/admin”) matches “/admin/”: potential security risk
mvcMatchers: recommended

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Overloads of mvcMatchers

A
  1. mvcMatchers(path1, path2)

2. mvcMatchers(httpMethod, path)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

hasRole vs. hasAnyRole

A

e. g. hasRole(roleName)

e. g. hasAnyRole(roleName1, roleName2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is the prefix value of authority?

A

ROLE_

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Write custom role checking?

A

Using SpEL:

mvcMatchers(“…”).access(“hasRole(‘ADMIN’) && hasRole(‘USER’)”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Service to get user?

A

UserDetailsService.loadUserByUsername(String username): UserDetails

29
Q

Web security: how to authorize a URL?

A
  1. Override WebSecurityConfigurerAdapter.configure(HttpSecurity)
  2. Using mvcMatcchers().hasRole()
30
Q

How to ignore all permission checking on static resources?

A
  1. Override WebSecurityConfigurerAdapter.configure(WebSecurity)
  2. web.ignoring().mvcMatchers(…)
31
Q

How to configure AuthenticationManager?

A

Override WebSecurityConfigurerAdapter.configure(AuthenticationManagerBuilder)

32
Q

What is the authentication flow for basic authentication?

A
  1. Request goes to BasicAuthenticationFilter (extends UsernamePasswordAuthenticationToken)
  2. Calling auth = AuthenticationManager.authenticate(Authentication)
    a. Fail if throwing AuthenticationException
    b. Fully Authentication object otherwise
  3. AuthenticationManager is a ProviderManager that contains a list of AuthenticationProvider
    a. Loop through all AuthenticationProvider
    b. Call AuthenticationProvider.supports(Class> authenticationClass) if true, call AuthenticationProvider.authenticate(Authentication) forwards result to ProviderManager. If AuthenticationProvider is a DaoAuthenticationProvider, it calls UserDetailsService to lookup for user
33
Q

Where is Authentication stored?

A

SecurityContextHolder

34
Q

How to authenticate with the basic authentication mechanism?

A

Calculate token = base64 value of username:password
Put in the header:
authentication: Basic $token

35
Q

Implementations of AuthenticationProvider

A
  1. DaoAuthenticationProvider
  2. LdapAuthenticationProvider
  3. OpenIDAuthenticationProvider
  4. RememberMeAuthenticationProvider
36
Q

Implementations of UserDetailsService

A

InMemoryUserDetailsManager
JdbcUserDetailsManager
LdapUserDetailsManager

37
Q

How to configure user and role using InMemoryUserDetailsManager?

A
  1. Override WebSecurityConfigurerAdapter.configure(AuthenticationManagerBuilder auth)
  2. Configure:
    auth.inMemoryAuthentication()
    .withUser(username).password(passwordEncoder.encode(pw)).roles(roleName)
    // .and().with… next user
38
Q

How to configure JdbcUserDetailsManager?

A
  1. Override WebSecurityConfigurerAdapter.configure(AuthenticationManagerBuilder auth)
  2. Configure
    auth. jdbcAuthentication().dataSource(ds)
39
Q

How to configure custom UserDetailsService?

A

Just implement UserDetailsService interface and mark it with @Service. DaoAuthenticationProvider will find and use it

40
Q

How to add a custom AuthenticationProvider?

A
  1. Override WebSecurityConfigurerAdapter.configure(AuthenticationManagerBuilder auth) and annotate with @Configuration
  2. Add
    auth. authenticationProvider(customAuthenticationProvider)
41
Q

What is password encoded format?

A

{encoderId}encodedPassword
example:
{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG

42
Q

What is the default password encoder?

A

BcryptPasswordEncoder

43
Q

How to encode a password?

A

PasswordEncoderFactories.createDelegatingPasswordEncoder().encode(password);

44
Q

What class manages all password encoders?

A

DelegatingPasswordEncoder

45
Q

Does Spring provide a default login page?

A

yes

46
Q

How to enable basic authentication?

A
  1. Override WebSecurityConfigurerAdapter.configure(HttpSecurity)
  2. Configure
    http.authorizeRequests()

    .and()
    .httpBasic();
47
Q

Which layer is recommended for method security?

A

service layer beans

48
Q

What exception will be thrown if method access is not allowed?

A

AccessDeniedException

49
Q

How to enable method security JSR-250?

A

@EnableGlobalMethodSecurity(jsr250Enabled=true)

50
Q

How to set role-required for a method using method security JSR-250?

A

@RoleAllowed(“ROLE_ADMIN”)

public void method() {}

51
Q

How to set role-required “ADMIN” for a method using method security JSR-250?

A

Must use full-name ROLE_ADMIN instead of ADMIN
@RoleAllowed(“ROLE_ADMIN”)
public void method() {}

52
Q

How to enable method security?

A

@EnableGlobalMethodSecurity(prePostEnabled=true)

53
Q

How to check role and argument with method security?

A

@PreAuthorize(“hasRole(‘ADMIN’) && #order.id == 1”)

public Item findItem(Order order) {}

54
Q

How to check role and return value with method security?

A

@PostAuthorize(“hasRole(‘ADMIN’) && returnObject.id == 1”)

public Item findItem(Order order) {}

55
Q

How to enable @Secured?

A

@Configuration

@EnableGlobalMethodSecurity(securedEnabled = true)

56
Q

What can we do with @Secured?

A
Check role only e.g.
@Secured({"ROLE_A", "ROLE_B"})
void method()
57
Q

How to test the controller with spring security?

A
  1. Add @WebMvcTest(Controller.class) to test class
    a. Override config if needed: @ContextConfiguration(classes={Config1.class, Config2.class})
  2. Mock role
    @Test @WithMockUser(roles={“ADMIN”})
    void testClass() {}
  3. Using mockMvc.perform to test
58
Q

In the integration test, how to perform a test with username and password?

A
  1. Add @SpringBootTest(webEnvironment=RANDOM_PORT)

2. Using TestRestTemplate.withBasicAuth(username, password)

59
Q

By default, what is the first filter in the spring filter chain?

A

springSecurityFilterChain

Note: with postfix Chain

60
Q

What does springSecurityFilterChain do through Spring-managed filters?

A
  1. Drive authentication
  2. Enforce authorization
  3. Manage logout
  4. Maintain SecurityContext in HttpSession
  5. and more
61
Q

What is the relationship between ExceptionTranslationFilter and FilterSecurityInterceptor?

A
  1. ExceptionTranslationFilter does nothing on request
  2. FilterSecurityInteceptor does the hard work of performing the security check, but only raises an exception if the request is rejected
  3. ExceptionTranslationFilter handles exception if exists and responds to the client.
62
Q

How to replace an existing filter?

A
  1. Must extend the filter being replaced e.g.
    class Custom extends UsernamePasswordAuthenticationFilter {}
  2. Create bean @Bean Filter loginFilter() {}
  3. Override WebSecurityConfigurerAdapter.configure(HttpSecurity)
  4. http.addFilter(loginFilter());
    Note: the order will be taken care by Spring
63
Q

How to add a custom filter?

A
  1. class Custom implements Filter {}
  2. Create bean for the filter
  3. Override WebSecurityConfigurerAdapter.configure(HttpSecurity)
  4. http.addFilterAfter(custom, UsernamePasswordAuthenticationFilter.class)
64
Q

@EnableGlobalMethodSecurity is annotation used in Spring Security to secure which layer?

A

Service layer

65
Q

In Spring Security, what is the name of the class holding the information regarding high-level user permissions?

A

Represents an authority granted to an Authentication object.

A GrantedAuthority must either represent itself as a String or be specifically supported by an AccessDecisionManager.

66
Q

In Spring Security, what is the name of the Servlet Filter intercepting all the requests sent to an application?

A

DelegatingFilterProxy

67
Q

In sprint security, how to filter data return by a function?

A

Using @PostFilter: data returned by a method can be filtered by a security restriction
There is also a @PreFilter but it is less commonly used.

68
Q

What do SpEL expressions starting with @ reference?

A

Spring bean

69
Q

Annotation equivalent to @RoleAllowed

A

@Secured