重大更新,系统全面接入第三方登录api,可以实现Facebook登陆

Merge branch 'macro'
This commit is contained in:
18019465682 2020-12-15 15:58:54 +08:00
commit a1c435bb53
15 changed files with 158 additions and 214 deletions

View File

@ -1,123 +0,0 @@
package com.letoy.edu.config.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.letoy.edu.service.MyDetailsUserService;
import com.letoy.edu.service.auth.AuthUser;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.*;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* 拦截器
*/
@Component
public class MyEmailLoginFilter extends OncePerRequestFilter {
private AuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
private AuthenticationFailureHandler failureHandler = new SimpleUrlAuthenticationFailureHandler();
private AuthenticationManager authenticationManager;
public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler successHandler) {
Assert.notNull(successHandler, "successHandler cannot be null");
this.successHandler = successHandler;
}
public void setAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) {
Assert.notNull(failureHandler, "failureHandler cannot be null");
this.failureHandler = failureHandler;
}
protected AuthenticationSuccessHandler getSuccessHandler() {
return this.successHandler;
}
protected AuthenticationFailureHandler getFailureHandler() {
return this.failureHandler;
}
protected AuthenticationManager getAuthenticationManager() {
return this.authenticationManager;
}
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Resource
MyDetailsUserService myDetailsUserService;
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
if (!"/email/login".equals(request.getRequestURI())) {
chain.doFilter(request, response);
} else {
System.out.println("email验证模块");
ObjectMapper mapper = new ObjectMapper();
Map<String, String> authenticationBean = null;
try (InputStream is = request.getInputStream()) {
authenticationBean = mapper.readValue(is, Map.class);
} catch (IOException e) {
//将异常放到自定义的异常类中
System.out.println(e.getMessage());
}
System.out.println("当前登录的邮箱是:" + authenticationBean.get("email"));
String email = authenticationBean.get("email");
// System.out.println("headerToken = " + headerToken);
// System.out.println("request getMethod = " + request.getMethod());
//通过令牌获取用户名称
AuthUser authUser = myDetailsUserService.loginByEmail(email);
String username = authUser.getUsername();
System.out.println("Token_username = " + username);
//判断用户不为空且SecurityContextHolder授权信息还是空的
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
//通过用户信息得到UserDetails
UserDetails userDetails = authUser;
System.out.println(userDetails);
//验证令牌有效性
// 将用户信息存入 authentication方便后续校验
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(
userDetails,
null,
userDetails.getAuthorities()
);
//
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
// authentication 存入 ThreadLocal方便后续获取用户信息
SecurityContextHolder.getContext().setAuthentication(authentication);
}
ObjectMapper mapper2 = new ObjectMapper();
HashMap resMap = new HashMap();
resMap.put("token","fasdfsdg");
String data = mapper2.writeValueAsString("退出成功");
JSONAuthentication.WriteJSONS(request, response, resMap);
}
}
}

View File

