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

xtfmy6hx  于 2021-07-16  发布在  Java
关注(0)|答案(1)|浏览(529)

我正在尝试使用jwt方法学习Spring Security 。当这样做时,程序中没有错误,但我没有在我的 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文件
Postman 请求

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

Postman 回复

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

我错在哪里?有人能帮我吗?

vfwfrxfs

vfwfrxfs1#

必须将@restcontroller添加到jwtcontroller类以使其可用:)

相关问题