我無法從控制器中的發布請求方法中獲取身份驗證用戶。我嘗試使用@AuthficationPrincipal UserDetails、Principal 和 SecurityContextHolder,但他回傳 null。需要我將影像上傳到資料庫。請幫我解決這個問題。(.csrf 已禁用)
控制器:
@Controller
@RequestMapping("/images")
public class ImageController {
private final ImageService imageService;
private final UserService userService;
@Autowired
public ImageController(ImageService imageService,
UserService userService) {
this.imageService = imageService;
this.userService = userService;
}
@PostMapping("/load-image")
public String loadImage(@RequestParam("image") MultipartFile image,
@AuthenticationPrincipal UserDetails user){
User authUser = userService.findUserByNickname(user.getUsername());
imageService.load(image, authUser);
return "redirect:/users/show/" authUser.getId();
}
}
安全配置:
@Configuration
@EnableWebSecurity
public class SecurityCFG extends WebSecurityConfigurerAdapter {
private final BCryptPasswordEncoder bCryptPasswordEncoder;
private final MyUserDetailsService userDetailsService;
@Autowired
public SecurityCFG(BCryptPasswordEncoder bCryptPasswordEncoder,
MyUserDetailsService userDetailsService) {
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
this.userDetailsService = userDetailsService;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(bCryptPasswordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
csrf().disable()
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/orders/**").authenticated()
.antMatchers("/users/orders").authenticated()
.antMatchers("/admin/**").hasRole("ADMIN")
.and()
.formLogin().loginPage("/users/login")
.usernameParameter("login")
.passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/users/login?logout").permitAll();
}
}
用戶詳細資訊服務:
@Service
public class MyUserDetailsService implements UserDetailsService {
private final UserService userService;
@Autowired
public MyUserDetailsService(UserService userService) {
this.userService = userService;
}
@Override
@Transactional
public UserDetails loadUserByUsername(final String login){
User user;
if(login.contains("@")){
user = userService.findUserByEmail(login);
}else{
user = userService.findUserByNickname(login);
}
if(user!=null){
List<GrantedAuthority> authorities = getUserAuthority(user.getRoles());
return buildUserForAuthentication(user, authorities);
}
throw new BadCredentialsException(String.format("Логин %s неверный",login));
}
private List<GrantedAuthority> getUserAuthority(Set<Role> userRoles) {
Set<GrantedAuthority> roles = new HashSet<>();
for (Role role : userRoles) {
roles.add(new SimpleGrantedAuthority(role.getRole()));
}
return new ArrayList<>(roles);
}
private UserDetails buildUserForAuthentication(User user,
List<GrantedAuthority> authorities) {
UserDetails userDetails = new
org.springframework.security.core.userdetails.User(user.getNickname(),
user.getPassword(),user.isActive(), true,true,
user.isAccountNonLocked(), authorities);
new AccountStatusUserDetailsChecker().check(userDetails);
return userDetails;
}
}
uj5u.com熱心網友回復:
這是因為您正在使用@Controller而不是@RestController
如果你想讓你的控制器正常作業,你應該使用@RestController而不是只@Controller在你的休息控制器類上使用。@RestController實際上是一個簡寫@Controller,@ResponseBody它基本上告訴 spring 你想要將所有來自函式的回應序列化為諸如 json 或 xml 等之類的東西。
您可以在此處閱讀有關注釋的更多資訊。
uj5u.com熱心網友回復:
從控制器中洗掉@RequestMapping("/images")解決了這個問題,但我不明白為什么會這樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425484.html
