spring-cloud-oauth2实现用户认证及单点登录( 三 )


微服务1、引入需要的maven包org.springframework.bootspring-boot-starter-weborg.springframework.cloudspring-cloud-starter-oauth2org.springframework.bootspring-boot-starter-data-redis2、配置application.ymlspring:application:name: mzh-etlredis:database: 1host: localhostport: 6379jedis:pool:max-active: 8max-idle: 8min-idle: 0timeout: 10000server:port: 8889security:oauth2:client:# 需要和之前认证中心配置中的一样client-id: mzh-etlclient-secret: mzh-etl-8888# 获取token的地址access-token-uri: http://localhost:8888/oauth/tokenresource:id: mzh-etluser-info-uri: user-infoauthorization:# 检查token的地址check-token-access: http://localhost:8888/oauth/check_token这里的配置一定要仔细 , 必须和之前认证中心中配置的一样 。
3、资源配置在OAuth2中接口也称为资源 , 资源的权限也就是接口的权限 。 spring-cloud-oauth2提供了关于资源的注解@EnableResourceServer
/** * @Author mzh * @Date 2020/10/24 */@Configuration@EnableResourceServer@EnableGlobalMethodSecurity(prePostEnabled = true)public class ResourceServerConfig extends ResourceServerConfigurerAdapter {@Value("${security.oauth2.client.client-id}")private String clientId;@Value("${security.oauth2.client.client-secret}")private String clientSecret;@Value("${security.oauth2.authorization.check-token-access}")private String checkTokenEndpointUrl;@Autowiredprivate RedisConnectionFactory redisConnectionFactory;@Bean("redisTokenStore")public TokenStore redisTokenStore(){return new RedisTokenStore(redisConnectionFactory);}@Beanpublic RemoteTokenServices tokenService() {RemoteTokenServices tokenService = new RemoteTokenServices();tokenService.setClientId(clientId);tokenService.setClientSecret(clientSecret);tokenService.setCheckTokenEndpointUrl(checkTokenEndpointUrl);return tokenService;}@Overridepublic void configure(ResourceServerSecurityConfigurer resources) throws Exception {resources.tokenServices(tokenService());}@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/get/**").authenticated();}}4、创建一个接口@RestControllerpublic class UserController {@GetMapping("get")@PreAuthorize("hasAuthority('ADMIN_ROLE')")public Object get(Authentication authentication){authentication.getAuthorities();OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();String token = details.getTokenValue();return token;}}这个接口就是会返回一个请求他时携带的token值 , @PreAuthorize会在请求接口时检查是否用权限“ADMIN_ROLE”(之前认证中心配置的权限)
5、启动服务启动服务 , 只有当用户有“ADMIN_ROLE“的时候 , 才能正确返回 , 否则返回401未授权
同样适用REST Client来发起一个请求:
GET http://localhost:8889/get Accept: */* Cache-Control: no-cache Authorization: bearer b4cb804c-93d2-4635-913c-265ff4f37309【spring-cloud-oauth2实现用户认证及单点登录】请求路径是http://localhost:8889/get 然后在请求头部带上我们上一步骤获取到的token , 放入到Authorization中 , 格式是bearer空格token值 , 如果请求成功 , 就会把token原样返回 。