编写Controller方法
生活随笔
收集整理的這篇文章主要介紹了
编写Controller方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
編寫登錄授權接口
接下來,我們需要在learn-auth-servcice編寫一個接口,對外提供登錄授權服務。基本流程如下:
-
客戶端攜帶用戶名和密碼請求登錄
-
授權中心調用用戶中心接口,根據用戶名和密碼查詢用戶信息
-
如果用戶名密碼正確,能獲取用戶,否則為空,則登錄失敗
-
如果校驗成功,則生成JWT并返回
生成公鑰和私鑰
我們需要在授權中心生成真正的公鑰和私鑰。我們必須有一個生成公鑰和私鑰的secret,這個可以配置到application.yml中:
learn:jwt:secret: learn@Login(Auth}*^31)&heihei% # 登錄校驗的密鑰pubKeyPath: C:\\tmp\\rsa\\rsa.pub # 公鑰地址priKeyPath: C:\\tmp\\rsa\\rsa.pri # 私鑰地址expire: 30 # 過期時間,單位分鐘然后編寫屬性類,加載這些數據:
@ConfigurationProperties(prefix = "learn.jwt") public class JwtProperties {private String secret; // 密鑰private String pubKeyPath;// 公鑰private String priKeyPath;// 私鑰private int expire;// token過期時間private PublicKey publicKey; // 公鑰private PrivateKey privateKey; // 私鑰private static final Logger logger = LoggerFactory.getLogger(JwtProperties.class);/*** @PostContruct:在構造方法執行之后執行該方法*/@PostConstructpublic void init(){try {File pubKey = new File(pubKeyPath);File priKey = new File(priKeyPath);if (!pubKey.exists() || !priKey.exists()) {// 生成公鑰和私鑰RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);}// 獲取公鑰和私鑰this.publicKey = RsaUtils.getPublicKey(pubKeyPath);this.privateKey = RsaUtils.getPrivateKey(priKeyPath);} catch (Exception e) {logger.error("初始化公鑰和私鑰失敗!", e);throw new RuntimeException();}}// getter setter ... }Controller
編寫授權接口,我們接收用戶名和密碼,校驗成功后,寫入cookie中。
-
請求方式:post
-
請求路徑:/accredit
-
請求參數:username和password
-
返回結果:無
代碼:
@RestController @EnableConfigurationProperties(JwtProperties.class) public class AuthController {@Autowiredprivate AuthService authService;@Autowiredprivate JwtProperties prop;/*** 登錄授權** @param username* @param password* @return*/@PostMapping("accredit")public ResponseEntity<Void> authentication(@RequestParam("username") String username,@RequestParam("password") String password,HttpServletRequest request,HttpServletResponse response) {// 登錄校驗String token = this.authService.authentication(username, password);if (StringUtils.isBlank(token)) {return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);}// 將token寫入cookie,并指定httpOnly為true,防止通過JS獲取和修改CookieUtils.setCookie(request, response, prop.getCookieName(),token, prop.getCookieMaxAge(), null, true);return ResponseEntity.ok().build();} }這里的cookie的name和生存時間,我們配置到屬性文件:application.yml:
然后在JwtProperties中添加屬性:
?
總結
以上是生活随笔為你收集整理的编写Controller方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 结合zuul网关的鉴权流程
- 下一篇: 完成登陆接口