Def*_*fit 6 java spring-security
问题是:我有一个身份验证服务器(spring security)和一个资源服务器\xef\xbc\x8c资源服务器无法正确获取主要用户。
\n\nSpring Boot 版本:2.0.7\nSpring Cloud 版本:Finchley.SR2
\n\n首先,我去Auth-server获取访问令牌,并且成功。\n然后,我使用令牌发布Resource-server,Resource-server的控制器可以获得一个principal。\n但是,principal是一个字符串,而不是 UserDetails 对象。
\n\n身份验证服务器网络安全配置如下:
\n\n@Configuration\n@EnableWebSecurity\n@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)\npublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {\n @Autowired\n private MaliUserDetailsService maliUserDetailsService;\n\n @Bean\n public PasswordEncoder passwordEncoder() {\n return new BCryptPasswordEncoder();\n }\n\n @Override\n protected void configure(HttpSecurity http) throws Exception {\n http\n .authorizeRequests()\n .anyRequest().authenticated()\n .and()\n .csrf().disable();\n }\n\n @Override\n protected void configure(AuthenticationManagerBuilder auth) throws Exception {\n auth.userDetailsService(maliUserDetailsService).passwordEncoder(passwordEncoder());\n}\n\n @Override\n @Bean\n public AuthenticationManager authenticationManagerBean() throws Exception {\n return super.authenticationManagerBean();\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n身份验证服务器 UserDetailsService\xef\xbc\x9a
\n\n@Override\npublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {\n User user = userRepository.findByUsername(username);\n if (user == null) {\n throw new UsernameNotFoundException(username);\n }\n return user;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n资源服务器控制器\xef\xbc\x9a
\n\n@GetMapping("/test")\npublic String test(Authentication authentication) {\n UserDetails userDetails = (UserDetails) authentication.getPrincipal();\n\n return "hello " + userDetails.getUsername();\n}\nRun Code Online (Sandbox Code Playgroud)\n\n当我发布到资源服务器时,它抛出异常:
\n\njava.lang.ClassCastException: class java.lang.String cannot be cast to class org.springframework.security.core.userdetails.UserDetails (java.lang.String is in module java.base of loader \'bootstrap\'; org.springframework.security.core.userdetails.UserDetails is in unnamed module of loader \'app\')\nRun Code Online (Sandbox Code Playgroud)\n\n\n\n==============\n然后我尝试更改控制器代码,如下所示:
\n\n@GetMapping("/test")\npublic String test(Authentication authentication) {\n return "hello " + authentication.getPrincipal().toString();\n}\nRun Code Online (Sandbox Code Playgroud)\n\n\n\n为什么控制器中的主体是字符串而不是 UserDetails 对象?怎么解决呢。
\n| 归档时间: |
|
| 查看次数: |
2033 次 |
| 最近记录: |