Код: Выделить всё
package com.keyoflife.keyoflife.config;
import com.keyoflife.keyoflife.services.UserDetailsLoader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Arrays;
@Configuration
@EnableWebSecurity
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SecurityConfiguration {
private final UserDetailsLoader usersLoader;
private final JwtFilter jwtFilter;
public SecurityConfiguration(UserDetailsLoader usersLoader, JwtFilter jwtFilter) {
this.usersLoader = usersLoader;
this.jwtFilter = jwtFilter;
}
@Bean
public PasswordEncoder passwordEncoder() {
//TODO: remove this
//get the hashed version of 'asdfasdf' to save in db
//System.out.println(new BCryptPasswordEncoder().encode("asdfasdf"));
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http, PasswordEncoder passwordEncoder)
throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.userDetailsService(usersLoader).passwordEncoder(passwordEncoder);
return authenticationManagerBuilder.build();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable)
.cors(Customizer.withDefaults())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/user-dash").authenticated()
.requestMatchers(HttpMethod.OPTIONS,"/api/auth/**", "/login", "/").permitAll()
)
.sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.httpBasic(Customizer.withDefaults())
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.formLogin((login) -> login
.loginPage("/login")
.failureUrl("/login")
.defaultSuccessUrl("/user-dash"))
/* Logout configuration */
.logout((logout) -> logout
.logoutSuccessUrl("/"))
.build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrigin("http://127.0.0.1:8080");
configuration.setAllowedMethods(Arrays.asList("GET", "POST"));
configuration.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization"));
configuration.setAllowCredentials(true); // for cookies. bc everyone likes cookies
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
Код: Выделить всё
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
// Get authorization header and validate
final String header = request.getHeader("Authorization");
System.out.println(header);
//ensure header has text and starts with "Bearer "
if (!StringUtils.hasText(header) || (StringUtils.hasText(header) && !header.startsWith("Bearer "))) {
chain.doFilter(request, response); //Access Denied Exception thrown here because header is null
return;
}
//rest of method below
}
Код: Выделить всё
{
"username":"testUser",
"password": "asdfasdf"
}
Подробнее здесь: https://stackoverflow.com/questions/780 ... rning-null