OAuth2 Google、Github自定义登录页面

OAuth2 Google、Github自定义登录页面

1.0概要

如何使用Google或Github账号登录web应用 页面模板使用thymeleaf,没有前后端分离。如果有前后端分离的需求,只需要修改Controller代码即可,视频里有说。

代码行间里都有注释说明。

过去,看过我的视频或公众号,基本上都会写了,八九不离十。看得懂代码又懒得写。就在这里下载吧

2.0代码

2.1Maven依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
	<groupId>org.webjars</groupId>
	<artifactId>bootstrap</artifactId>
	<version>4.5.3</version>
</dependency>
<dependency>
	<groupId>org.webjars</groupId>
	<artifactId>jquery</artifactId>
	<version>3.5.1</version>
</dependency>
<dependency>
	<groupId>org.webjars</groupId>
	<artifactId>webjars-locator</artifactId>
	<version>0.40</version>
</dependency>


2.2控制类

LoginController.java

package com.example.googlegithubcustomoauth2;

import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ResolvableType;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
@Log4j2
public class LoginController {

    private final  ClientRegistrationRepository clientRegistrationRepository;

    public LoginController(ClientRegistrationRepository clientRegistrationRepository) {
        this.clientRegistrationRepository = clientRegistrationRepository;
    }

    /**
     * 自定义登录页面
     * @param model
     * @return
     */
    @GetMapping("/oauth2_login")
    public String login(Model model){
        model.addAttribute("urls", getOAuth2AuthenticationUrls());
        return "oauth2_login";
    }



    /**
     * 登录成功调转页面
     * 如果在浏览器中输入 http://localhost:8080/admin 然后登录成功后
     * 系统会自动调转到 /admin 页面,而不是 /loginSuccess
     * @return
     */
    @GetMapping("/loginSuccess")
    public String loginSuccess(){
        return "loginSuccess";
    }

    /**
     * 登录失败调转页面
     * @return
     */
    @GetMapping("/loginFailure")
    public String loginFailure(){
        return "loginFailure";
    }

}

MessageController.java

package com.example.googlegithubcustomoauth2;

import lombok.extern.log4j.Log4j2;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *  Message 控制器
 */
@RestController
@Log4j2
public class MessageController {

    @GetMapping("/")
    public String hello(){
        return "Hello Google Github.";
    }

    @GetMapping("/guest")
    public String guest(){
        return "Hello Guest.";
    }

    /**
     * 获取Google或Github返回的用户信息
     * @param principal
     * @return
     */
    @GetMapping("/admin")
    public OAuth2User admin(@AuthenticationPrincipal OAuth2User principal){
        return principal;
    }

}

2.3配置类

SecurityConfig.java

package com.example.googlegithubcustomoauth2;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

/**
 * Security配置信息
 */
@Configuration
public class SecurityConfig  extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .antMatcher("/**").authorizeRequests()
                //设置访问资源文件权限
                .antMatchers("/webjars/**").permitAll()
                //设置指定url访问权限
                .antMatchers("/", "/guest","/oauth2_login").permitAll()
                .anyRequest().authenticated()
                .and()
                //明确oath2登录
                .oauth2Login()
                //登录页面
                .loginPage("/oauth2_login")
                //登录成功后调转页面
                //如果在浏览器中输入 http://localhost:8080/admin 然后登录成功后,系统会自动调转到 /admin 页面,而不是 /loginSuccess
                //如果输入http://localhost:8080/oauth2_login,登录成功后,才会调转到/loginSuccess
                .defaultSuccessUrl("/loginSuccess")
                //登录失败调转页面
                .failureUrl("/loginFailure");
    }

}

WebConfig.java

package com.example.googlegithubcustomoauth2;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * MVC配置信息
 */
@Configuration
class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler("/webjars/**")//添加webjar资源文件bootstrap、jquery等...
                .addResourceLocations("/webjars/")//资源文件开始路径“/webjars/”
                .resourceChain(false);//是否缓存资源文件
    }
}

5.0运行

http://localhost:8080/oauth2_login 或 http://localhost:8080/admin

本文使用 mdnice 排版

原文地址:https://www.cnblogs.com/JavaWeiBianCheng/p/13902774.html