小编Luk*_*hey的帖子

Spring Security @AuthenticationPrincipal

我一直在努力让@AuthenticationPrincipal与自定义User类一起正常工作.不幸的是,用户始终为空.这是代码:

调节器

@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index(@AuthenticationPrincipal User user) {
    ModelAndView mav= new ModelAndView("/web/index");
    mav.addObject("user", user);
    return mav;
}
Run Code Online (Sandbox Code Playgroud)

安全配置

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    CustomUserDetailsService customUserDetailsService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
    }
Run Code Online (Sandbox Code Playgroud)

}

CustomUserDetailsS​​ervice

@Component
public class CustomUserDetailsService implements UserDetailsService {

@Autowired
UserRepository userRepository;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    // Spring Data findByXY function
    return userRepository.findByUsername(username);
}
Run Code Online (Sandbox Code Playgroud)

用户实体

public class User implements UserDetails{
    private …
Run Code Online (Sandbox Code Playgroud)

java spring spring-security

13
推荐指数
2
解决办法
2万
查看次数

自动装配 SimpMessagingTemplate

我在尝试在 Service 类中使用 SimpMessagingTemplate 时遇到了麻烦。以下是相关的代码片段:

UserService.java - 自动装配失败,模板 = null

@Service
public class UserService{
    @Autowired
    private SimpMessagingTemplate template;

    // Some Code

    public void tellUser(String username, String url) {
        // This is always true
        System.out.println("TEMPLATE NULL? " +(this.template == null));
        // Further code omitted
    }
}
Run Code Online (Sandbox Code Playgroud)

SocketController.java - 自动装配工作,Spring Websockets 工作正常。

@Controller
public class WebSocketController {
    @Autowired
    private SimpMessagingTemplate template;

    public void tellUser(String username, String url) {
        // False here, template is autowired correctly
        System.out.println("TEMPLATE NULL? " +(this.template == null));
        this.template.convertAndSendToUser(username, …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc websocket

5
推荐指数
1
解决办法
2980
查看次数

标签 统计

java ×2

spring ×2

spring-mvc ×1

spring-security ×1

websocket ×1