package com.example.loginbysocial.controller; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import com.example.loginbysocial.common.GoogleUtils; import com.example.loginbysocial.entity.GooglePojo; import org.apache.http.client.ClientProtocolException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class LoginSocialController { @Autowired private GoogleUtils googleUtils; @RequestMapping(value = { "/", "/login" }) public String login() { return "login"; } @GetMapping(value = {"/login-google"}) public String loginGoogle(HttpServletRequest request) throws ClientProtocolException, IOException { String code = request.getParameter("code"); if (code == null || code.isEmpty()) { return "redirect:/login?google=error"; } String accessToken = googleUtils.getToken(code); GooglePojo googlePojo = googleUtils.getUserInfo(accessToken); UserDetails userDetail = googleUtils.generateUser(googlePojo); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetail, null, userDetail.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); return "Login by Google:"+googlePojo.getGiven_name()+" "+googlePojo.getFamily_name(); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter