Springboot使用JustAuth实现各种第三方登陆

 更新时间:2023年07月18日 09:01:50   作者:桂亭亭  
本文主要介绍了Springboot使用JustAuth实现各种第三方登陆,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

使用Gitee进行登陆

1.Gitee准备工作

进入gitee,在设置中选择此选项

2. 编码

依赖 

        <!--        第三方登陆justauth 引入-->
        <dependency>
            <groupId>com.xkcoding.justauth</groupId>
            <artifactId>justauth-spring-boot-starter</artifactId>
            <version>1.4.0</version>
        </dependency>
        <!--        对象转json-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>

配置文件

justauth:
  # 是否启用
  enabled: true
  type:
    # 配置各种类型的登陆
    GITEE:
      # 创建的应用的client-id
      client-id: xx
      client-secret: xx
      # 自己写的回调地址
      redirect-uri: http://127.0.0.1:8081/Auth/gitee/callback
  cache:
    type: default   

 接口编写

package com.scm.myblog.controller;
import com.alibaba.fastjson.JSON;
import com.xkcoding.justauth.AuthRequestFactory;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@RestController
@RequestMapping("/Auth")
@Slf4j
public class UserAuthController {
    @Autowired
    private AuthRequestFactory factory;
    @GetMapping("/login/{type}")
    public void toLogin(@PathVariable String type, HttpServletResponse response) throws IOException {
        AuthRequest authRequest = factory.get(type);
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }
    @GetMapping("/{type}/callback")
    public AuthResponse loginBack(@PathVariable String type, AuthCallback callback) {
        AuthRequest authRequest = factory.get(type);
        log.info(JSON.toJSONString(callback));
        AuthResponse response = authRequest.login(callback);
        log.info(JSON.toJSONString(response));
        return response;
    }
}

如果有spring security的话,还要打开这两个接口的访问权限为所有人都可以访问。

没有的可忽略

package com.scm.myblog.config.securityconfig;
public class ApiConfig {
    //无需权限即可访问的Api接口地址
    public static String [] NoAuthApi=new String[] {
            // 第三方登陆
            "/Auth/**",
    };
}
=------------------------------------=
package com.scm.myblog.config.securityconfig;
import com.scm.myblog.common.ExceptionLancer.MyAuthenticationException;
import com.scm.myblog.filter.AuthFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
//开启权限管理系统
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private AuthFilter af;
    @Autowired
    private MyAuthenticationException myAuthenticationException;
    //密码加密解密
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Override
    @Order(1)
    protected void configure(HttpSecurity http) throws Exception {
        //设置无需权限即可访问的
        for (String n: ApiConfig.NoAuthApi){
            http.authorizeRequests().antMatchers(n).permitAll();
        }
        http
                //关闭csrf
                .csrf().disable()
                //不通过session获取security上下文
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //其他的所有接口都需要带token认证
                .anyRequest().authenticated()
                .and().exceptionHandling().authenticationEntryPoint(myAuthenticationException);
        //配置自定义的过滤器在何处执行
        //在UsernamePasswordAuthenticationFilter之前
        http.addFilterBefore(af, UsernamePasswordAuthenticationFilter.class);
        //配置跨域请求
        http.cors();
    }
    //用于进行用户验证
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

启动测试

访问:

http://localhost:8081/Auth/login/gitee

同意授权之后,会自动跳转到这里,这里有我们登陆成功后的信息

3.建立数据表

CREATE TABLE `oauth_platform` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) DEFAULT NULL COMMENT '平台名称',
  `description` varchar(100) DEFAULT NULL,
  `is_delete` int(11) DEFAULT NULL,
  `status` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COMMENT='第三方认证平台信息表'
