我使用 spring boot、Spring security、Spring oauth2、Eureka server 和 Zuul Proxy 创建了微服务。我创建了下面给出的三个项目。
- register-Eureka:用于在 Eureka 服务器中注册我的服务。
gatway-Zuul:我实现了zuul代理服务器,spring security和spring-security-oauth2。它工作正常,令牌正在生成,它也成功地将请求转发到其他微服务。
micorest:第三个微服务用于创建运行良好的宁静服务。
问题:我需要在 micorest 项目控制器上获取登录用户详细信息,但我不知道如何获取它。
我试图通过使用 Principal 类来获得它。
@RequestMapping(value = "/user", method = RequestMethod.GET)
public User getUser(Principal principal)
{
try
{
System.out.println("fine here mueraza"+principal.getName());
}
catch(Exception e) {
System.out.println("fine here mueraza===========principal is null==============");
}
return new User();
}
我使用 Principal 来获取值,但它总是 cumming null
@SpringBootApplication
@EnableDiscoveryClient
@EnableZuulProxy
public class GatewayZullApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayZullApplication.class, args);
}
}
Aouth2 配置
@Configuration
@EnableOAuth2Client
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
private static String REALM="microclient";
private static final int ONE_DAY = 60 * 60 * 24;
private static final int THIRTY_DAYS = 60 * 60 * 24 * 30;
@Autowired
private TokenStore tokenStore;
@Autowired
private UserApprovalHandler userApprovalHandler;
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("microclient")
.secret("{noop}secret")
.authorizedGrantTypes("password", "refresh_token")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("read", "write", "trust")
//.accessTokenValiditySeconds(ONE_DAY)
.accessTokenValiditySeconds(6000)
.refreshTokenValiditySeconds(THIRTY_DAYS);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler)
.authenticationManager(authenticationManager);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.realm(REALM);
}
}