Code ví dụ Spring MVC đăng nhập bằng google/gmail.
(Xem lại: Code ví dụ JSP Servlet login bằng Google (Gmail/Google+))
(Xem lại: Code ví dụ Spring Boot Security login bằng Google (Gmail))
Các công nghệ sử dụng:
- Spring 5.0.2.RELEASE
- Spring Security 5.0.2.RELEASE
- Maven
- Tomcat
- JDK 1.8
- Eclipse + Spring Tool Suite
Tạo ứng dung/project trên google API
(Xem lại: Tạo ứng dụng google+ để đăng nhập thay tài khoản)
Ở đây mình tạo ứng dụng “stackajva-demo-login” với:
- Client ID = 127492257645-9j4f1o189sq15fmg41dr4bmc8u3lv53s.apps.googleusercontent.com
- Client Secret = VN2CMuNb92bRrasiZ0MnXfMU
Tạo Maven Project
Thư viện sử dụng:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>stackjava.com</groupId> <artifactId>SpringMvcGoogle</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <spring.version>5.0.2.RELEASE</spring.version> <spring.security.version>5.0.2.RELEASE</spring.security.version> <jstl.version>1.2</jstl.version> </properties> <dependencies> <!-- Spring MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring Security --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${spring.security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${spring.security.version}</version> </dependency> <!-- JSP/Servlet --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <!-- jstl for jsp page --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <!-- org.apache.httpcomponents --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>fluent-hc</artifactId> <version>4.5.5</version> </dependency> <!-- Jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.3</version> </dependency> </dependencies> </project>
Mình sử dụng thêm thư viện httpcomponents để gửi request bên trong code Java và jackson để xử lý dữ liệu JSON
File cấu hình Spring MVC
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <context:component-scan base-package="stackjava.com.springmvcgoogle" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/views/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
File cấu hình Spring Security
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <http auto-config="true"> <intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" /> <intercept-url pattern="/user**" access="hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')" /> <access-denied-handler error-page="/403"/> <form-login login-page="/login" login-processing-url="/j_spring_security_login" default-target-url="/user" authentication-failure-url="/login?message=error" username-parameter="username" password-parameter="password" /> <logout logout-url="/j_spring_security_logout" logout-success-url="/login?message=logout" delete-cookies="JSESSIONID" /> </http> <authentication-manager> <authentication-provider> <user-service> <user name="kai" password="{noop}123456" authorities="ROLE_ADMIN" /> <user name="sena" password="{noop}123456" authorities="ROLE_USER" /> </user-service> </authentication-provider> </authentication-manager> </beans:beans>
File controller
package stackjava.com.springmvcgoogle.controller; import java.io.IOException; import javax.servlet.http.HttpServletRequest; 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.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import stackjava.com.springmvcgoogle.common.GooglePojo; import stackjava.com.springmvcgoogle.common.GoogleUtils; @Controller public class BaseController { @Autowired private GoogleUtils googleUtils; @RequestMapping(value = { "/", "/login" }) public String login(@RequestParam(required = false) String message, final Model model) { if (message != null && !message.isEmpty()) { if (message.equals("logout")) { model.addAttribute("message", "Logout!"); } if (message.equals("error")) { model.addAttribute("message", "Login Failed!"); } if (message.equals("google_error")) { model.addAttribute("message", "Login by Facebook Failed!"); } } return "login"; } @RequestMapping("/login-google") public String loginGoogle(HttpServletRequest request) throws ClientProtocolException, IOException { String code = request.getParameter("code"); if (code == null || code.isEmpty()) { return "redirect:/login?message=google_error"; } String accessToken = googleUtils.getToken(code); GooglePojo googlePojo = googleUtils.getUserInfo(accessToken); UserDetails userDetail = googleUtils.buildUser(googlePojo); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetail, null, userDetail.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); return "redirect:/user"; } @RequestMapping("/user") public String user() { return "user"; } @RequestMapping("/admin") public String admin() { return "admin"; } @RequestMapping("/403") public String accessDenied() { return "403"; } }
Method loginGoogle xử lý kết quả trả về từ google
- Lấy code mà google gửi về sau đó đổi code sang access token
- Sử dụng access token lấy thông tin user (có thể thực hiện lưu lại thông tin vào database để quản lý)
- Chuyển thông tin user sang đối tượng UserDetails để spring security quản lý
- Sử dụng đối tượng UserDetails trên giống như thông tin authentication (tương đương với đăng nhập bằng username/password)
File GoogleUtils.java
Thực hiện gửi request tới google (lấy access_token, lấy thông tin tài khoản)
package stackjava.com.springmvcgoogle.common; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.fluent.Form; import org.apache.http.client.fluent.Request; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @Component public class GoogleUtils { public static String GOOGLE_CLIENT_ID = "127492257645-9j4f1o189sq15fmg41dr4bmc8u3lv53s.apps.googleusercontent.com"; public static String GOOGLE_CLIENT_SECRET = "VN2CMuNb92bRrasiZ0MnXfMU"; public static String GOOGLE_REDIRECT_URI = "http://localhost:8080/SpringMvcGoogle/login-google"; public static String GOOGLE_LINK_GET_TOKEN = "https://accounts.google.com/o/oauth2/token"; public static String GOOGLE_LINK_GET_USER_INFO = "https://www.googleapis.com/oauth2/v1/userinfo?access_token="; public static String GOOGLE_GRANT_TYPE = "authorization_code"; public String getToken(final String code) throws ClientProtocolException, IOException { String response = Request.Post(GOOGLE_LINK_GET_TOKEN) .bodyForm(Form.form().add("client_id", GOOGLE_CLIENT_ID) .add("client_secret", GOOGLE_CLIENT_SECRET) .add("redirect_uri", GOOGLE_REDIRECT_URI).add("code", code) .add("grant_type", GOOGLE_GRANT_TYPE).build()) .execute().returnContent().asString(); ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(response).get("access_token"); return node.textValue(); } public GooglePojo getUserInfo(final String accessToken) throws ClientProtocolException, IOException { String link = GOOGLE_LINK_GET_USER_INFO + accessToken; String response = Request.Get(link).execute().returnContent().asString(); ObjectMapper mapper = new ObjectMapper(); GooglePojo googlePojo = mapper.readValue(response, GooglePojo.class); System.out.println(googlePojo); return googlePojo; } public UserDetails buildUser(GooglePojo googlePojo) { boolean enabled = true; boolean accountNonExpired = true; boolean credentialsNonExpired = true; boolean accountNonLocked = true; List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new SimpleGrantedAuthority("ROLE_USER")); UserDetails userDetail = new User(googlePojo.getEmail(), "", enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); return userDetail; } }
File GooglePojo.java
Dùng để chứa các thông tin tài khoản (email, name…) gửi về từ google.
package stackjava.com.sbgoogle.common; public class GooglePojo { private String id; private String email; private boolean verified_email; private String name; private String given_name; private String family_name; private String link; private String picture; // getter-setter }
Các file view:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <head> <title>login</title> </head> <body> <h1>Spring MVC Security - Login with Google</h1> <h2>${message}</h2> <a href="https://accounts.google.com/o/oauth2/auth?scope=email&redirect_uri=http://localhost:8080/SpringMvcGoogle/login-google&response_type=code &client_id=127492257645-9j4f1o189sq15fmg41dr4bmc8u3lv53s.apps.googleusercontent.com&approval_prompt=force">Login With Google</a> <form name='loginForm' action="<c:url value='j_spring_security_login' />" method='POST'> <table> <tr> <td>User:</td> <td><input type='text' name='username'></td> </tr> <tr> <td>Password:</td> <td><input type='password' name='password' /></td> </tr> <tr> <td colspan='2'><input name="submit" type="submit" value="login" /></td> </tr> </table> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> </form> </body> </html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <head> <title>Admin Page</title> </head> <body> <h1>Admin Page</h1> <h2>Welcome: ${pageContext.request.userPrincipal.name}</h2> <a href="<c:url value="/user" />">User Page</a> <br/><br/> <form action="<c:url value="/j_spring_security_logout" />" method="post"> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> <input type="submit" value="Logout" /> </form> </body> </html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <head> <title>User Page</title> </head> <body> <h1>User Page</h1> <h2>Welcome: ${pageContext.request.userPrincipal.name}</h2> <a href="<c:url value="/admin" />">Admin Page</a> <br/><br/> <form action="<c:url value="/j_spring_security_logout" />" method="post"> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> <input type="submit" value="Logout" /> </form> </body> </html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <head> <title>403</title> </head> <body> <h1>403</h1> <span>Hi: ${pageContext.request.userPrincipal.name} you do not have permission to access this page</span> <a href="<c:url value="/user" />">User Page</a> <br/><br/> <form action="<c:url value="/j_spring_security_logout" />" method="post"> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> <input type="submit" value="Logout" /> </form> </body> </html>
Demo:
Đăng nhập bình thường bằng tài khoản kai/123456
Đăng nhập bằng tài khoản google (gmail)
Chọn tài khoản gmail sẽ dùng để đăng nhập.
Tài khoản đăng nhập qua gmail không có quyền truy cập trang /admin vì chỉ có role user
Code ví dụ Spring MVC đăng nhập bằng google/gmail stackjava.com
Okay, Done!
Download code ví dụ trên tại đây.
(Xem thêm: Code ví dụ Spring MVC Security, login bằng Facebook)
References: