其他分享
首页 > 其他分享> > 2021.11.17 孤尽训练营D23——用户登录

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

作者:互联网

登录流程

配置

在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

 

标签:map,2021.11,17,client,secret,孤尽,user,new,password
来源: https://blog.csdn.net/Kiaaaa/article/details/121454989