0


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即可登陆成功!

4. 自由发挥


本文转载自: https://blog.csdn.net/qq_53679247/article/details/130316315
版权归原作者 桂亭亭 所有, 如有侵权,请联系我们删除。

“Springboot使用JustAuth完成各种第三方登陆”的评论:

还没有评论