业务层

创建com.oauth.service.AuthService接口,并添加授权认证方法:

package com.leon.oauth.service;import com.leon.oauth.util.AuthToken;public interface AuthService {/**** 授权认证方法*/AuthToken login(String username, String password, String clientId, String clientSecret);
}

创建com.oauth.service.impl.AuthServiceImpl实现类,实现获取令牌数据,这里认证获取令牌采用的是密码授权模式,用的是RestTemplate向OAuth服务发起认证请求,代码如下:

package com.leon.oauth.service.impl;import com.alibaba.fastjson.JSON;
import com.leon.oauth.service.AuthService;
import com.leon.oauth.util.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;import java.io.IOException;
import java.util.Map;/****** @Author: www.leon* @Date: 2019/7/7 16:23* @Description: com.leon.oauth.service.impl****/
@Service
public class AuthServiceImpl implements AuthService {@Autowiredprivate LoadBalancerClient loadBalancerClient;@Autowiredprivate RestTemplate restTemplate;/**** 授权认证方法* @param username* @param password* @param clientId* @param clientSecret* @return*/@Overridepublic AuthToken login(String username, String password, String clientId, String clientSecret) {//申请令牌AuthToken authToken = applyToken(username,password,clientId, clientSecret);if(authToken == null){throw new RuntimeException("申请令牌失败");}return authToken;}/***** 认证方法* @param username:用户登录名字* @param password:用户密码* @param clientId:配置文件中的客户端ID* @param clientSecret:配置文件中的秘钥* @return*/private AuthToken applyToken(String username, String password, String clientId, String clientSecret) {//选中认证服务的地址ServiceInstance serviceInstance = loadBalancerClient.choose("user-auth");if (serviceInstance == null) {throw new RuntimeException("找不到对应的服务");}//获取令牌的urlString path = serviceInstance.getUri().toString() + "/oauth/token";//定义bodyMultiValueMap<String, String> formData = new LinkedMultiValueMap<>();//授权方式formData.add("grant_type", "password");//账号formData.add("username", username);//密码formData.add("password", password);//定义头MultiValueMap<String, String> header = new LinkedMultiValueMap<>();header.add("Authorization", httpbasic(clientId, clientSecret));//指定 restTemplate当遇到400或401响应时候也不要抛出异常,也要正常返回值restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {@Overridepublic void handleError(ClientHttpResponse response) throws IOException {//当响应的值为400或401时候也要正常响应,不要抛出异常if (response.getRawStatusCode() != 400 && response.getRawStatusCode() != 401) {super.handleError(response);}}});Map map = null;try {//http请求spring security的申请令牌接口ResponseEntity<Map> mapResponseEntity = restTemplate.exchange(path, HttpMethod.POST,new HttpEntity<MultiValueMap<String, String>>(formData, header), Map.class);//获取响应数据map = mapResponseEntity.getBody();} catch (RestClientException e) {throw new RuntimeException(e);}if(map == null || map.get("access_token") == null || map.get("refresh_token") == null || map.get("jti") == null) {//jti是jwt令牌的唯一标识作为用户身份令牌throw new RuntimeException("创建令牌失败!");}//将响应数据封装成AuthToken对象AuthToken authToken = new AuthToken();//访问令牌(jwt)String accessToken = (String) map.get("access_token");//刷新令牌(jwt)String refreshToken = (String) map.get("refresh_token");//jti,作为用户的身份标识String jwtToken= (String) map.get("jti");authToken.setJti(jwtToken);authToken.setAccessToken(accessToken);authToken.setRefreshToken(refreshToken);return authToken;}/**** base64编码* @param clientId* @param clientSecret* @return*/private String httpbasic(String clientId,String clientSecret){//将客户端id和客户端密码拼接,按“客户端id:客户端密码”String string = clientId+":"+clientSecret;//进行base64编码byte[] encode = Base64Utils.encode(string.getBytes());return "Basic "+new String(encode);}
}

控制层

package com.leon.oauth.controller;import com.leon.oauth.service.AuthService;
import com.leon.oauth.util.AuthToken;
import com.leon.oauth.util.CookieUtil;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletResponse;@RestController
@RequestMapping(value = "/userx")
public class AuthController {//客户端ID@Value("${auth.clientId}")private String clientId;//秘钥@Value("${auth.clientSecret}")private String clientSecret;//Cookie存储的域名@Value("${auth.cookieDomain}")private String cookieDomain;//Cookie生命周期@Value("${auth.cookieMaxAge}")private int cookieMaxAge;@AutowiredAuthService authService;@PostMapping("/login")public Result login(String username, String password) {if(StringUtils.isEmpty(username)){throw new RuntimeException("用户名不允许为空");}if(StringUtils.isEmpty(password)){throw new RuntimeException("密码不允许为空");}//申请令牌AuthToken authToken =  authService.login(username,password,clientId,clientSecret);//用户身份令牌String access_token = authToken.getAccessToken();//将令牌存储到cookiesaveCookie(access_token);return new Result(true, StatusCode.OK,"登录成功!");}/**** 将令牌存储到cookie* @param token*/private void saveCookie(String token){HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();CookieUtil.addCookie(response,cookieDomain,"/","Authorization",token,cookieMaxAge,false);}
}

工具封装

在user-oauth工程中添加如下工具对象,方便操作令牌信息。

创建com.oauth.util.AuthToken类,存储用户令牌数据,代码如下:

package com.leon.oauth.util;import java.io.Serializable;/***** @Description:用户令牌封装*****/
public class AuthToken implements Serializable{//令牌信息String accessToken;//刷新token(refresh_token)String refreshToken;//jwt短令牌String jti;public String getAccessToken() {return accessToken;}public void setAccessToken(String accessToken) {this.accessToken = accessToken;}public String getRefreshToken() {return refreshToken;}public void setRefreshToken(String refreshToken) {this.refreshToken = refreshToken;}public String getJti() {return jti;}public void setJti(String jti) {this.jti = jti;}
}

创建com.oauth.util.CookieUtil类,操作Cookie,代码如下:

package com.leon.oauth.util;import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;public class CookieUtil {/*** 设置cookie** @param response* @param name     cookie名字* @param value    cookie值* @param maxAge   cookie生命周期 以秒为单位*/public static void addCookie(HttpServletResponse response, String domain, String path, String name,String value, int maxAge, boolean httpOnly) {Cookie cookie = new Cookie(name, value);cookie.setDomain(domain);cookie.setPath(path);cookie.setMaxAge(maxAge);cookie.setHttpOnly(httpOnly);response.addCookie(cookie);}/*** 根据cookie名称读取cookie* @param request* @return map<cookieName,cookieValue>*/public static Map<String,String> readCookie(HttpServletRequest request, String ... cookieNames) {Map<String,String> cookieMap = new HashMap<String,String>();Cookie[] cookies = request.getCookies();if (cookies != null) {for (Cookie cookie : cookies) {String cookieName = cookie.getName();String cookieValue = cookie.getValue();for(int i=0;i<cookieNames.length;i++){if(cookieNames[i].equals(cookieName)){cookieMap.put(cookieName,cookieValue);}}}}return cookieMap;}
}

用户密码登录改造实现相关推荐

