登录流程
- 前端提交?户名、密码
- ?户微服务得到?户名密码
- ?户微服务组织数据包括:client_id:client_secret、组织、Basic Authorization、?户名、密码等参数
- ?户微服务使?RestTemplate发送HTTP请求给授权中?微服务
- 授权中?微服务校验通过颁发令牌
- 前端将令牌令牌存储到sessionStorage中,下次访问资源服务器通过Header携带访问?
配置
在nacos中对admin-service-dev.yaml进行配置
security:
oahtu2:
client:
access-token-uri: http://localhost:9098/oauth/token #令牌端点
user-authorization-uri: http://localhost:9098/oauth/authorize #授权端点
client-id: client
client-secret: 123456
grant-type: password
scope: read,write
登录方法:
@RestController
@RequestMapping("/user")
public class AdminUserController extends BaseController<AdminUserService, AdminUser> {
@Autowired
private OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails;
@Autowired
private OAuth2ClientProperties oAuth2ClientProperties;
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Autowired
private RestTemplate restTemplate;
@Autowired
private IMenuService menuService;
@RequestMapping("/login")
public ResponseEntity<OAuth2AccessToken> login(String username,String password) {
// 1:验证用户
AdminUser user = service.getByName(username);
if (null == user) {
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
if (!BPwdEncoderUtil.matches(password, user.getPassword())) {
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
// 2:使用restTemplate发送请求到授权服务器,申请令牌
// 请求头“basic auth”
String client_secret = oAuth2ClientProperties.getClientId() + ":"
+ oAuth2ClientProperties.getClientSecret();
client_secret = "Basic " + Base64.getEncoder().encodeToString(client_secret.getBytes());
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", client_secret);
// 请求参数
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.put("username", Collections.singletonList(username));
map.put("password", Collections.singletonList(password));
map.put("grant_type", Collections.singletonList(oAuth2ProtectedResourceDetails.getGrantType()));
map.put("scope", oAuth2ProtectedResourceDetails.getScope());
//HttpEntity(请求参数,头。。。)
HttpEntity httpEntity = new HttpEntity(map,headers);
return restTemplate.exchange(oAuth2ProtectedResourceDetails.getAccessTokenUri(), HttpMethod.POST, httpEntity, OAuth2AccessToken.class);
}
代码解析
?测试:
前端实现:
login/login.vue?
?router/index.js
?
|