-1

I am using Http Basic Auth for a REST API where the username and password is sent in the header.This is the relevant config

@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();
}

A controller method

  @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);
    }
    }

Is it possible to inside the "getOneSchedule" method to obtain the User object for the username/password provided?

Daniel Haughton
  • 1,085
  • 5
  • 20
  • 45

1 Answers1

0

Yes,

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

and to fetch the username, for example just use authentication.getName()

Leonardo Beal
  • 724
  • 11
  • 24