Skip to content

Tag 24: Spring Security

Lukas edited this page Apr 12, 2023 · 3 revisions

Spring Security

Spring Security Cookies

Principal Framework

  • Identität des Benutzers
public String getMe(Principal principal) {  
if (principal == null) {  
	return "No one logged in";  
}  
	return principal.getName();  
}

1. Möglichkeit (funktioniert nur im Controller)

public String getMe() {  
return SecurityContextHolder.getContext().getAuthentication().getName();  
}

2. Methode (funktioniert überall)

Authrization Type

Authorization Type "Basic Auth" auswählen, um Zugangsdaten einzugeben

Base64

Unter Headers > Authorization wird Base64-Code generiert (kann mit bestimmten Webseiten decoded werden)

JSESSIONID

Erstellter Cookie kann bei Browser über Netzwerkanalyse angezeigt werden

CSRF-Token

  • steht für Cross-Site Request Forgery
  • Token dient zum Schutz vor Angriffen
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
      CsrfTokenRequestAttributeHandler requestHandler = new CsrfTokenRequestAttributeHandler();
      requestHandler.setCsrfRequestAttributeName(null);

      return http
              .csrf(csrf -> csrf
                      .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                      .csrfTokenRequestHandler(requestHandler))
              .httpBasic()
              .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase()))
              .and()
              .authorizeHttpRequests()
              .requestMatchers("/api/users/**").permitAll()
              .requestMatchers("/api/**").authenticated()
              .anyRequest().permitAll()
              .and()
              .formLogin()
              .and().build();
  }

Code um CSRF-Token zu generieren

XSRF-TOKEN

Wird bei Postman bei GET-Anfrage bei Cookies angezeigt

XSRF-Token-Header

Unter Header Token mit dem Key "X-XSRF-TOKEN" eintragen

Logout-Funktion

.and()
.logout()

Clone this wiki locally