2021.11.17 孤尽训练营D23——用户登录

登录流程

  • 前端提交⽤户名、密码
  • ⽤户微服务得到⽤户名密码
  • ⽤户微服务组织数据包括: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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值