.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login")
.usernameParameter("email")
.passwordParameter("password")
.defaultSuccessUrl("/dashboard")
.failureUrl("/login?logout")
.permitAll()при нажатии на вход всплывает окно и ссылка получается вида site.com/***?login
?login - это всего лишь request parameter @PreAuthorize("hasAuthority('ADMIN')") Пользователь должен быть админомfor (AdminProductions admrem : rmadm){
adminProductRepo.deleteById(admrem.getId());
adminProductRepo.save(admrem);
}adminProductRepo.save(admrem);deleteByAdminproductname()Adminproductnamespring.profiles.active=development@Configuration
@ConfigurationProperties(prefix = "application")
public class AppProperties {
@Getter
@Setter
private String baseUrl;
@Getter
@Setter
private String uploadPath;
}application.base_url=http://localhost:7777
application.upload_path=/home/admin/application.com/uploadsbase_url => baseUrl upload_path => uploadPath@EnableConfigurationProperties({
ApplicationProperties.class
})
public class MyApplication {
}@Controller
@RequiredArgsConstructor
public class MyController {
private final ApplicationProperties properties;
// ... тут методы контроллера
String uploadPath = properties.getUploadPath();
//...
}# File upload size
spring.servlet.multipart.max-file-size=20MB
spring.servlet.multipart.max-request-size=20MB
spring.servlet.multipart.file-size-threshold=2KB
# Uploads
spring.servlet.multipart.enabled=true
fl.upload_path=/home/phoenix/example.com/uploads <span th:text="${address.city != null} ? ${address.city} : 'No data!'">City</span>==, а если объект, то нужно использовать eq<span th:if="${address.city} == null">Non data</span>
<span th:unless="${address.city} != null" th:text="'Your city : ' + ${address.city}">Non data</span>?. между address & city<span th:text="'Your city : ' + ${address?.city}">Non data</span> @RequiredArgsConstructor
@ControllerAdvice
public class GlobalControllerAdvice {
private final UserServiceImpl userServiceImpl;
@ModelAttribute("currentUser")
public User getUserProfile(
@AuthenticationPrincipal UserDetails currentUser
) {
if (currentUser != null)
return (User) userServiceImpl.findUserByEmail(currentUser.getUsername());
return null;
}
}${currentUser} (текущий авторизованный пользователь)<div class="comments" th:each="comment : ${comments}">
<input th:if="${comment.author} eq ${currentUser}" type="button" value="Отредактировать комментарий"/>
</div>@GetMapping("/edit/{commentId}")
public String editComment(
@PathVariable("commentId") Long commentId,
@AuthenticationPrincipal UserDetails currentUser,
) {
User user = (User) userServiceImpl.findUserByEmail(currentUser.getUsername());
/*
Далее находим комментарий по его id. находим его автора и сравниваем с user.
*/
} public void setZones(List<Zone> zones) {
zones.forEach(zone -> zone.setDestination(this));
this.zones = zones;
}@Entity
public class Book {
@id
private Long bookId;
private String bookName;
}@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
Book findBookByBookName(String bookName);
// или можно вернуть Optional
Optional<Book> findBookByBookName(String bookName);
} @ResponseBody, либо создайте контроллер и добавьте аннотацию @RestController</body> добавьте js код для аякс.String или например, Map<String, String> с нужными данными.<div class="notify" style="display:none;"></div>show() (видимым).@keyframesSHIFT+Ctrl+A ->registry-> compiler.automake.allow.when.app.runningfile->settings->build,execution,deployment. Go to ->compiler->build project automatically.
accessDeniedHandler срабатывает только если я зологинился и пытаюсь зайти на существующую запрещенную страницу. Почему он не срабатывает если я разлогиненый и пытаюсь зайти на существующую запрещенную страницу и перекидывает на страницу логина?
permitAll(), проходя дальше по цепочке он натыкается на .anyRequest().authenticated() и отдает Access Denied Exception./error закомментирована. Возможно, что он пытается показать ошибку, но так как эта страница недоступна будучи неавторизованным, то сперва перекидывает на страницу авторизации...@Controller
public class HttpErrorController implements ErrorController {
private final MessageSource messageSource;
@Autowired
public HttpErrorController(MessageSource messageSource) {
this.messageSource = messageSource;
}
@RequestMapping("/error")
public String handleError(
Locale locale,
Model model,
HttpServletRequest request,
Exception ex
) {
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if (status != null) {
int statusCode = Integer.valueOf(status.toString());
Map<String, String> metaData = new HashMap<>();
// 403
if (statusCode == HttpStatus.FORBIDDEN.value()) {
//do somthing
}
// 404
else if (statusCode == HttpStatus.NOT_FOUND.value()) {
//do somthing
}
// 405
else if (statusCode == HttpStatus.NOT_FOUND.value()) {
//do somthing
}
// 500
else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
//do somthing
}
}
return "errors/httperrors";
}
@Override
public String getErrorPath() {
return "/error";
}
} /**
* Конфигурация для Spring Security
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig {
private static UserDetailsServiceImpl userDetailsService;
@Autowired
private UserDetailsServiceImpl userDetailsServiceImpl;
@PostConstruct
private void init() {
userDetailsService = this.userDetailsServiceImpl;
}
@Bean
public static PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authProvider() {
CustomAuthenticationProvider authProvider = new CustomAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
// Конфигурация для backend
@Configuration
@Order(1)
public static class BackendConfigurationAdapter extends WebSecurityConfigurerAdapter {
@Autowired
private CustomWebAuthenticationDetailsSource authenticationDetailsSource;
public BackendConfigurationAdapter() {
super();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/admin/**")
.antMatcher("/admin/**/**")
.authorizeRequests()
.anyRequest()
.hasAuthority("ADMIN_PRIVILEGE")
/*.hasAuthority("ADMIN")*/
.and()
.formLogin()
.authenticationDetailsSource(authenticationDetailsSource)
.loginPage("/admin/login")
.loginProcessingUrl("/admin/login")
.usernameParameter("email")
.passwordParameter("password")
.defaultSuccessUrl("/admin/dashboard")
.failureUrl("/admin/login?authError")
.permitAll()
.and()
.rememberMe()
.rememberMeParameter("remember-me")
.tokenValiditySeconds(86400)
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/admin/logout"))
.logoutSuccessUrl("/admin/login")
.deleteCookies("JSESSIONID")
.and()
.exceptionHandling()
.accessDeniedPage("/403")
.and()
.csrf()
.ignoringAntMatchers("/admin/**");
}
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers(
// статика backend
"/backend/css/**",
"/backend/js/**",
"/backend/fonts/**",
"/backend/images/**",
"/backend/init/**"
);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
}
// Конфигурация для frontend (Обычная авторизация и авторизация oauth2)
@Configuration
@Order(2)
public static class FrontendConfigurationAdapter extends WebSecurityConfigurerAdapter {
@Autowired
private CustomWebAuthenticationDetailsSource authenticationDetailsSource;
public FrontendConfigurationAdapter() {
super();
}
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().mvcMatchers("/robots.txt").permitAll()
.antMatchers(
"/", "/auth", "/signup", "/restore", "/activation/**",
"/admin/login", "/admin_restore",
"/attachments/get/**",
"/sendMessage",
"/error",
"/page/**",
"/categories", "/categories/**",
"/terms/**", "/posts", "/posts/**"
).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.authenticationDetailsSource(authenticationDetailsSource)
.loginPage("/auth")
.loginProcessingUrl("/auth")
.usernameParameter("email")
.passwordParameter("password")
.defaultSuccessUrl("/")
.failureUrl("/auth?authError")
.permitAll()
.and()
.rememberMe()
.rememberMeParameter("remember-me")
.tokenValiditySeconds(86400)
.and()
.oauth2Login().defaultSuccessUrl("/")
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/")
.deleteCookies("JSESSIONID")
.and()
.exceptionHandling()
.accessDeniedPage("/403")
.and()
.csrf()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
.and()
.headers().frameOptions().sameOrigin();
}
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers(
"/frontend/css/**",
"/frontend/js/**",
"/frontend/fonts/**",
"/frontend/images/**",
"/frontend/lib/**",
"/frontend/vendor/**"
);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
}
}@Component
public class InitData implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
if (userServiceImpl.usersCount() == 0)
initUsers();
}
private void initUsers() {
// создаем пользователей
}
} href="/contact" , то при наличии context может не работать. И соответственно, например, через thymeleaf надо добавлять как th:href="@{/contact}"Reason: Failed to determine a suitable driver class
@Controller
public class HttpErrorController implements ErrorController {
private final MessageSource messageSource;
@Autowired
public HttpErrorController(MessageSource messageSource) {
this.messageSource = messageSource;
}
@RequestMapping("/error")
public String handleError(
Locale locale,
Model model,
HttpServletRequest request,
Exception ex
) {
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if (status != null) {
int statusCode = Integer.valueOf(status.toString());
Map<String, String> metaData = new HashMap<>();
// 403
if (statusCode == HttpStatus.FORBIDDEN.value()) {
// do somthing
}
// 404
else if (statusCode == HttpStatus.NOT_FOUND.value()) {
// do somthing
}
// 405
else if (statusCode == HttpStatus.NOT_FOUND.value()) {
// do somthing
}
// 500
else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
// do somthing
}
}
return "templates/errors/httperrors";
}
@Override
public String getErrorPath() {
return "/error";
}
}# Disable Whitelabel Error Page
server.error.whitelabel.enabled=false