@ -2,13 +2,15 @@ package com.letoy.edu.config.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.letoy.edu.service.MyDetailsUserService;
import com.letoy.edu.entity.TokenInfo;
import com.letoy.edu.service.ThirdPartService;
import com.letoy.edu.service.auth.AuthUser;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.*;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;
@ -61,7 +63,7 @@ public class MyThirdPartLoginFilter extends OncePerRequestFilter {
}
@Resource
MyDetailsUserService myDetailsUserService;
ThirdPartService thirdPartService;
@Override
protected void doFilterInternal(HttpServletRequest request,
@ -75,46 +77,44 @@ public class MyThirdPartLoginFilter extends OncePerRequestFilter {
try (InputStream is = request.getInputStream()) {
authenticationBean = mapper.readValue(is, Map.class);
} catch (IOException e) {
//将异常放到自定义的异常类中
System.out.println(e.getMessage());
}
System.out.println("当前登录的邮箱是:" + authenticationBean.get("token"));
System.out.println("当前登录的Token是:" + authenticationBean.get("token"));
System.out.println("当前登录的类型:" + authenticationBean.get("type"));
String type = authenticationBean.get("type");
String token = authenticationBean.get("token");
// System.out.println("headerToken = " + headerToken);
// System.out.println("request getMethod = " + request.getMethod());
String studentNumber = authenticationBean.get("studentNumber");
TokenInfo tokenInfo = new TokenInfo();
switch (type) {
case "facebook":
tokenInfo.setFacebook(token);
break;
case "linkedin":
tokenInfo.setLinkedin(token);
break;
}
//通过令牌获取用户名称
AuthUser authUser = myDetailsUserService.loginByEmail(token);
String username = authUser.getUsername();
System.out.println("Token_username = " + username);
System.out.println(studentNumber);
//判断用户不为空且SecurityContextHolder授权信息还是空的
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
//通过用户信息得到UserDetails
UserDetails userDetails = authUser;
System.out.println(userDetails);
//验证令牌有效性
// 将用户信息存入 authentication方便后续校验
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(
userDetails,
null,
userDetails.getAuthorities()
);
//
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
// authentication 存入 ThreadLocal方便后续获取用户信息
SecurityContextHolder.getContext().setAuthentication(authentication);
AuthUser authUser = thirdPartService.loginByTokenAndType(tokenInfo, type, Integer.parseInt(studentNumber));
if (authUser != null) {
String username = authUser.getUsername();
System.out.println("Token_username = " + username);
if (SecurityContextHolder.getContext().getAuthentication() == null) {
Map<String, Object> resMap = new HashMap<>();
resMap.put("status", 0);
resMap.put("token", authUser.getSystemToken());
JSONAuthentication.WriteJSONS(request, response, resMap);
}
} else {
Map<String, Object> resMap = new HashMap<>();
resMap.put("status", 10);
JSONAuthentication.WriteJSONS(request, response, resMap);
}
ObjectMapper mapper2 = new ObjectMapper();
HashMap resMap = new HashMap();
resMap.put("token","fasdfsdg");
String data = mapper2.writeValueAsString("退出成功");
JSONAuthentication.WriteJSONS(request, response, resMap);
}
}

View File

@ -1,7 +1,6 @@
package com.letoy.edu.config.auth;
import com.letoy.edu.service.MyDetailsUserService;
import com.letoy.edu.utils.BCryptPasswordEncoderUtil;
import com.letoy.edu.utils.DynamicPermission;
import org.springframework.beans.factory.annotation.Autowired;
@ -9,14 +8,12 @@ import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.cors.CorsUtils;
import javax.annotation.Resource;
@ -32,17 +29,12 @@ public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
private UserDetailsService userDetailsService;
@Resource
MyDetailsUserService myDetailsUserService;
@Resource
MyAuthenticationEntryPoint myAuthenticationEntryPoint;
@Resource
MyOncePerRequestFilter myOncePerRequestFilter;
@Resource
MyEmailLoginFilter myEmailLoginFilter;
@Resource
MyThirdPartLoginFilter myThirdPartLoginFilter;
@ -97,9 +89,10 @@ public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
myEmailLoginFilter.setAuthenticationSuccessHandler(myAuthenticationSuccessHandler);
myEmailLoginFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);
myEmailLoginFilter.setAuthenticationManager(authenticationManagerBean());
myThirdPartLoginFilter.setAuthenticationSuccessHandler(myAuthenticationSuccessHandler);
myThirdPartLoginFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);
myThirdPartLoginFilter.setAuthenticationManager(authenticationManagerBean());
//第1步解决跨域问题cors 预检请cors求放行,让Spring security 放行所有preflight requestcors 预检请求
http.authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll();
@ -135,7 +128,6 @@ public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
//第5步拦截token并检测 UsernamePasswordAuthenticationFilter 之前添加 JwtAuthenticationTokenFilter
http.addFilterBefore(myOncePerRequestFilter, UsernamePasswordAuthenticationFilter.class);
http.addFilterBefore(myEmailLoginFilter, UsernamePasswordAuthenticationFilter.class);
http.addFilterBefore(myThirdPartLoginFilter, UsernamePasswordAuthenticationFilter.class);
@ -169,5 +161,4 @@ public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
}
}