  1. linux7怎么禁止用户密码登录,Centos7锁定用户禁止登陆的解决办法

    针对Linux上的用户,如果用户连续3次登录失败,就锁定该用户,几分钟后该用户再自动解锁.linux有一个pam_tally2.so的PAM模块,来限定用户的登录失败次数,如果次数达到设置的阈值,则锁 ...

  2. java后台实现用户密码登录和手机短信登录

    1.账号密码登录:获取用户名.密码,检验是否存在该账号,以及该账号是否有效(未冻结.未删除),检验密码是否正确 public Result<JSONObject> login(@Reque ...

  3. python实现简单的用户密码登录控制(输入三次就锁定用户)

    问题描述 我们经常在登录一些网站的时候,发现我们如果连续的输错好几次密码,我们的帐号就被锁定起来了,那这个过程是如何实现的呢?本程序主要就是解决以下3件事情 1.输入用户名密码 2.认证成功并显示欢迎 ...

  4. Python3.5 Day1作业:实现用户密码登录,输错三次锁定。

    作业需求: 1.输入用户名密码 2.认证成功后显示欢迎信息 3.输错三次后锁定 实现思路: 1.判断用户是否在黑名单,如果在黑名单提示账号锁定. 2.判断用户是否存在,如果不存在提示账号不存在. 3. ...

  5. (Java)实现一个用户密码登录的弹窗界面

    目录 一.前言 二.涉及到的知识点代码 三.代码部分 四.程序运行结果(弹出) 一.前言 1.本代码是我在上学时写的,有一些地方没能完美实现,请包涵也请多赐教! 2.本弹窗界面可以根据简单的要求进行输 ...

  6. c语言:模拟用户密码登录

    #include<stdio.h> #include<string.h> int main() {int i = 0;char password[20] = { 0 };for ...

  7. javaweb关于用户是否登录全局判断,没有登录跳转到登录界面

    javaweb关于用户是否登录全局判断,没有登录跳转到登录界面 有这样一个需求,用户密码登录网站,在session中保留了用户的信息,但是用户很长时间没有再操作该界面,用户的session则被浏览器清 ...

  8. AWS服务器密码登录设置

    https://aws.amazon.com/cn/premiumsupport/knowledge-center/ec2-password-login/  最近在aws申请了一个服务器,选择的AMI ...

  9. 关于win10忘记用户密码,却无法找回,反复让我输入密码

    关于win10忘记用户密码,却无法找回,反复让我输入密码 win10忘记用户密码,打算通过账号邮箱途径找回密码,验证完邮箱之后,再次让我输入密码,我他妈是在找回密码,我知道密码还用找回?(垃圾微软都是 ...

最新文章

  1. dateformat java 并发_java.text.DateFormat 多线程并发问题
  2. 机器学习:集成学习(ensemble),bootstrap,Bagging,随机森林,Boosting
  3. 常见的几种RuntimeException
  4. Postman安装与使用(网络请求神器)--post、get请求
  5. java 布隆过滤器_什么是布隆过滤器(Bloom Filter)?
  6. github(GitHub Flavored Markdown)
  7. 极性大小判断技巧_别愣着了,来分析分析正极性半波整流电路!
  8. 《Python知识手册》V2.1版,高清PDF免费获取
  9. AppStore安装历史版本,利用Charles抓包安装历史版本
  10. ACM程序设计之马拉松竞赛
  11. ysoserial exploit/JRMPClient
  12. 2021春运12306抢票攻略
  13. 甲型流感H1N1流感症状预防和治疗
  14. TMS320F28035 之ECAP捕获频率
  15. Win7 系统还原被管理员禁用
  16. 怎么批量生成100多条短视频素材
  17. 装多系统的U盘启动盘的制作
  18. 学习笔记(43):R语言入门基础-plot绘制箱体图
  19. 分布式:Docker
  20. 【C语言】c语言中的数组和字符串

热门文章

  1. InfluxDB中文文档
  2. UVA11019 Martix Matcher --- AC自动机
  3. Spark 运行模式 standalong yarn
  4. openstack-networking-neutron(一)---端到端和点到点的理解
  5. ---WebCam网络摄像头6 编译WebCam
  6. 演练:在 Windows 窗体中承载 Windows Presentation Foundation 复合控件 【转载】
  7. 【Maven】Maven POM配置详解
  8. 清理收藏夹中的json
  9. C++ Primer Plus 笔记第十章
  10. 使用对象存储应对勒索病毒