【发布时间】:2019-01-11 15:40:08
【问题描述】:
我一直在关注this 教程以在 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")
}
}
感谢任何帮助。
【问题讨论】:
-
你叫什么网址?
-
对于我调用的任何 URL,都没有任何反应。我有一个 url “/request”,如果没有令牌和注册,则不应访问。但是请求只是返回值而不检查任何标题 auth
-
所以您遇到了与链接问题相同的问题。你看我的回答了吗?
-
是的,它并没有真正帮助我解决
标签: java spring spring-mvc spring-security jwt