1 package org.oxerr.spring.security.wechat.web.authentication;
2
3 import java.io.IOException;
4
5 import javax.servlet.FilterChain;
6 import javax.servlet.ServletException;
7 import javax.servlet.ServletRequest;
8 import javax.servlet.ServletResponse;
9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11
12 import org.oxerr.spring.security.wechat.authentication.WeChatAuthenticationToken;
13 import org.oxerr.spring.security.wechat.core.AuthDenyException;
14 import org.springframework.security.core.Authentication;
15 import org.springframework.security.core.AuthenticationException;
16 import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
17 import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
18 import org.springframework.util.Assert;
19
20 public class WeChatAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
21
22 private final String AUTH_DENY_ATTRIBUTE_NAME = this.getClass().getName() + ".AuthDeny";
23 private final WeChatService weChatService;
24
25 public WeChatAuthenticationFilter(WeChatService weChatService) {
26 super(new AntPathRequestMatcher("/login/wechat", "GET"));
27 this.weChatService = weChatService;
28 }
29
30
31
32
33 @Override
34 public void doFilter(ServletRequest req, ServletResponse res,
35 FilterChain chain) throws IOException, ServletException {
36 HttpServletRequest request = (HttpServletRequest) req;
37 HttpServletResponse response = (HttpServletResponse) res;
38
39 if (request.getSession().getAttribute(AUTH_DENY_ATTRIBUTE_NAME) == null
40 && isInWeChat(request)) {
41 super.doFilter(request, response, chain);
42 } else {
43 chain.doFilter(request, response);
44 }
45 }
46
47
48
49
50 @Override
51 public Authentication attemptAuthentication(HttpServletRequest request,
52 HttpServletResponse response)
53 throws AuthenticationException, IOException, ServletException {
54 final Authentication authentication;
55
56 final String code = request.getParameter("code");
57
58 if (code == null) {
59 this.weChatService.redirectToAuthorize(request, response);
60 authentication = null;
61 } else {
62 final WeChatAuthenticationToken authenticationToken = new WeChatAuthenticationToken(code);
63
64
65 try {
66 authentication = this.getAuthenticationManager().authenticate(authenticationToken);
67 } catch (AuthDenyException e) {
68 request.getSession().setAttribute(AUTH_DENY_ATTRIBUTE_NAME, e);
69 throw e;
70 }
71 }
72
73 return authentication;
74 }
75
76
77
78
79 @Override
80 public void afterPropertiesSet() {
81 super.afterPropertiesSet();
82
83 Assert.notNull(this.weChatService, "A weChatService must be set.");
84 }
85
86 protected boolean isInWeChat(HttpServletRequest request) throws IOException {
87 final String userAgent = request.getHeader("user-agent");
88 return userAgent != null && userAgent.contains("MicroMessenger/");
89 }
90
91 }