英文:
Generating JWT token with JwtUtil class in Spring Boot resulting in NullPointerException
问题
尝试为特定端点实现基于JWT的身份验证,但无法导入许多包,如在安全配置中,无法将我的类扩展为extends WebSecurityConfigurerAdapter
,该类提供了许多内置函数,用于此的JWT依赖项是:
io.jsonwebtoken
jjwt
0.11.0
@Configuration
@EnableWebSecurity()
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {
请注意,我只提供代码部分的翻译。
英文:
trying to implement a jwt based authentication for specific end points , but not able to import many of the packages , like in security config , cant able to extend my class with extends WebSecurityConfigurerAdapter , which gives many of the built in functions , jwt dependency used for this is :
io.jsonwebtoken
jjwt
0.11.0
@Configuration
@EnableWebSecurity()
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {
答案1
得分: 0
在类中:public class MySecurityConfig extends WebSecurityConfigurerAdapter
WebSecurityConfigurerAdapter 已被弃用,您可以创建这样的类:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
SecurityFilterChain filterChain(HttpSecurity http)throws Exception{
http.authorizeHttpRequests(authz -> authz
.requestMatchers(HttpMethod.GET,"/testAPI").permitAll()
.requestMatchers("").permitAll()
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
UserDetailsService userDetailsService() {
InMemoryUserDetailsManager userDetailsService = new InMemoryUserDetailsManager();
UserDetails userDetails = User
.withUsername("vinod")
.password(bCryptPasswordEncoder().encode("singh"))
.authorities("read").build();
userDetailsService.createUser(userDetails);
return userDetailsService;
}
}
英文:
in class: public class MySecurityConfig extends WebSecurityConfigurerAdapter
the WebSecurityConfigurerAdapter is deprecated, instead you can create class like this:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
SecurityFilterChain filterChain(HttpSecurity http)throws Exception{
http.authorizeHttpRequests(authz -> authz
.requestMatchers(HttpMethod.GET,"/testAPI").permitAll()
.requestMatchers("").permitAll()
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
UserDetailsService userDetailsService() {
InMemoryUserDetailsManager userDetailsService = new
InMemoryUserDetailsManager();
UserDetails userDetails = User
.withUsername("vinod")
.password(bCryptPasswordEncoder().encode("singh"))
.authorities("read").build();
userDetailsService.createUser(userDetails);
return userDetailsService;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论