在Spring中获取当前HTTP基本认证用户

时间:2018-02-22 13:24:57

标签: spring spring-boot spring-security

我正在使用Http Basic Auth作为REST API,其中用户名和密码在标题中发送。这是相关的配置

@Configuration
 @EnableWebSecurity
 public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserService userService;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
  auth.userDetailsService(userService);
}


 @Override
protected void configure(HttpSecurity http) throws Exception {
    http.sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    http
            .antMatcher("/api/**")
            .authorizeRequests()
            .antMatchers("/api/**").authenticated()
            .and()
            .httpBasic();
}

控制器方法

  @RestController
  public class ScheduleController {
@Autowired
ScheduleService scheduleService;

   @RequestMapping(value ="api/schedule/{scheduleId}",method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<Schedule> getOneSchedule(@PathVariable Long scheduleId) {
    //  Get the product given by Id
    Schedule schedule = scheduleService.findOne(scheduleId);
    if(schedule == null) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
    }
    return ResponseEntity.status(HttpStatus.OK).body(schedule);
    }
    }

是否有可能进入&#34; getOneSchedule&#34;获取用户名/密码的User对象的方法?

1 个答案:

答案 0 :(得分:0)

是,

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

并获取用户名,例如只使用authentication.getName()