Hướng dẫn làm chức năng đăng nhập với spring mvc

Code ví dụ Spring MVC Security, login bằng Facebook

(Xem thêm: Code ví dụ Spring Boot Security login bằng Facebook)

(Xem lại bài Code ví dụ JSP Servlet login bằng Facebook (Java Web) để hiểu nguyên lý đăng nhập bằng tài khoản facebook)

Ở bài này mình cũng sẽ không dùng Facebook SDK hay Spring Social mà sẽ tạo thủ công quy trình đăng nhập ứng dụng bằng facebook để mọi người hiểu rõ nguyên lý và luồng chạy. Ở bài sau mình sẽ hướng dẫn sử dụng Spring Social để đăng nhập Facebook)

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

Cấu hình https cho tomcat

Xem lại: cấu hình https cho tomcat

Tạo ứng dụng trên facebook

Ở đây mình tạo ứng dụng trên facebook để thực hiện chức năng login với app id = ‘359123991240252’ và key = ‘d07e182d8495df6930665d6c39fbe8ac’

Hướng dẫn làm chức năng đăng nhập với spring mvc

(Xem lại: Tạo ứng dụng facebook để đăng nhập thay tài khoản)

Tạo Maven Project

Hướng dẫn làm chức năng đăng nhập với spring mvc

Thư viện sử dụng:

4.0.0 stackjava.com AccessFacebook 0.0.1-SNAPSHOT war

5.0.2.RELEASE  
5.0.2.RELEASE  
1.2
  
  
  org.springframework  
  spring-webmvc  
  ${spring.version}  

  
  
  org.springframework.security  
  spring-security-web  
  ${spring.security.version}  
  
  
  org.springframework.security  
  spring-security-config  
  ${spring.security.version}  

  
  
  javax.servlet.jsp  
  jsp-api  
  2.2  
  provided  
  
  
  javax.servlet  
  servlet-api  
  2.5  
  provided  

  
  
  jstl  
  jstl  
  ${jstl.version}  

  
  
  org.apache.httpcomponents  
  httpcore  
  4.4.9  
  
  
  org.apache.httpcomponents  
  httpclient  
  4.5.5  
  
  
  org.apache.httpcomponents  
  fluent-hc  
  4.5.5  

  
  
  com.restfb  
  restfb  
  2.3.0  

  
  
  com.fasterxml.jackson.core  
  jackson-databind  
  2.9.3  
  
  
  com.fasterxml.jackson.core  
  jackson-core  
  2.9.3  
  
  
  com.fasterxml.jackson.core  
  jackson-annotations  
  2.9.3  

Mình sử dụng thêm thư viện httpcomponents và restfb để gửi request bên trong controller tới facebook. Thư viện Jackson để xử lý dữ liệu JSON

File cấu hình Spring MVC

class="org.springframework.web.servlet.view.InternalResourceViewResolver"> /WEB-INF/views/jsp/ .jsp File cấu hình Spring Security

  
  
  
  
  
  
    
      
      
    
  
File controller:

