spring-cloud-oauth2实现用户认证及单点登录( 二 )
/** * @Author mzh * @Date 2020/10/24 */@Component(value = "http://kandian.youth.cn/index/customUserDetailsService")public class CustomUserDetailsService implements UserDetailsService {@Autowiredprivate PasswordEncoder passwordEncoder;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {// 1. 根据username 去数据库查询 user// 2.获取用户的角色和权限// 下面是写死 , 暂时不和数据库交互if(!(("admin").equals(username))){throw new UsernameNotFoundException("the user is not found");}else{String role = "ADMIN_ROLE";List authorities = new ArrayList<>();authorities.add(new SimpleGrantedAuthority(role));String password = passwordEncoder.encode("123456");return new User(username,password,authorities);}}}这里是在程序中写死了用户和权限 。 账号:admin , 密码:123456 , 权限:ADMIN_ROLE(注意是权限 , 不是角色) , 实际中应该从数据库获取用户和相关的权限 , 然后进行认证 。
5、OAuth2 配置OAuth2配置需要继承AuthorizationServerConfigurerAdapter类
/** * @Author mzh * @Date 2020/10/24 */@Configuration@EnableAuthorizationServerpublic class Oauth2Config extends AuthorizationServerConfigurerAdapter {@Autowiredprivate PasswordEncoder passwordEncoder;@Autowiredprivate UserDetailsService customUserDetailsService;@Autowiredprivate AuthenticationManager authenticationManager;@Autowiredprivate TokenStore redisTokenStore;/*** 对AuthorizationServerEndpointsConfigurer参数的重写* 重写授权管理Bean参数* 重写用户校验* 重写token缓存方式* @param endpointsConfigurer* @throws Exception*/@Overridepublic void configure(final AuthorizationServerEndpointsConfigurer endpointsConfigurer) throws Exception{endpointsConfigurer.authenticationManager(authenticationManager).userDetailsService(customUserDetailsService).tokenStore(redisTokenStore);}/*** 客户端的参数的重写* 这里是将数据直接写入内存 , 实际应该从数据库表获取* clientId:客户端Id* secret:客户端的密钥* authorizedGrantTypes:授权方式*authorization_code: 授权码类型,*implicit: 隐式授权,*password: 密码授权,*client_credentials: 客户端授权,*refresh_token: 通过上面4中方式获取的刷新令牌获取的新令牌 ,*注意是获取token和refresh_token之后 , 通过refresh_toke刷新之后的令牌* accessTokenValiditySeconds: token有效期* scopes 用来限制客户端访问的权限 , 只有在scopes定义的范围内 , 才可以正常的换取token* @param clients* @throws Exception*/@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception{clients.inMemory().and().withClient("mzh-etl").secret(passwordEncoder.encode("mzh-etl-8888")).authorizedGrantTypes("refresh_token","authorization_code","password").accessTokenValiditySeconds(3600).scopes("all");}@Overridepublic void configure(AuthorizationServerSecurityConfigurer serverSecurityConfigurer) throws Exception{serverSecurityConfigurer.allowFormAuthenticationForClients();serverSecurityConfigurer.checkTokenAccess("permitAll()");serverSecurityConfigurer.tokenKeyAccess("permitAll()");serverSecurityConfigurer.passwordEncoder(passwordEncoder);}}6、启动服务上述步骤完成之后启动服务 , 然后观察IDEA下方的Endpoints中的Mappings , 就可以找到相关的认证端口 。 主要的有以下几个:
POST /oauth/authorize授权码模式认证授权接口 GET/POST /oauth/token获取 token 的接口 POST/oauth/check_token检查 token 合法性接口到此 , 认证中心就算是创建完成了 。 我们通过idea的REST Client 来请求一个token进行测试 。
请求内容如下:
POST http://localhost:8888/oauth/token?grant_type=password --tt-darkmode-bgcolor: #1C1C1C;">POST http://localhost:8888/oauth/token?grant_type=password --tt-darkmode-bgcolor: #1C1C1C;">/oauth/token,请求参数是grant_type=password表示认证类型是password , username=admin --tt-darkmode-bgcolor: #1C1C1C;">admin , 密码是123456 , scope=all是权限相关的 , 之前在Oauth2Config中配置了scope是all 。
第四行表示在请求头中加入一个字段Authorization , 值为Basic空格base64(clientId:clientSecret) , 我们之前配置的clientId是“meh-etl” , clientSecret是"meh-etl-8888" , 所以这个值的base64是:bXpoLWV0bDptemgtZXRsLTg4ODg= 。
运行请求之后 , 如果参数都正确的话 , 获取到返回的内容如下:
{// token值 , 后面请求接口时都需要带上的token "access_token": "b4cb804c-93d2-4635-913c-265ff4f37309",// token的形式"token_type": "bearer",// 快过期时可以用这个换取新的token"refresh_token": "5cac05f4-158f-4561-ab16-b06c4bfe899f",// token的过期时间 "expires_in": 3599,// 权限范围 "scope": "all"}token值过期之后 , 可以通过refresh_token来换取新的access_token
POST http://localhost:8888/oauth/token?grant_type=refresh_token --tt-darkmode-bgcolor: #1C1C1C;">grant_type的值为“refresh_token” , refresh_token的值是要过期的token的refresh_token值 , 也就是之前请求获取Token的refresh_token值 , 请求之后会返回一个和获取token时一样格式的数据 。
- 看不上|为什么还有用户看不上华为Mate40系列来看看内行人怎么说
- 闲鱼|电诉宝:“闲鱼”网络欺诈成用户投诉热点 Q3获“不建议下单”评级
- 用户|5G信号有猫腻,又在考验用户的智商?
- 垫底|5G用户突破2亿:联通垫底,电信月增700万,中国移动有多少?
- iPhone|接近8千万!苹果被罚款了!中国iPhone用户这次真的该生气了!
- 苹果|iPhone13迎来变化!或回归指纹解锁,这几点备受用户喜爱
- 屏幕|苹果iPhone12屏幕不仅发白,还绿的你发慌,用户:环保绿
- 与用户|掌握好这4个步骤,实现了规模性的盈利
- 视频|短视频如何在前3秒吸引用户眼球?
- 用户|把更多主动权交还给用户,市面上敢这么做的或许只有OriginOS了
