33import com .alibaba .fastjson .JSON ;
44import com .alibaba .fastjson .JSONObject ;
55
6+ import com .alibaba .fastjson .JSONPObject ;
7+ import lombok .extern .slf4j .Slf4j ;
8+ import org .apache .commons .lang .StringUtils ;
69import org .joychou .security .SecurityUtil ;
710import org .joychou .util .LoginUtils ;
11+ import org .springframework .beans .factory .annotation .Autowired ;
812import org .springframework .http .MediaType ;
13+ import org .springframework .security .web .csrf .CookieCsrfTokenRepository ;
914import org .springframework .security .web .csrf .CsrfToken ;
1015import org .springframework .web .bind .annotation .*;
1116import org .springframework .web .servlet .ModelAndView ;
1419import org .joychou .util .WebUtils ;
1520
1621import javax .servlet .http .HttpServletRequest ;
22+ import javax .servlet .http .HttpServletResponse ;
1723import java .security .Principal ;
1824
1925
2228 * https://github.com/JoyChou93/java-sec-code/wiki/JSONP
2329 */
2430
31+ @ Slf4j
2532@ RestController
2633@ RequestMapping ("/jsonp" )
2734public class Jsonp {
2835
2936 private String callback = WebConfig .getBusinessCallback ();
3037
38+ @ Autowired
39+ CookieCsrfTokenRepository cookieCsrfTokenRepository ;
3140 /**
3241 * Set the response content-type to application/javascript.
3342 * <p>
@@ -57,7 +66,7 @@ public String emptyReferer(HttpServletRequest request) {
5766 }
5867
5968 /**
60- * Adding callback or cback on parameter can automatically return jsonp data.
69+ * Adding callback or _callback on parameter can automatically return jsonp data.
6170 * http://localhost:8080/jsonp/object2jsonp?callback=test
6271 * http://localhost:8080/jsonp/object2jsonp?_callback=test
6372 *
@@ -101,11 +110,33 @@ public String safecode(HttpServletRequest request) {
101110 return WebUtils .json2Jsonp (callback , LoginUtils .getUserInfo2JsonStr (request ));
102111 }
103112
104-
113+ /**
114+ * http://localhost:8080/jsonp/getToken?fastjsonpCallback=aa
115+ *
116+ * object to jsonp
117+ */
105118 @ GetMapping ("/getToken" )
106- public CsrfToken getCsrfToken (CsrfToken token ) {
119+ public CsrfToken getCsrfToken1 (CsrfToken token ) {
107120 return token ;
108121 }
109122
123+ /**
124+ * http://localhost:8080/jsonp/fastjsonp/getToken?fastjsonpCallback=aa
125+ *
126+ * fastjsonp to jsonp
127+ */
128+ @ GetMapping (value = "/fastjsonp/getToken" , produces = "application/javascript" )
129+ public String getCsrfToken2 (HttpServletRequest request ) {
130+ CsrfToken csrfToken = cookieCsrfTokenRepository .loadToken (request ); // get csrf token
131+
132+ String callback = request .getParameter ("fastjsonpCallback" );
133+ if (StringUtils .isNotBlank (callback )) {
134+ JSONPObject jsonpObj = new JSONPObject (callback );
135+ jsonpObj .addParameter (csrfToken );
136+ return jsonpObj .toString ();
137+ } else {
138+ return csrfToken .toString ();
139+ }
140+ }
110141
111142}
0 commit comments