View File

@ -8,5 +8,5 @@ public interface TokenInfoMapper {
TokenInfo getTokenByTokenInfo(TokenInfo tokenInfo);
TokenInfo getTokenByUserId(String userId);
int insertTokenInfo(TokenInfo tokenInfo);
int updateTokenInfo(TokenInfo tokenInfo);
int updateTokenInfoByUserId(TokenInfo tokenInfo);
}

View File

@ -16,4 +16,6 @@ public interface UserMapper {
int insertToken(String id, String token);
User loginUser(User user);
User getUserByUserId(String userId);
}

View File

@ -45,7 +45,7 @@ public class AuthUserDetailsServiceImpl implements UserDetailsService {
// for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(user.getRoles()));
// }
return new AuthUser(user.getName(), user.getPassword(), user.getState(), authorities,user.getUserId(),"");
return new AuthUser(user.getEmail(), user.getName(), "", user.getUserId(), user.getPassword(), 0,authorities);
}
}

View File

@ -1,22 +0,0 @@
package com.letoy.edu.service.Impl;
import com.letoy.edu.service.MyDetailsUserService;
import com.letoy.edu.service.auth.AuthUser;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class MyDetailsUserServiceImpl implements MyDetailsUserService {
@Override
public AuthUser loginByEmail(String email) {
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
// for (String role : roles) {
authorities.add(new SimpleGrantedAuthority("admin"));
AuthUser authUser = new AuthUser("mk","$2a$10$Ar/V6g8XW70e1MEzcA2i2.v9jxPHZiSMkwn7SR9D8k07XATBMs8UO",0,authorities,"","lyhkeven@126.com");
return authUser;
}
}

View File

