[英]Spring Filters not being called
我一直在遵循本教程來在Spring中進行JWT身份驗證,但是由於某些原因,這些過濾器對我不起作用。 我已經從Github下載了該教程項目,並且可以正常工作,但是我的卻沒有,我也不知道為什么...
我將在下面發布一些代碼(不要介意Kotlin + Java的混合,我試圖在Java中實現安全性配置,可能是個問題)
Initializer.kt
class Initializer : WebApplicationInitializer {
@Throws(ServletException::class)
override fun onStartup(container: ServletContext) {
val context = AnnotationConfigWebApplicationContext()
context.scan("com.newyorkcrew.server.config")
context.scan("com.newyorkcrew.server.domain")
val dispatcher = container.addServlet("dispatcher", DispatcherServlet(context))
dispatcher.setLoadOnStartup(1)
dispatcher.addMapping("/api/*")
}
}
WebConfig.kt
@Bean
fun propertySourcesPlaceholderConfigurer(): PropertySourcesPlaceholderConfigurer {
return PropertySourcesPlaceholderConfigurer()
}
@Configuration
@Import(JPAConfig::class)
@EnableWebMvc
@ComponentScan("com.newyorkcrew.server")
@PropertySources(PropertySource(value = ["classpath:local/db.properties", "classpath:local/security.properties"]))
open class WebConfig {
@Bean
open fun corsConfigurer(): WebMvcConfigurer {
return object : WebMvcConfigurer {
override fun addCorsMappings(registry: CorsRegistry?) {
registry!!.addMapping("/**")
.allowedOrigins("http://localhost:4200", "http://localhost:8080", "http://localhost:8081")
.allowedMethods("GET", "PUT", "POST", "DELETE")
}
}
}
}
WebSecurity.java
@Configuration
@EnableWebSecurity
@ComponentScan("com.newyorkcrew.server.config")
public class WebSecurity extends WebSecurityConfigurerAdapter {
public static String SECRET;
@Value("{security.secret}")
private void setSECRET(String value) {
SECRET = value;
}
@Value("{security.expiration}")
public static long EXPIRATION_TIME;
@Value("{security.header}")
public static String HEADER;
@Value("{security.prefix}")
public static String PREFIX;
public static String SIGN_UP_URL;
@Value("${security.signupurl}")
private void setSignUpUrl(String value) {
SIGN_UP_URL = value;
}
@Autowired
private UserDetailsService userDetailsService;
public WebSecurity(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().authorizeRequests()
.antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
.anyRequest().authenticated()
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()));
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
我還實現了UserDetailService,JWTAuthenticationFilter和JWTAuthorizationFilter,但是只要它們沒有被擊中,我認為它們並不是很重要。
我已經使用配置了一段時間,並且它們可以正常工作,但是在添加SecurityConfig時,它已經初始化,但是由於某些原因,過濾器不起作用。
如果需要更多代碼,我將發布。
編輯:根據要求,實現JWTAuthenticationFilter。
open class JWTAuthenticationFilter(private val authManager: AuthenticationManager) : UsernamePasswordAuthenticationFilter() {
override fun attemptAuthentication(request: HttpServletRequest?, response: HttpServletResponse?): Authentication {
try {
// Build the user DTO from the request
val userDTO = Gson().fromJson(convertInputStreamToString(request?.inputStream), UserDTO::class.java)
// Build the user from the DTO
val user = UserConverter().convertDtoToModel(userDTO)
// Try to authenticate
return authManager.authenticate(UsernamePasswordAuthenticationToken(user.email, user.password, ArrayList()))
} catch (e: Exception) {
throw RuntimeException(e)
}
}
override fun successfulAuthentication(request: HttpServletRequest?, response: HttpServletResponse?,
chain: FilterChain?, authResult: Authentication?) {
val token = Jwts.builder()
.setSubject(authResult?.principal.toString())
.setExpiration(Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET.toByteArray())
.compact()
response?.addHeader(HEADER, "$PREFIX $token")
}
}
任何幫助表示贊賞。
對我有用的解決方案是放棄Kotlin。 使用相同的配置啟動了一個新的Spring項目,該項目很簡單。 我很想在Kt進行這個項目時感到非常難過,但也許我做錯了什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.