在这种情况下,报错 "UnauthorizedException" 表明当前用户没有授权访问用户信息的权限。
解决方法取决于使用的身份验证和授权机制。以下是一种可能的解决方法,假设您正在使用Spring Security进行身份验证和授权。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/user-info").hasAnyRole("ADMIN", "USER")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("password").roles("ADMIN")
.and()
.withUser("user").password("password").roles("USER");
}
}
上述配置中,任何具有 "ADMIN" 或 "USER" 角色的用户将被授予访问 "/user-info" 端点的权限。
userProfileManager.getUserInfo()
之前,用户已经通过身份验证并具有相应的角色。您可以在控制器或服务类中使用 @PreAuthorize
注解进行授权检查。@RestController
public class UserController {
private final UserProfileManager userProfileManager;
public UserController(UserProfileManager userProfileManager) {
this.userProfileManager = userProfileManager;
}
@GetMapping("/user-info")
@PreAuthorize("hasAnyRole('ADMIN', 'USER')")
public UserInfo getUserInfo() {
return userProfileManager.getUserInfo();
}
}
在上面的示例中,只有具有 "ADMIN" 或 "USER" 角色的用户才能调用 getUserInfo()
方法。
请注意,这只是一个示例解决方案,具体的解决方法取决于您的应用程序架构和使用的身份验证/授权机制。