@ -1,14 +1,57 @@
package com.letoy.edu.service.Impl;
import com.letoy.edu.dao.StudentInfoMapper;
import com.letoy.edu.dao.TokenInfoMapper;
import com.letoy.edu.dao.UserMapper;
import com.letoy.edu.entity.TokenInfo;
import com.letoy.edu.entity.User;
import com.letoy.edu.service.ThirdPartService;
import com.letoy.edu.service.auth.AuthUser;
import com.letoy.edu.vo.Student;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Service
public class ThirdPartServiceImpl implements ThirdPartService {
@Resource
StudentInfoMapper studentInfoMapper;
@Resource
TokenInfoMapper tokenInfoMapper;
@Resource
UserMapper userMapper;
@Override
public AuthUser loginByTokenAndType() {
return null;
public AuthUser loginByTokenAndType(TokenInfo tokenInfo, String type, int studentNumber) {
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
if (studentNumber == 0) {
TokenInfo resToken = tokenInfoMapper.getTokenByTokenInfo(tokenInfo);
if (resToken == null) {
//登录失败token不存在
return null;
} else {
User user = userMapper.getUserByUserId(resToken.getUserId());
authorities.add(new SimpleGrantedAuthority(user.getRoles()));
return new AuthUser(user.getEmail(), user.getName(), resToken.getSystemToken(), user.getUserId(), user.getPassword(), 0, authorities);
}
} else {
System.out.println("开始注册");
Student student = studentInfoMapper.findStudentByNumber(studentNumber);
tokenInfo.setUserId(student.getUserId());
System.out.println(tokenInfo.toString());
tokenInfoMapper.updateTokenInfoByUserId(tokenInfo);
User user = userMapper.getUserByUserId(student.getUserId());
TokenInfo resToken = tokenInfoMapper.getTokenByUserId(user.getUserId());
authorities.add(new SimpleGrantedAuthority(user.getRoles()));
return new AuthUser(user.getEmail(), user.getName(), resToken.getSystemToken(), user.getUserId(), user.getPassword(), 0, authorities);
}
}
}

View File

@ -25,6 +25,6 @@ public class TokenServiceImpl implements TokenService {
@Override
public int updateTokenInfo(TokenInfo tokenInfo) {
return tokenInfoMapper.updateTokenInfo(tokenInfo);
return tokenInfoMapper.updateTokenInfoByUserId(tokenInfo);
}
}

View File

@ -1,7 +0,0 @@
package com.letoy.edu.service;
import com.letoy.edu.service.auth.AuthUser;
public interface MyDetailsUserService {
AuthUser loginByEmail(String email);
}

View File

@ -1,9 +1,10 @@
package com.letoy.edu.service;
import com.letoy.edu.entity.TokenInfo;
import com.letoy.edu.entity.User;
import com.letoy.edu.service.auth.AuthUser;
public interface ThirdPartService {
AuthUser loginByTokenAndType();
AuthUser loginByTokenAndType(TokenInfo tokenInfo, String type,int studentNumber);
}

View File

@ -15,6 +15,8 @@ public class AuthUser implements UserDetails {
private String email;
private String username;
private String systemToken;
private String id;
private String password;
@ -26,13 +28,22 @@ public class AuthUser implements UserDetails {
public AuthUser() {
}
public AuthUser(String username, String password, Integer state, Collection<? extends GrantedAuthority> authorities,String id,String email) {
public AuthUser(String email, String username, String systemToken, String id, String password, Integer state, Collection<? extends GrantedAuthority> authorities) {
this.email = email;
this.username = username;
this.systemToken = systemToken;
this.id = id;
this.password = password;
this.state = state;
this.authorities = authorities;
this.id = id;
this.email = email;
}
public String getSystemToken() {
return systemToken;
}
public void setSystemToken(String systemToken) {
this.systemToken = systemToken;
}
public String getEmail() {

View File

@ -7,8 +7,8 @@
third_token_id, facebook, linkedin, system_token, user_id
from token_info
where
<if test="type=='facebook'">facebook = #{facebook}</if>
<if test="type=='linkedin'">linkedin = #{linkedin}</if>
<if test="facebook!=null">facebook = #{facebook}</if>
<if test="linkedin!=null">linkedin = #{linkedin}</if>
</select>
<select id="getTokenByUserId" resultType="TokenInfo">
@ -26,7 +26,7 @@
values (#{thirdTokenId}, #{facebook}, #{linkedin}, #{systemToken}, #{userId})
</insert>
<update id="updateTokenInfo" parameterType="TokenInfo">
<update id="updateTokenInfoByUserId" parameterType="TokenInfo">
update token_info
<set>
<if test="facebook!=null">facebook = #{facebook}</if>

View File

@ -3,11 +3,21 @@
<mapper namespace="com.letoy.edu.dao.UserMapper">
<select id="getUserIdByNamePassword" resultType="String">
select user_id from user_info where name = #{name} and password = #{password};
select user_id
from user_info
where name = #{name}
and password = #{password};
</select>
<select id="getUserByName" resultType="User">
select user_id,name,password,roles from user_info where name = #{name};
select user_id, name, password, roles
from user_info
where name = #{name};
</select>
<select id="getUserByUserId" resultType="User">
select user_id, name, password, roles
from user_info
where user_id = #{userId};
</select>
<update id="insertToken">

View File

@ -0,0 +1,38 @@
package com.letoy.edu.dao;
import com.letoy.edu.entity.TokenInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import static org.junit.Assert.*;
@SpringBootTest
@RunWith(SpringRunner.class)
public class TokenInfoMapperTest {
@Resource
TokenInfoMapper tokenInfoMapper;
@Test
public void getTokenByTokenInfo() {
TokenInfo tokenInfo = new TokenInfo();
tokenInfo.setFacebook("1421138114902038");
tokenInfoMapper.getTokenByTokenInfo(tokenInfo);
}
@Test
public void getTokenByUserId() {
}
@Test
public void insertTokenInfo() {
}
@Test
public void updateTokenInfoByUserId() {
}
}