Commit 1f17b06c by Patryk Czarnik

WhoAmI

parent b64f2ea9
......@@ -2,6 +2,7 @@ package sklep.controller;
import java.time.LocalDateTime;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
......@@ -25,4 +26,13 @@ public class RootController {
model.addAttribute("dt", LocalDateTime.now());
return "wyswietl_czas";
}
@GetMapping("/whoami")
public String whoAmI(Authentication authentication, Model model) {
if(authentication != null && authentication.isAuthenticated()) {
model.addAttribute("userName", authentication.getName());
model.addAttribute("authorities", authentication.getAuthorities());
}
return "whoami";
}
}
......@@ -2,23 +2,58 @@ package sklep.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
import jakarta.servlet.DispatcherType;
@Configuration
public class SecurityConfig {
// W tej wersji dla każdego zapytanie będziemy wymagać uwierzytelnienia
// (czyli użytkownik musi się zalogować)
// W tej wersji zapisujemy reguły dostępu ("autoryzacji").
// Określamy też, że do uwierzytelnienia służyć będzie formularz generowany automatycznie przez Springa.
@Bean
SecurityFilterChain configureHttpSecurity(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeHttpRequests(authz -> authz.anyRequest().authenticated())
.formLogin(Customizer.withDefaults())
.csrf(csrf -> csrf.disable());
SecurityFilterChain configHttpSecurity(HttpSecurity httpSecurity, HandlerMappingIntrospector hmi) throws Exception {
MvcRequestMatcher.Builder mvc = new MvcRequestMatcher.Builder(hmi);
httpSecurity
.authorizeHttpRequests(authz -> authz
// zezwalamy na działanie przekierowań wewnętrznych (szablony) i błędów
.dispatcherTypeMatchers(DispatcherType.FORWARD, DispatcherType.ERROR).permitAll()
.requestMatchers("/", "/hello", "/czas", "/skrypt").permitAll()
.requestMatchers(mvc.pattern("/whoami")).permitAll()
.requestMatchers("/*.css", "/*.js").permitAll()
.requestMatchers(mvc.pattern("/alt?/**")).authenticated() // zalogowany jako ktokolwiek
// kolejność reguł ma znaczenie - pierwsza reguła, do której pasuje zapytanie, jest decydująca
// np. /products/new wymaga uprawnień managera, chociaż to zapytanie pasowałoby te z do /products/**
.requestMatchers(mvc.pattern("/products/new"), mvc.pattern("/products/*/edit")).hasAuthority("ROLE_manager")
.requestMatchers(mvc.pattern("/products/szukaj")).authenticated()
.requestMatchers(mvc.pattern("/products/**")).permitAll() // pozostałe zapytanie w obrębie products - dopuszczamy wszystkich; kolejność reguł ma znaczenie
.requestMatchers(mvc.pattern("/customers/new"), mvc.pattern("/customers/*/edit")).hasRole("manager") // skrót na hasAuthority("ROLE_...")
.requestMatchers(mvc.pattern("/customers/**")).authenticated()
.requestMatchers(mvc.pattern(HttpMethod.GET, "/rest/**")).permitAll()
.requestMatchers(mvc.pattern(HttpMethod.POST, "/rest/**")).hasRole("manager")
.requestMatchers(mvc.pattern(HttpMethod.PUT, "/rest/**")).hasRole("manager")
.requestMatchers(mvc.pattern(HttpMethod.DELETE, "/rest/**")).hasRole("manager")
.anyRequest().denyAll() // dobra praktyka - odrzucanie pozostałych zapytań; Spring domyślnie wymagałby "authenticated"
)
.formLogin(Customizer.withDefaults())
// .formLogin(config -> config
// .loginPage("/moja_strona_logowania")
// .usernameParameter("nazwa_uzytkownika")
// .passwordParameter("haslo")
// .failureForwardUrl("/porazka-logowania")
// )
// Dla zapytań restowych większy sens ma takie ustawienie:
// .httpBasic(Customizer.withDefaults())
// .csrf(config -> config.disable())
.csrf(config -> config.ignoringRequestMatchers("/rest/**"))
.cors(config -> config.disable());
return httpSecurity.build();
}
......
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="jakarta.tags.core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<c:choose>
<c:when test="${not empty userName}">
<p>Jesteś zalogowany jako <strong>${userName}</strong>.</p>
<p>Twoje uprawnienia (<i>authorities</i>):</p>
<ul>
<c:forEach var="auth" items="${authorities}">
<li>${auth}</li>
</c:forEach>
</ul>
</c:when>
<c:otherwise>
<p>Nie jesteś zalogowany.</p>
</c:otherwise>
</c:choose>
<div><a href="/">Powrót do spisu treści</a></div>
<div><a href="/logout">Wyloguj się</a></div>
</body>
</html>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment