当前位置:网站首页>Login authentication service
Login authentication service
2022-06-26 14:39:00 【Catch wind and shadow】
Common login mode integrating SMS :
@PostMapping(value = "/register")
public String register(@Valid UserRegisterVo vos, BindingResult result,
RedirectAttributes attributes) {
// If there is an error, go back to the registration page
if (result.hasErrors()) {
Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
attributes.addFlashAttribute("errors",errors);
// Validation error return to registration page
return "redirect:http://auth.gulimall.com/reg.html";
}
//1、 Validation code
String code = vos.getCode();
// Get deposit Redis The verification code in
String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
if (!StringUtils.isEmpty(redisCode)) {
// Intercepting string
if (code.equals(redisCode.split("_")[0])) {
// Delete verification code ; Token mechanism
stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+vos.getPhone());
// The verification code passed , Real registration , Call the remote service to register todo The remote invocation
R register = memberFeignService.register(vos);
if (register.getCode() == 0) {
// success
return "redirect:http://auth.gulimall.com/login.html";
} else {
// Failure
Map<String, String> errors = new HashMap<>();
errors.put("msg", register.getData("msg",new TypeReference<String>(){
}));
attributes.addFlashAttribute("errors",errors);
return "redirect:http://auth.gulimall.com/reg.html";
}
} else {
// Validation error return to registration page
Map<String, String> errors = new HashMap<>();
errors.put("code"," Verification code error ");
attributes.addFlashAttribute("errors",errors);
return "redirect:http://auth.gulimall.com/reg.html";
}
} else {
// Validation error return to registration page
Map<String, String> errors = new HashMap<>();
errors.put("code"," Verification code error ");
attributes.addFlashAttribute("errors",errors);
return "redirect:http://auth.gulimall.com/reg.html";
}
}
The remote invocation
@PostMapping(value = "/register")
public R register(@RequestBody MemberUserRegisterVo vo) {
try {
memberService.register(vo);
} catch (PhoneException e) {
return R.error(BizCodeEnum.PHONE_EXIST_EXCEPTION.getCode(),BizCodeEnum.PHONE_EXIST_EXCEPTION.getMessage());
} catch (UsernameException e) {
return R.error(BizCodeEnum.USER_EXIST_EXCEPTION.getCode(),BizCodeEnum.USER_EXIST_EXCEPTION.getMessage());
}
return R.ok();
}
After encryption, it is stored in the database :
@Override
public void register(MemberUserRegisterVo vo) {
MemberEntity memberEntity = new MemberEntity();
// Set the default level
MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
memberEntity.setLevelId(levelEntity.getId());
// Set other default information
// Check whether the user name and mobile phone number are unique . Abnormal perception , Exception mechanism
checkPhoneUnique(vo.getPhone());
checkUserNameUnique(vo.getUserName());
memberEntity.setNickname(vo.getUserName());
memberEntity.setUsername(vo.getUserName());
// The password goes on MD5 encryption
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
String encode = bCryptPasswordEncoder.encode(vo.getPassword());
memberEntity.setPassword(encode);
memberEntity.setMobile(vo.getPhone());
memberEntity.setGender(0);
memberEntity.setCreateTime(new Date());
// Save the data
this.baseMapper.insert(memberEntity);
}
Social login :
Click social login , It will be forwarded to the corresponding server , return code, We pass this code To get access_token
@Slf4j
@Controller
public class OAuth2Controller {
@Autowired
private MemberFeignService memberFeignService;
@GetMapping(value = "/oauth2.0/weibo/success")
public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
Map<String, String> map = new HashMap<>();
map.put("client_id","2077705774");
map.put("client_secret","40af02bd1c7e435ba6a6e9cd3bf799fd");
map.put("grant_type","authorization_code");
map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
map.put("code",code);
//1、 Returned according to user authorization code Exchange for access_token Do it once on the server post request
HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>());
//2、 Handle
if (response.getStatusLine().getStatusCode() == 200) {
// Got it access_token, Turn into a general social login object
String json = EntityUtils.toString(response.getEntity());
//String json = JSON.toJSONString(response.getEntity());
SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
// Know which social user
//1)、 If the current user is entering the website for the first time , Automatic registration ( Generate a member information for the current social user , In the future, this social account will correspond to the designated members )
// Log in or register this social user Social users have one feature , Registration and login are written together
System.out.println(socialUser.getAccess_token());
// Call remote service
R oauthLogin = memberFeignService.oauthLogin(socialUser);
if (oauthLogin.getCode() == 0) {
MemberResponseVo data = oauthLogin.getData("data", new TypeReference<MemberResponseVo>() {
});
log.info(" Login successful : User information :{}",data.toString());
//1、 For the first time session, Command the browser to save the card number ,JSESSIONID This cookie
// Which website the browser will visit in the future will bring this website cookie
//TODO 1、 Default token . Current domain ( Resolve subdomains session Sharing issues )
//TODO 2、 Use JSON Serialize objects to Redis in
session.setAttribute(LOGIN_USER,data);
//2、 Log in successfully and jump back to the home page
return "redirect:http://gulimall.com";
} else {
return "redirect:http://auth.gulimall.com/login.html";
}
} else {
return "redirect:http://auth.gulimall.com/login.html";
}
}
}
The remote invocation :
@FeignClient("gulimall-member")
public interface MemberFeignService {
@PostMapping(value = "/member/member/register")
R register(@RequestBody UserRegisterVo vo);
@PostMapping(value = "/member/member/loggin")
R login(@RequestBody UserLoginVo vo);
@PostMapping(value = "/member/member/oauth2/login")
R oauthLogin(@RequestBody SocialUser socialUser) throws Exception;
@PostMapping(value = "/member/member/weixin/login")
R weixinLogin(@RequestParam("accessTokenInfo") String accessTokenInfo);
}
controller:
@PostMapping(value = "/oauth2/login")
public R oauthLogin(@RequestBody SocialUser socialUser) throws Exception {
MemberEntity memberEntity = memberService.login(socialUser);
if (memberEntity != null) {
return R.ok().setData(memberEntity);
} else {
return R.error(BizCodeEnum.LOGINACCT_PASSWORD_EXCEPTION.getCode(),BizCodeEnum.LOGINACCT_PASSWORD_EXCEPTION.getMessage());
}
}
A method login and registration are implemented together :
@Override
public MemberEntity login(SocialUser socialUser) throws Exception {
// With login and registration logic
String uid = socialUser.getUid();
//1、 Judge whether the current social user has logged in to the system
MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
if (memberEntity != null) {
// This user has already registered
// Time and time to update the user's access token access_token
MemberEntity update = new MemberEntity();
update.setId(memberEntity.getId());
update.setAccessToken(socialUser.getAccess_token());
update.setExpiresIn(socialUser.getExpires_in());
this.baseMapper.updateById(update);
memberEntity.setAccessToken(socialUser.getAccess_token());
memberEntity.setExpiresIn(socialUser.getExpires_in());
return memberEntity;
} else {
//2、 If we don't find the corresponding record of the current social user, we need to register one
MemberEntity register = new MemberEntity();
//3、 Query the social account information of the current social user ( nickname 、 Gender, etc )
Map<String,String> query = new HashMap<>();
query.put("access_token",socialUser.getAccess_token());
query.put("uid",socialUser.getUid());
HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
if (response.getStatusLine().getStatusCode() == 200) {
// The query is successful
String json = EntityUtils.toString(response.getEntity());
JSONObject jsonObject = JSON.parseObject(json);
String name = jsonObject.getString("name");
String gender = jsonObject.getString("gender");
String profileImageUrl = jsonObject.getString("profile_image_url");
register.setNickname(name);
register.setGender("m".equals(gender)?1:0);
register.setHeader(profileImageUrl);
register.setCreateTime(new Date());
register.setSocialUid(socialUser.getUid());
register.setAccessToken(socialUser.getAccess_token());
register.setExpiresIn(socialUser.getExpires_in());
// Insert user information into the database
this.baseMapper.insert(register);
}
return register;
}
}
session Out of sync problem :
Use springsession Conduct management
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Integrate springsession -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
@EnableRedisHttpSession // Integrate Redis As session Storage Start class
Configuration class assignment session Storage location , It's not a server , It is redis in 
But the accepted parameters are all object types , Storage redis What is needed is json type :
Create configuration class :
@Configuration
public class GulimallSessionConfig {
@Bean
public CookieSerializer cookieSerializer() {
DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer();
// Zoom in
cookieSerializer.setDomainName("gulimall.com");
cookieSerializer.setCookieName("GULISESSION");
return cookieSerializer;
}
@Bean
public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
return new GenericJackson2JsonRedisSerializer();
}
}
边栏推荐
- 1075 pat judge (25 points)
- Hard (magnetic) disk (II)
- (improved) bubble sorting and (improved) cocktail sorting
- 网上股票开户安不安全?谁给回答一下
- Sword finger offer 06.24.35 Linked list
- Question bank and answers of the latest Guizhou construction eight (Mechanics) simulated examination in 2022
- Knowledge about the determination coefficient R2 and the relationship with the correlation coefficient
- Atcoder bit operation & Conclusion + formula derivation
- A remove the underline from the label
- Knowledge about adsorption
猜你喜欢
随机推荐
布局管理器~登录界面的搭建实例
Sword finger offer 06.24.35 Linked list
Pycharm远程连接服务器来跑代码
量化框架backtrader之一文读懂observer观测器
使用宝塔面板部署flask环境
Jianzhi offer 43.47.46.48 dynamic planning (medium)
Practice with the topic of bit operation force deduction
Two point answer, 01 score planning (mean / median conversion), DP
A solution to the problem that the display of newff function in neural network cannot be converted from double to struct
K gold Chef (two conditions, two points and difference)
Setup instance of layout manager login interface
Electron
9項規定6個嚴禁!教育部、應急管理部聯合印發《校外培訓機構消防安全管理九項規定》
Never use redis expired monitoring to implement scheduled tasks!
工作上对金额价格类小数点的总结以及坑
Understand the difference and use between jsonarray and jsonobject
Error when redis is started: could not create server TCP listening socket *: 6379: bind: address already in use - solution
Obtain information about hard disk and volume or partition (capacity, ID, volume label name, etc.)
这才是优美的文件系统挂载方式,亲测有效
9 regulations and 6 prohibitions! The Ministry of education and the emergency management department jointly issued the nine provisions on fire safety management of off campus training institutions









