11package org .mushare .pluto ;
22
3+ import net .sf .json .JSONObject ;
4+ import org .mushare .pluto .exception .PlutoErrorCode ;
5+ import org .mushare .pluto .exception .PlutoException ;
6+
7+ import java .security .Signature ;
8+ import java .util .Base64 ;
9+
310public class Pluto {
411
512 private PublicKeyManager keyManager ;
@@ -9,35 +16,44 @@ private Pluto() {
916 super ();
1017 }
1118
12- public PublicKeyManager getKeyManager () {
13- return keyManager ;
14- }
15-
16- public void setKeyManager (PublicKeyManager keyManager ) {
17- this .keyManager = keyManager ;
18- }
19-
20- public String getAppId () {
21- return appId ;
22- }
23-
24- public void setAppId (String appId ) {
25- this .appId = appId ;
26- }
27-
2819 private static Pluto shared = new Pluto ();
2920
3021 public static void setup (String server , String appId ) {
31- shared .setKeyManager (new PublicKeyManager (server ));
32- shared .setAppId (appId );
33- }
34-
35- public static void auth (String token ) {
36-
37- }
38-
39- public static void auth (String token , String scope ) {
40-
22+ shared .keyManager = new PublicKeyManager (server );
23+ shared .appId = appId ;
24+ }
25+
26+ public static PlutoUser auth (String token ) throws PlutoException {
27+ if (token == null ) {
28+ throw new PlutoException (PlutoErrorCode .jwtFormatError );
29+ }
30+ String [] parts = token .split ("\\ ." );
31+ if (parts .length != 3 ) {
32+ throw new PlutoException (PlutoErrorCode .jwtFormatError );
33+ }
34+
35+ try {
36+ String header = new String (Base64 .getDecoder ().decode (parts [0 ]), "utf-8" );
37+ JSONObject payload = JSONObject .fromObject (new String (Base64 .getDecoder ().decode (parts [1 ]), "utf-8" ));
38+ // Verify the appId of the jwt token.
39+ if (!payload .getString ("appId" ).equals (shared .appId )) {
40+ ;
41+ }
42+ Long expire = payload .getLong ("expire_time" ) * 1000 ;
43+ if (expire < System .currentTimeMillis ()) {
44+ throw new PlutoException (PlutoErrorCode .expired );
45+ }
46+ Signature signature = Signature .getInstance ("SHA256withRSA" );
47+ signature .initVerify (shared .keyManager .getPublicKey ());
48+ signature .update ((header + payload ).getBytes ());
49+ if (!signature .verify (Base64 .getDecoder ().decode (parts [2 ]))) {
50+ throw new PlutoException (PlutoErrorCode .notVerified );
51+ }
52+ return new PlutoUser (payload );
53+ } catch (Exception e ) {
54+ e .printStackTrace ();
55+ throw new PlutoException (PlutoErrorCode .other );
56+ }
4157 }
4258
4359}
0 commit comments