package stackjava.com.accessfacebook.controller; import java.io.IOException; import javax.servlet.http.HttpServletRequest; 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.accessfacebook.utils.RestFB; @Controller public class BaseController { @Autowired private RestFB restFB; @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("facebook_denied")) {  
    model.addAttribute("message", "Login by Facebook Failed!");  
  }  
}  
return "login";  
} @RequestMapping("/login-facebook") public String loginFacebook(HttpServletRequest request) {
String code = request.getParameter("code");  
String accessToken = "";  
try {  
  accessToken = restFB.getToken(code);  
} catch (IOException e) {  
  return "login?facebook=error";  
}
com.restfb.types.User user = restFB.getUserInfo(accessToken);  
UserDetails userDetail = restFB.buildUser(user);  
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 loginFacebook xử lý kết quả trả về từ facebook

  • Nếu user không đồng ý đăng nhập bằng facebook thì sẽ quay ngược trở về trang login
  • Nếu user đồng ý đăng nhập bằng facebook thì:
    • Lấy code mà facebook 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 truy vấn, gửi request tới facebook:

package stackjava.com.accessfacebook.utils; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.http.client.ClientProtocolException; 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; import com.restfb.DefaultFacebookClient; import com.restfb.FacebookClient; import com.restfb.Version; @Component public class RestFB { public static String FACEBOOK_APP_ID = "359123991240252"; public static String FACEBOOK_APP_SECRET = "d07e182d8495df6930665d6c39fbe8ac"; public static String FACEBOOK_REDIRECT_URL = "https://localhost:8443/AccessFacebook/login-facebook"; public static String FACEBOOK_LINK_GET_TOKEN = "https://graph.facebook.com/oauth/access_token?client_id=%s&client_secret=%s&redirect_uri=%s&code=%s"; public String getToken(final String code) throws ClientProtocolException, IOException {

String link = String.format(FACEBOOK_LINK_GET_TOKEN, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET, FACEBOOK_REDIRECT_URL, code);  
String response = Request.Get(link).execute().returnContent().asString();  
 ObjectMapper mapper = new ObjectMapper();  
JsonNode node = mapper.readTree(response).get("access_token");  
return node.textValue();  
} public com.restfb.types.User getUserInfo(final String accessToken) {
FacebookClient facebookClient = new DefaultFacebookClient(accessToken, FACEBOOK_APP_SECRET, Version.LATEST);  
return facebookClient.fetchObject("me", com.restfb.types.User.class);  
} public UserDetails buildUser(com.restfb.types.User user) {
boolean enabled = true;  
boolean accountNonExpired = true;  
boolean credentialsNonExpired = true;  
boolean accountNonLocked = true;  
List authorities = new ArrayList();  
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));  
UserDetails userDetail = new User(user.getId(), "", enabled, accountNonExpired, credentialsNonExpired,  
    accountNonLocked, authorities);  
return userDetail;  
} } Nếu không dùng thư viện RestFB thì bạn có thể dùng URL sau để lấy thông tin của user: https://graph.facebook.com/me?access_token=... thông tin trả về sẽ gồm id và name.

(Bạn cũng có thể lấy thêm nhiều trường khác như email, comment, image… nhưng cần phải có thêm permission, ở đây mình chỉ thực hiện đăng nhập nên chỉ cần permission để lấy public profile)

Các file views:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> login

Spring MVC-Security Login Form

${message}

Login Facebook
User:
Password:

Đường link

https://www.facebook.com/dialog/oauth?client_id=180439422588509&redirect_uri=https://localhost:8443/login-facebookdùng để gọi hộp thoại Đăng nhập và cài đặt URL chuyển hướng.

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> User Page

User Page

Welcome: ${pageContext.request.userPrincipal.name}

">Admin Page

" method="post">
  
  
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> Admin Page

Admin Page

Welcome: ${pageContext.request.userPrincipal.name}

">User Page

" method="post">
  
  
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 403

403

Hi: ${pageContext.request.userPrincipal.name} you do not have permission to access this page ">User Page

" method="post">
  
  

Demo:

Đăng nhập bình thường bằng tài khoản kai/123456

Hướng dẫn làm chức năng đăng nhập với spring mvc

Hướng dẫn làm chức năng đăng nhập với spring mvc

Hướng dẫn làm chức năng đăng nhập với spring mvc

Đăng nhập bằng tài khoản facebook

Hướng dẫn làm chức năng đăng nhập với spring mvc

Trường hợp không đồng ý đăng nhập bằng facebook

Hướng dẫn làm chức năng đăng nhập với spring mvc

Hướng dẫn làm chức năng đăng nhập với spring mvc

Trường hợp cho phép đăng nhập bằng facebook (sau khi cho phép, lần sau đăng nhập tiếp facebook sẽ không hỏi lại nữa)