【发布时间】:2021-06-17 11:51:10
【问题描述】:
我正在尝试使用 JWT 方法学习 Spring 安全性。这样做时程序中没有错误,但我没有在我的 Postman 客户端上获得令牌。
这是我的代码:
(这里我不处理任何数据库,所以创建了假用户名和密码)
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
if(userName.equals("foo"))
return new User("foo", "foo" , new ArrayList<>());
else
throw new UsernameNotFoundException("User Not Found");
}
}
(控制器代码)
public class JwtController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private CustomUserDetailsService customUserDetailsService;
@Autowired
private JwtUtil jwtutil;
@RequestMapping(value = "/token" , method = RequestMethod.POST)
public ResponseEntity<?> generateToken(@RequestBody JwtRequest jwtRequest ) throws Exception
{
System.out.println(jwtRequest);
try
{
this.authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(jwtRequest.getUsername()
, jwtRequest.getPassword()));
}
catch(UsernameNotFoundException e)
{
e.printStackTrace();
throw new Exception("Bad Credentials");
}
UserDetails userDetails = this.customUserDetailsService.loadUserByUsername(jwtRequest.getUsername());
String token = this.jwtutil.generateToken(userDetails);
System.out.println("JWT Token "+ token);
// Now we want to send this token back to client
return ResponseEntity.ok(new JwtResponse(token));
}
}
(配置代码)
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Autowired
private CustomUserDetailsService customUserDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().cors().disable().authorizeRequests().antMatchers("/token")
.permitAll().anyRequest().authenticated()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception
{
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder()
{
return NoOpPasswordEncoder.getInstance();
}
}
(Jwt 请求和响应)
public class JwtRequest {
private String username;
private String password;
// getters and setters and constructors
}
public class JwtResponse {
String token;
// getters and setters and constructors
}
我从
JwtUtil.java复制的Jwtutil类代码
邮递员请求
{
"username": "foo",
"password": "foo"
}
邮递员回复
{
"timestamp": "2021-03-20T05:21:01.251+00:00",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/token"
}
我哪里错了?谁能帮帮我?
【问题讨论】:
标签: spring spring-boot spring-security jwt