JWT(JSON Web Token)は、ネットワークアプリケーション環境間でクレームを渡すために実装されたJSONベースのオープン標準(RFC 7519)です。トークンは、特に分散サイトのシングルサインオン(SSO)シナリオに適したコンパクトで安全なように設計されています。 JWTステートメントは、一般に、アイデンティティプロバイダーとサービスプロバイダー間の認証されたユーザーID情報を渡すために使用され、リソースサーバーからのリソースの取得を促進します。また、他のビジネスロジックに必要な追加の宣言情報を追加することもできます。トークンは、認証や暗号化に直接使用することもできます。
通常、APIを直接露出させることは非常に危険です。他に何も話さない場合は、マシンに直接攻撃されている場合は飲むことができます。一般的に、特定の許可レベルをAPIに分割する必要があり、ユーザー認証が実行され、認証結果に基づいて対応するAPIがユーザーに与えられます。現在、さらにいくつかの主流のソリューションがあります。
OAUTHは、ユーザーがユーザー名とパスワードをサードパーティアプリケーションに提供することなく、ユーザーが保存したプライベートリソース(写真、ビデオなど)にサードパーティのアプリケーションにプライベートリソース(写真、ビデオなど)にアクセスできるようにする公開承認基準です。
OAUTHを使用すると、ユーザーはユーザー名とパスワードの代わりにトークンを提供して、特定のサービスプロバイダーに保存するデータにアクセスできます。各トークンは、特定の期間(例:次の2時間以内)以内に特定のリソース(たとえば、特定のアルバムのビデオだけ)にアクセスするために、特定のサードパーティシステム(ビデオ編集Webサイトなど)を許可します。このようにして、OAUTHを使用すると、ユーザーはサードパーティのWebサイトに、すべてのコンテンツではなく、他のサービスプロバイダーに保存する特定の情報にアクセスすることを許可できます。
Cookie認証メカニズムは、認証を要求するためにサーバー上にセッションオブジェクトを作成し、同時にクライアントのブラウザにCookieオブジェクトを作成することです。 Cookieオブジェクトがクライアントに持ち込まれ、サーバー上のセッションオブジェクトと一致して、状態管理を実現します。デフォルトでは、ブラウザを閉じるとCookieが削除されます。ただし、Cookieの期限切れの時間を変更して、一定期間Cookieを有効にすることができます。セッションメソッドに基づく認証は、必然的にサーバー(メモリストレージ)にある程度の圧力をかけ、拡張は容易ではありません(分散セッションを処理する必要があります)、クロスサイトリクエスト偽造攻撃(CSRF)
1。セッションと比較して、サーバーに保存する必要はなく、サーバーメモリのオーバーヘッドを占有しません。
2。ステートレスで高度にスケーラブル:たとえば、サーバークラスターを形成するための3つのマシン(a、b、c)があります。セッションがマシンAに存在する場合、セッションはサーバーの1つにのみ保存できます。この時点では、セッションがBとCに保存されていないため、マシンBとCにアクセスすることはできません。トークンを使用すると、ユーザーの要求の正当性が確認できます。さらにいくつかのマシンを追加しても大丈夫なので、これが意味します。
3。フロントエンドの分離とサポートクロスドメインアクセス。
-JWTの構成
{"ISS": "JWT BUILDER"、 "IAT":1416797419、 "exp":1448333419、 "aud": "www.battcn.com"、 "sub": "" [email protected] "、" revin "、" surname ":" "[email protected]"、 "role":["admin"、 "member"]}JWTは実際には、ヘッダー、ペイロード、署名の3つの部分で構成される文字列です(上の写真の順番でソートされています)
JWTトークンジェネレーター:https://jwt.io/
- 認証をログインします
- 認証のリクエスト
無効なトークン
有効なトークン
利点と短所があります。適用可能かどうかは、テクノロジーやスタイルではなく、明確に考慮する必要があります。
tokenProperties application.ymlリソースを使用したキーマッピング、使いやすい
@configuration@configurationproperties(prefix = "battcn.security.token")public class tokenproperties { / *** {@link com.battcn.security.model.token.token}トークン有効期間* / private integer expirationtime; / ***発行者*/ private文字列発行者。 /*** signature sead cey {@link com.battcn.security.model.token.token}。 */ private string singiblekey; / *** {@link com.battcn.security.model.token.token} reffresse expiration time*/ private integer refreshexptime; //セットを取得...}トークンによって生成されたクラス
@componentPublic Class TokenFactory {プライベート最終TokenPropertiesプロパティ; @autowired public tokenfactory(tokenpropertiesプロパティ){this.properties = properties; } / ** * jjwtを使用してtoken * @param Context * @return * / public AccessToken createaCcesStoken(usercontext context){optional.ofnullable(context.getUsername())。 optional.ofnullable(context.getauthorities())。orelsethrow(() - > new IllegalArgumentException( "ユーザーには特権がありません"));クレームクレーム= jwts.claims()。setSubject(context.getUsername());請求書( "scopes"、context.getauthorities()。stream()。map(object :: toString).collect(tolist())); localDateTime currentTime = localDateTime.now(); string token = jwts.builder().setclaims(くか).setissuer(properties.getissuer()).setissuedat(date.from(currentTime.systemDefault()) .ATZONE(ZONEID.systemDefault())。ToInStant())).SignWith(SignAtureAlgorithM.HS512、Properties.GetSigineKey()).compact();新しいアクセストークン(トークン、クレーム)を返します。 } / ** * refentoken * @param usercontext * @return * / public token createrefreshtoken(usercontext usercontext){if(stringutils.isblank(usercontext.getusername()))){show show out out out out out out out out out out out out uld regalargumentexception( " } localDateTime currentTime = localDateTime.now();クレームクレーム= jwts.claims()。setSubject(usercontext.getusername());請求書( "scopes"、arrays.aslist(scopes.refresh_token.authority())); string token = jwts.builder().setclaims(請求).setissuer(properties.getissuer()).setid(uuid.randomuuid()。toString()).setisseuedat(date.from(currenttime.atzone(ZoneId.systemDefault()) .plusminutes(properties.getRefreshExptime())).atzone(Zoneid.systemDefault())。toinstant())).signwith(signaturealgorithm.hs512、properties.getSimingKey().compact();新しいアクセストークン(トークン、クレーム)を返します。 }}トークンの有効期限、シークレットキーを含む構成ファイルは、単独で拡張できます
battcn:security:token:expiration-time:10#minutes 1440 refresh-exp-time:30#minutes 2880発行者:http://blog.battcn.com
WebSecurityConfigは、Spring Securityの重要な構成です。セキュリティでは、基本的にフィルターを定義することで必要な機能を実装できます。
@configuration@enablewebsecuritypublic class websecurityconfig extends websecurityconfigureradapter {public static final string token_header_param = "x-authorization"; public static final string form_based_login_entry_point = "/api/auth/login"; public static final string token_based_auth_entry_point = "/api/**"; public static final string manage_token_based_auth_entry_point = "/manage/**"; public static final string token_refresh_entry_point = "/api/auth/token"; @autowired private restauthenticationEntryPoint AuthindicationEntryPoint; @AutowiredプライベートAuthenticationsuccesshandler successhandler; @autowired private authenticationfailurehandler faildhandler; @autowired private loginauthenticationProvider loginauthenticationProvider; @autowired private tokenauthenticationProvider tokenauthenticationProvider; @autowired private tokenextractor tokenextractor; @Autowired Private AuthenticationManager AuthenticationManager; protected loginprocessingfilter buildloginprocessingfilter()スロー例外{loginprocessingfilter filter = new loginprocessingfilter(form_based_login_entry_point、successhandler、faildhandler); filter.setAuthenticationManager(this.AuthenticationManager);返品フィルター。 } protected tokenauthenticationProcessingFilter buildtokenauthenticationprocessingfilter()スロー例外{list <string> list = lists.newarrayList(token_based_auth_entry_point、manage_token_based_auth_entry_point); SkippathRequestMatcher Matcher = new SkippathRequestMatcher(list); tokenauthenticationProcessingFilterフィルター= new tokenauthenticationProcessingFilter(faildhandler、tokenextractor、matcher); filter.setAuthenticationManager(this.AuthenticationManager);返品フィルター。 } @bean @Override public AuthenticationManager AuthenticationManagerbean()Throws Exception {return super.authenticationmanagerbean(); } @Override Protected void Configure(AuthenticationManagerBuilder auth){auth.authenticationProvider(loginauthenticationProvider); auth.authenticationprovider(tokenauthenticationProvider); } @Override Protected void configure(httpsecurity http)スロー例外{http .csrf()。disable()// jwtを使用しているため、ここでcsrfをオフにすることができます。 .sessionCreationPolicy(SessionCreationPolicy.Stateless).and().AthorizereQuests().AntMatchers().AntMatchers(Form_based_login_entry_point).permitall()// login endpoint .antmatchers(token_refresh_entry_point).permitall() .AntMatchers(token_based_auth_entry_point).authenticated()// protected api end-point.antmatchers(manage_token_based_auth_entry_point)。 usernamepasswordauthenticationfilter.class).addfilterbefore(buildtokenauthenticationprocessingfilter()、usernamepasswordauthenticationfilter.class); }}JWTコードは単にカプセル化されており、多くのコンテンツが含まれているため、メインフラグメントのみが記事に投稿されています。完全なコードが必要な場合は、次のgitから直接取得できます
この章のコード(battcn-jwt-service):http://xiazai.vevb.com/201801/yuanma/battcn-cloud_jb51.rar
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。