Commit 1c9e894a by Patryk Czarnik

SecurityConfig - reguły dostępu

parent 672abdea
......@@ -28,10 +28,6 @@ public class RunXSLT implements Provider<Source> {
ServletContext servletContext = (ServletContext) wsContext.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
StreamSource xslt = new StreamSource(servletContext.getResourceAsStream("kalkulator.xsl"));
// inne opcje, bez korzystania z WebServiceContext i ServletContext:
// StreamSource xslt = new StreamSource("C:/katalog/aplikacja/kalkulator.xsl");
// StreamSource xslt = new StreamSource("http://localhost:8080/PC10-Provider-1.0/kalkulator.xsl");
TransformerFactory tf = TransformerFactory.newInstance();
Transformer tr = tf.newTransformer(xslt);
DOMResult result = new DOMResult();
......
package sklep.controller;
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";
}
}
package sklep.security;
import jakarta.servlet.DispatcherType;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
......@@ -7,17 +9,42 @@ 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.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
import org.springframework.security.web.SecurityFilterChain;
// https://docs.spring.io/spring-security/reference/servlet/getting-started.html
// W tej wersji różnym rolom dajemy różne poziomy dostępu.
// (inaczej mówiąc: dla róznych adresów mamy różne wymagania)
// To pomogło mi napisać poprawną konfigurację w "nowym stylu":
// https://docs.spring.io/spring-security/reference/servlet/authorization/authorize-http-requests.html
// Kluczowe było dodanie linii z DispatcherType.FORWARD → bez tego Spring wymagał autentykacji na etapie przechodzenia do szablonu jsp (FORWARD) lub wyświetlenia błędu
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain configHttpSecurity(HttpSecurity httpSecurity, HandlerMappingIntrospector hmi) throws Exception {
MvcRequestMatcher.Builder mvc = new MvcRequestMatcher.Builder(hmi);
httpSecurity
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated())
.authorizeHttpRequests(authz -> authz
// zezwalamy na działanie przekierowań wewnętrznych (szablony) i błędów
.dispatcherTypeMatchers(DispatcherType.FORWARD, DispatcherType.ERROR).permitAll()
.requestMatchers(mvc.pattern("/")).permitAll()
.requestMatchers(mvc.pattern("/whoami")).permitAll()
.requestMatchers(mvc.pattern("/*.css")).permitAll()
.requestMatchers(mvc.pattern("/hello"), mvc.pattern("/czas")).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/**")).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("/rest/**")).permitAll()
.anyRequest().denyAll() // dobra praktyka - odrzucanie pozostałych zapytań; Spring domyślnie wymagałby "authenticated"
)
.formLogin(Customizer.withDefaults())
// .httpBasic(Customizer.withDefaults())
.csrf(config -> config.disable())
......
<%@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