Spring Security Oauth2自定义登录和退出

登录:

public class MyLoginAuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    /**
	 * 配置日志
	 */
	private final static Logger logger = LoggerFactory.getLogger(MyLoginAuthSuccessHandler.class);

	@Autowired
	private ClientDetailsService jdbcClientDetailsService;

	@Autowired
	private DefaultTokenServices defaultTokenServices;

	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	private TokenStore authTokenStore;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private RedisTemplate<String, TokenEntity> tokenEntityRedisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        JSONObject result = createToken(request,response,authentication);
        if(result==null){
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(CommonResponse.successResponse("同时在线人数过多!")));
            return;
        }
        //获取openId返回
        String code = request.getParameter("code");
        if(StringUtils.isNotBlank(code)) {
            result.put("openId", redisTemplate.opsForValue().get(code));
        }
        result.put("userInfo",((BaseUserDetail)authentication.getPrincipal()).getBaseUser());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(result));
        logger.info("登录成功");
    }

    /**
     * 创建token
     * @param request
     * @param response
     * @param authentication
     */
    private JSONObject createToken(HttpServletRequest request, HttpServletResponse response, Authentication authentication){
        String clientId = request.getParameter("client_id");
        String clientSecret = request.getParameter("client_secret");

        ClientDetails clientDetails = jdbcClientDetailsService.loadClientByClientId(clientId);
        //密码工具
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (null == clientDetails) {
            throw new UnapprovedClientAuthenticationException("clientId不存在" + clientId);
        }
        //比较secret是否相等
        else if (!passwordEncoder.matches(clientSecret, clientDetails.getClientSecret())) {
            throw new UnapprovedClientAuthenticationException("clientSecret不匹配" + clientId);
        }

        TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_MAP, clientId, clientDetails.getScope(),
                "password");

        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);

        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        defaultTokenServices.setTokenStore(authTokenStore);
        logger.info("==="+authentication.getPrincipal());
        defaultTokenServices.setAccessTokenValiditySeconds(Constant.AUTH_EXP_TIME);
        defaultTokenServices.setRefreshTokenValiditySeconds(Constant.REFRESH_AUTH_EXP_TIME);

        OAuth2AccessToken token = defaultTokenServices.createAccessToken(oAuth2Authentication);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONObject result = new JSONObject();
        result.put("access_token", token.getValue());
        result.put("token_Expiration", sdf.format(token.getExpiration()));
        logger.debug("token:"+token.getValue());
        //判断token的和方法性
        if(!TokenUtil.pushToken(((BaseUserDetail)authentication.getPrincipal()).getBaseUser().getTelephone(),tokenEntityRedisTemplate,token.getValue(),token.getExpiration())){
            return null;
        }
        return result;
    }
}

退出:

/**
 * 退出成功处理逻辑
 */
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(CommonResponse.successResponse("退出成功")));
    }
}
发布了149 篇原创文章 · 获赞 36 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/zhuwei_clark/article/details/103979919