CREATE TABLE `oauth_user_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `uid` varchar(20) DEFAULT NULL COMMENT 'OAuth用户唯一的id',
  `username` varchar(30) DEFAULT NULL COMMENT 'OAuth用户名',
  `avatar` varchar(120) DEFAULT NULL COMMENT 'OAuth平台的头像url',
  `oauth_token` varchar(50) DEFAULT NULL COMMENT '给的token',
  `oauth_expireIn` int(11) DEFAULT NULL COMMENT 'oauth的过期时间',
  `oauth_platform_id` int(11) DEFAULT NULL COMMENT '平台id',
  `is_delete` int(11) DEFAULT NULL,
  `status` int(11) DEFAULT NULL COMMENT '状态',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户第三方登陆信息表'
 

在代码中将需要的信息插入表格,并把用户的uid存入redis即可登陆成功!

到此这篇关于Springboot使用JustAuth实现各种第三方登陆的文章就介绍到这了,更多相关Springboot JustAuth第三方登陆内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 从入门到精通Spring Boot中WebSocket常用方法

    从入门到精通Spring Boot中WebSocket常用方法

    本文将从入门到精通,详细介绍Spring Boot中WebSocket的常用使用方法,涵盖协议特性、消息收发、点对点通信、认证拦截及注解实现方式,,需要的朋友跟随小编一起看看吧
    2025-08-08
  • Java DelayQueue实现延时任务的示例详解

    Java DelayQueue实现延时任务的示例详解

    DelayQueue是一个无界的BlockingQueue的实现类,用于放置实现了Delayed接口的对象,其中的对象只能在其到期时才能从队列中取走。本文就来利用DelayQueue实现延时任务,感兴趣的可以了解一下
    2022-08-08
  • Java循环创建对象内存溢出的解决方法

    Java循环创建对象内存溢出的解决方法

    在Java中,如果在循环中不当地创建大量对象而不及时释放内存,很容易导致内存溢出(OutOfMemoryError),所以本文给大家介绍了Java循环创建对象内存溢出的解决方法,需要的朋友可以参考下
    2025-01-01
  • SpringBoot @ControllerAdvice 拦截异常并统一处理

    SpringBoot @ControllerAdvice 拦截异常并统一处理

    这篇文章主要介绍了SpringBoot @ControllerAdvice 拦截异常并统一处理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • Java多线程中的ThreadPoolExecutor解读

    Java多线程中的ThreadPoolExecutor解读

    这篇文章主要介绍了Java多线程中的ThreadPoolExecutor解读,线程池中的核心线程数,当提交一个任务时,线程池创建一个新线程执行任务,直到当前线程数等于corePoolSize;如果当前线程数为corePoolSize,继续提交的任务被保存到阻塞队列中,等待被执行,需要的朋友可以参考下
    2023-09-09
  • Java结合Spark的数据清洗场景及对应的实现方法

    Java结合Spark的数据清洗场景及对应的实现方法

    在大数据处理中,数据清洗是非常重要的一步,数据清洗可以帮助我们去除脏数据、处理缺失值、规范数据格式等,以确保数据质量和准确性,在本文中,我们将介绍如何使用Java结合Spark框架来实现数据清洗,需要的朋友可以参考下
    2025-05-05
  • Spring Boot 集成Shiro的多realm实现以及shiro基本入门教程

    Spring Boot 集成Shiro的多realm实现以及shiro基本入门教程

    这篇文章主要介绍了Spring Boot 集成Shiro的多realm实现以及shiro基本入门,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-10-10
  • 基于mybatis batch实现批量提交大量数据

    基于mybatis batch实现批量提交大量数据

    这篇文章主要介绍了基于mybatis batch实现批量提交大量数据,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-05-05
  • Spring Cache 最佳实践总结

    Spring Cache 最佳实践总结

    SpringCache是Spring框架提供的声明式缓存抽象层,通过少量注解即可为应用添加缓存能力,无需侵入业务代码,本文给大家介绍Spring Cache 最佳实践总结,感兴趣的朋友跟随小编一起看看吧
    2026-01-01
  • JAVA控制流程break continue的示例代码

    JAVA控制流程break continue的示例代码

    JAVA流程控制中有相关代码可以终止整个流程的进程,他们就是(break和continue),本文通过实例代码介绍下JAVA控制流程break continue的相关知识,感兴趣的朋友一起看看吧
    2022-03-03

最新评论