经典登录案例
package me.aboullaite.controller;
import java.util.Date;
import javax.servlet.ServletException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import me.aboullaite.model.User;
import me.aboullaite.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
@CrossOrigin(origins = "http://localhost", maxAge = 3600)
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/register", method = RequestMethod.POST)
public User registerUser(@RequestBody User user) {
return userService.save(user);
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@RequestBody User login) throws ServletException {
String jwtToken = "";
if (login.getEmail() == null || login.getPassword() == null) {
throw new ServletException("Please fill in username and password");
}
String email = login.getEmail();
String password = login.getPassword();
User user = userService.findByEmail(email);
if (user == null) {
throw new ServletException("User email not found.");
}
String pwd = user.getPassword();
if (!password.equals(pwd)) {
throw new ServletException("Invalid login. Please check your name and password.");
}
jwtToken = Jwts.builder().setSubject(email).claim("roles", "user").setIssuedAt(new Date())
.signWith(SignatureAlgorithm.HS256, "secretkey").compact();
return jwtToken;
}
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。