无法在 Postman 上获取身份验证令牌

时间:2021-03-20 06:30:59

标签: spring spring-boot spring-security jwt

我正在尝试使用 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类代码
JwtUtil.java

邮递员请求

{
    "username": "foo",
    "password": "foo"
}       
    

邮递员回复

{
    "timestamp": "2021-03-20T05:21:01.251+00:00",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/token"
}      
   

我哪里错了?有人可以帮我吗?

1 个答案:

答案 0 :(得分:2)

您必须将 @RestController 添加到您的 JwtController 类中以使其可用:)