带有RESTAPI令牌的Spring Boot基本身份验证

时间:2019-04-02 13:00:53

标签: spring spring-boot authentication access-token

我需要使用SpringBoot应用程序提供用户登录名。

用户登录请求将是Rest请求,其有效载荷包括“用户名”和“密码”。

我需要第一次从DB验证那些凭据,并生成一个在特定时间有效的令牌。 登录后,所有后续请求都将具有该令牌,并且每次都会对该令牌进行验证。

我已经完成了令牌验证部分,但是对于第一次登录我真的很困惑,我不知道该怎么做。

即使是在首次登录请求时,系统也将检查令牌认证,这显然会失败。

我希望系统在验证db的名称和密码后仅在第一次生成令牌。

这是我第一次使用Spring Boot Security实现用户登录,所以我对此一无所知。尽管我已经在网上进行了很多研究和阅读,但仍然无法弄清楚这部分。

  • 编辑:

以下是扩展WebSecurityConfigurerAdapter的安全配置类

        @Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {

     auth.userDetailsService(userDetailsService)
    .passwordEncoder(getPasswordEncoder());
}



@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable();
    http.authorizeRequests()
    .antMatchers("/","**/firstPage").authenticated()
            .anyRequest().permitAll()
            .and()
            .formLogin().loginPage("/login").
            permitAll()
            .and().logout().permitAll();
}

以下是登录后将被调用的请求。如何使用已生成的令牌对用户进行身份验证?令牌正在请求的标题中发送。

 @PostMapping(value = "/home")
public ResponseEntity<ConsolidateResponse> TestReques(@RequestBody TestParam testParam)
        throws Exception {

    //Some logic

   }

1 个答案:

答案 0 :(得分:0)

如果从spring安全配置类中禁用表单登录并公开一个剩余端点(/ auth),则可以处理登录并生成令牌。这里我使用jwt来生成令牌。

 @RequestMapping(value = "/auth", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest) throws AuthenticationException, IOException {
        // Perform the security
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                authenticationRequest.getUsername(), authenticationRequest.getPassword());

        final Authentication authentication = authManager.authenticate(token);
        if (!authentication.isAuthenticated()) {
            throw new BadCredentialsException("Unknown username or password");
        }

        // Reload password post-security so we can generate token
        final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
        final String jwtoken = jwtTokenUtil.generateToken(userDetails);
        return ResponseEntity.ok(responseBean);
    }

使用无状态身份验证时,我们可以将令牌参数显式传递给控制器​​并进行验证。如果启用了基于会话的身份验证,我们还可以使用@AuthenticationPrincipal来检索当前登录的用户。

//Stateless authentication
@PostMapping(value = "/home")
public ResponseEntity<ConsolidateResponse> test(@RequestBody TestParam testParam,String token)
        throws Exception {


    Boolean isValidToken = jwtTokenUtil.validateToken(token);
    if(isValidToken) {
     //Some logic 
    }else {
     //invalid request
    }
}





@PostMapping(value = "/home")
    public ResponseEntity<ConsolidateResponse> test(@RequestBody TestBean requestToken,
            @AuthenticationPrincipal User contextPrincipal, HttpServletRequest req) {

        Optional.ofNullable(contextPrincipal).orElseThrow(InvalidUserSession::new);


        //some logic
    }