-
Notifications
You must be signed in to change notification settings - Fork 2
Tag 24: Spring Security
Lukas edited this page Apr 12, 2023
·
3 revisions
- 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)
Authorization Type "Basic Auth" auswählen, um Zugangsdaten einzugeben
Unter Headers > Authorization wird Base64-Code generiert (kann mit bestimmten Webseiten decoded werden)
Erstellter Cookie kann bei Browser über Netzwerkanalyse angezeigt werden
- 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
Wird bei Postman bei GET-Anfrage bei Cookies angezeigt
Unter Header Token mit dem Key "X-XSRF-TOKEN" eintragen
.logout()
.logout() ersetzt formLogin()