Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
J
javab_20230928
Overview
Overview
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Patryk Czarnik
javab_20230928
Commits
08eceeb5
Commit
08eceeb5
authored
Nov 07, 2023
by
Patryk Czarnik
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Próba dopisania reguł autoryzacji - na razie nie działa
parent
750bd50d
Hide whitespace changes
Inline
Side-by-side
Showing
4 changed files
with
199 additions
and
3 deletions
+199
-3
SecurityConfig.java
...epSpring/src/main/java/sklep/security/SecurityConfig.java
+27
-3
dziwny_config.txt
...klepSpring/src/main/java/sklep/security/dziwny_config.txt
+78
-0
nowy_config_inmemory.txt
...ing/src/main/java/sklep/security/nowy_config_inmemory.txt
+33
-0
stary_config.txt
...SklepSpring/src/main/java/sklep/security/stary_config.txt
+61
-0
No files found.
PC30-SklepSpring/src/main/java/sklep/security/SecurityConfig.java
View file @
08eceeb5
...
@@ -4,21 +4,46 @@ import org.springframework.context.annotation.Bean;
...
@@ -4,21 +4,46 @@ import org.springframework.context.annotation.Bean;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.security.config.Customizer
;
import
org.springframework.security.config.Customizer
;
import
org.springframework.security.config.annotation.web.builders.HttpSecurity
;
import
org.springframework.security.config.annotation.web.builders.HttpSecurity
;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
;
import
org.springframework.security.core.userdetails.User
;
import
org.springframework.security.core.userdetails.User
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
org.springframework.security.provisioning.InMemoryUserDetailsManager
;
import
org.springframework.security.provisioning.InMemoryUserDetailsManager
;
import
org.springframework.security.web.SecurityFilterChain
;
import
org.springframework.security.web.SecurityFilterChain
;
import
jakarta.servlet.DispatcherType
;
// https://docs.spring.io/spring-security/reference/servlet/getting-started.html
// 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
@Configuration
@EnableWebSecurity
public
class
SecurityConfig
{
public
class
SecurityConfig
{
@Bean
@Bean
SecurityFilterChain
configHttpSecurity
(
HttpSecurity
httpSecurity
)
throws
Exception
{
SecurityFilterChain
configHttpSecurity
(
HttpSecurity
httpSecurity
)
throws
Exception
{
httpSecurity
httpSecurity
.
authorizeHttpRequests
(
authz
->
authz
.
anyRequest
().
authenticated
())
.
authorizeHttpRequests
(
authz
->
authz
.
formLogin
(
Customizer
.
withDefaults
())
.
anyRequest
().
authenticated
()
// zezwalamy na działanie przekierowań wewnętrznych (szablony) i błędów
// .dispatcherTypeMatchers(DispatcherType.FORWARD, DispatcherType.ERROR).permitAll()
// .requestMatchers("/", "/whoami", "/*.css").permitAll()
// .requestMatchers("/hello", "/time").permitAll()
// .requestMatchers("/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("/products/new", "/products/*/edit").hasAuthority("ROLE_manager")
// .requestMatchers("/products/**").permitAll() // kolejność reguł ma znaczenie
// .requestMatchers("/customers/new", "/customers/*/edit").hasRole("manager") // skrót na hasAuthority("ROLE_...")
// .requestMatchers("/customers/**").authenticated()
// .anyRequest().denyAll() // dobra praktyka - odrzucanie pozostałych zapytań; Spring domyślnie wymagałby "authenticated"
)
.
formLogin
(
Customizer
.
withDefaults
())
// albo .httpBasic(Customizer.withDefaults())
// .csrf(authz -> authz.disable())
// .csrf(authz -> authz.disable())
;
;
...
@@ -36,5 +61,4 @@ public class SecurityConfig {
...
@@ -36,5 +61,4 @@ public class SecurityConfig {
return
new
InMemoryUserDetailsManager
(
users
);
return
new
InMemoryUserDetailsManager
(
users
);
}
}
}
}
PC30-SklepSpring/src/main/java/sklep/security/dziwny_config.txt
0 → 100644
View file @
08eceeb5
package sklep.security;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import jakarta.servlet.DispatcherType;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Autowired
// Spring wstrzyknie tu domyślne połączenie z bazą danych - to sonfigurowane w application.properties
private DataSource dataSource;
@Bean
SecurityFilterChain setHttpSecurity(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeHttpRequests((authz) -> authz
// zezwalamy na działanie przekierowań wewnętrznych (szablony) i błędów
.dispatcherTypeMatchers(DispatcherType.FORWARD, DispatcherType.ERROR).permitAll()
.requestMatchers("/", "/whoami", "/*.css").permitAll()
.requestMatchers("/hello", "/time").permitAll()
.requestMatchers("/alt?/**").authenticated() // zalogowany jako ktokolwiek
.requestMatchers("/products/new", "/products/*/edit").hasAuthority("ROLE_manager")
.requestMatchers("/products/**").permitAll() // kolejność reguł ma znaczenie
.requestMatchers("/customers/new", "/customers/*/edit").hasRole("manager") // skrót na hasAuthority("ROLE_...")
.requestMatchers("/customers/**").authenticated()
.anyRequest().denyAll() // dobra praktyka - odrzucanie pozostałych zapytań; Spring domyślnie wymagałby "authenticated"
)
.formLogin();
return httpSecurity.build();
}
@Bean
AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration, ApplicationContext applicationContext) throws Exception {
ObjectPostProcessor<Object> objectPostProcessor = new ObjectPostProcessor<Object>() {
public <O> O postProcess(O object) {
return object;
}
};
return authenticationConfiguration.authenticationManagerBuilder(objectPostProcessor, applicationContext)
.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery("SELECT username, password, enabled FROM spring_accounts WHERE username = ?")
.authoritiesByUsernameQuery("SELECT username, role FROM spring_account_roles WHERE username = ?")
.and()
.build();
}
// wersja "in memory":
// @Bean
// AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration, ApplicationContext applicationContext) throws Exception {
// ObjectPostProcessor<Object> objectPostProcessor = new ObjectPostProcessor<Object>() {
// public <O> O postProcess(O object) {
// return object;
// }
// };
//
// return authenticationConfiguration.authenticationManagerBuilder(objectPostProcessor, applicationContext)
// .inMemoryAuthentication()
// .withUser("ala").password("{noop}ala123").roles("manager", "worker").and()
// .withUser("ola").password("{noop}ola123").roles("worker").and()
// .and()
// .build();
// }
}
PC30-SklepSpring/src/main/java/sklep/security/nowy_config_inmemory.txt
0 → 100644
View file @
08eceeb5
package sklep.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
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;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain setHttpSecurity(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeHttpRequests((authz) -> authz
.anyRequest().authenticated()
)
.formLogin();
return httpSecurity.build();
}
@Bean
InMemoryUserDetailsManager userDetailsService() {
UserDetails[] users = {
User.withUsername("ala").password("{noop}ala123").roles("manager", "worker").build(),
User.withUsername("ola").password("{noop}ola123").roles("worker").build(),
};
return new InMemoryUserDetailsManager(users);
}
}
PC30-SklepSpring/src/main/java/sklep/security/stary_config.txt
0 → 100644
View file @
08eceeb5
package com.example.demo.security;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
/* Tak wyglądała konfiguracja bezpieczeństwa w aplikacji opartej o Spring Boot 2 / Spring Security 4 i 5
* (pod koniec funkcjonowania wersji 5 oznaczono klasę WebSecurityConfigurerAdapter jako @Deprecated).
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()
.antMatchers("/products/new", "/products/*/edit").hasAuthority("ROLE_manager") // tylko manager może edytować
.antMatchers("/customers/new", "/customers/*/edit").hasAuthority("ROLE_manager")
.antMatchers("/products/find").authenticated() // zalogowany jako ktokolwiek może wyszukiwać
.antMatchers("/", "/whoami", "/products/**", "/customers/**", "/*.css").permitAll() // dostęp dla wszystkich
.antMatchers("/products?", "/products?/**").permitAll() // inne wersje listy produktów
.antMatchers("/rest/**").permitAll()
// .antMatchers("/login").anonymous() // nie może być zalogowany! - ale to przestało działać...
.antMatchers("/login").permitAll()
.antMatchers("/logout").authenticated() // zalogowany jako ktokolwiek
.anyRequest().denyAll() // pozostałe adresy blokujemy
.and()
.formLogin()
.and()
.csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
auth.jdbcAuthentication()
.dataSource(dataSource)
.passwordEncoder(passwordEncoder)
.usersByUsernameQuery("SELECT username, password, enabled FROM spring_accounts WHERE username = ?")
.authoritiesByUsernameQuery("SELECT username, role FROM spring_account_roles WHERE username = ?");
// wersja inMemory:
// auth.inMemoryAuthentication()
// .withUser("ala").password("{noop}abc123").roles("manager", "sprzedawca")
// .and()
// .withUser("ola").password("{noop}abc123").roles("sprzedawca")
// .and()
// .withUser("ula").password("{noop}abc123").roles();
}
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment