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第三方登陆内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java 键盘输入的多种实现方法

    java 键盘输入的多种实现方法

    java不像C中拥有scanf这样功能强大的函数,大多是通过定义输入输出流对象。常用的类有BufferedReader,Scanner。
    2013-03-03
  • 详解MyBatis配置typeAliases的方法

    详解MyBatis配置typeAliases的方法

    这篇文章主要介绍了详解MyBatis配置typeAliases的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-10-10
  • SpringBoot参数校验之@Valid的使用详解

    SpringBoot参数校验之@Valid的使用详解

    这篇文章主要通过示例为大家详细介绍一下介绍了SpringBoot参数校验中@Valid的使用方法,文中的示例代码讲解详细,需要的可以参考一下
    2022-06-06
  • 对ArrayList和LinkedList底层实现原理详解

    对ArrayList和LinkedList底层实现原理详解

    今天小编就为大家分享一篇对ArrayList和LinkedList底层实现原理详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-10-10
  • Java面试必备之AQS阻塞队列和条件队列

    Java面试必备之AQS阻塞队列和条件队列

    我们大概知道AQS就是一个框架,把很多功能都给实现了(比如入队规则,唤醒节点中的线程等),我们如果要使用的话只需要实现其中的一些方法(比如tryAcquire等)就行了!这次主要说说AQS中阻塞队列的的入队规则还有条件变量,需要的朋友可以参考下
    2021-06-06
  • Java中如何使用Gson将对象转换为JSON字符串

    Java中如何使用Gson将对象转换为JSON字符串

    这篇文章主要给大家介绍了关于Java中如何使用Gson将对象转换为JSON字符串的相关资料,Gson是Google的一个开源项目,可以将Java对象转换成JSON,也可能将JSON转换成Java对象,需要的朋友可以参考下
    2023-11-11
  • springboot整合mqtt客户端示例分享

    springboot整合mqtt客户端示例分享

    这篇文章主要介绍了springboot整合mqtt客户端示例分享的相关资料,需要的朋友可以参考下
    2023-07-07
  • 建议你使用LocalDateTime而不是Date哦

    建议你使用LocalDateTime而不是Date哦

    这篇文章主要介绍了建议你使用LocalDateTime而不是Date,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-10-10
  • Java基础之让你彻底搞懂代理模式

    Java基础之让你彻底搞懂代理模式

    这篇文章主要介绍了Java基础之让你彻底搞懂代理模式,文中有非常详细的代码示例,对正在学习java基础的小伙伴们有非常好的帮助,需要的朋友可以参考下
    2021-04-04
  • JAVA数据结构之汉诺塔代码实例

    JAVA数据结构之汉诺塔代码实例

    这篇文章主要介绍了JAVA数据结构之汉诺塔,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-04-04

最新评论