1
0
mirror of synced 2026-05-22 22:53:16 +00:00

Compare commits

...

50 Commits

Author SHA1 Message Date
shengzhang 2c6e656834 v1.8.0更新 2021-01-02 04:00:49 +08:00
shengzhang 5ec35cce28 UPDATE LICENSE 2021-01-01 03:22:38 +08:00
shengzhang 453d83cea4 update license 2021-01-01 03:22:06 +08:00
省长 0091fbad09 update README.md. 2020-12-28 22:17:49 +08:00
省长 13760ccf4d update README.md.
优化readme
2020-12-28 22:14:47 +08:00
shengzhang d9e2d98390 调整示例 2020-12-28 02:05:08 +08:00
shengzhang 47140cea07 新增角色验证与权限验证完全分离 2020-12-28 02:00:32 +08:00
shengzhang 43308bf593 权限码限定必须为String类型 2020-12-28 01:14:34 +08:00
shengzhang d3792ad286 在无token时自动创建会话,完美兼容token-session会话模型! 2020-12-28 00:40:35 +08:00
shengzhang 930c28df6d 增加配置,指定在获取token专属session时是否必须登录 2020-12-27 23:45:47 +08:00
shengzhang a59ee9408b 添加token专有session 2020-12-27 22:47:00 +08:00
shengzhang 20f6bd7b3d dao层默认实现增加定时清理过期数据功能 2020-12-27 18:18:08 +08:00
shengzhang 67abf576f0 优化文档配色,更舒服的代码展示 2020-12-27 12:04:14 +08:00
shengzhang 72252ab6b4 简写项目目录结构 2020-12-27 00:12:48 +08:00
shengzhang 60e2afe76f 提供sa-token集成redis的starter方案 2020-12-26 23:55:46 +08:00
省长 62bd2febd0 !4 update sa-token-doc/doc/use/token-style.md.
Merge pull request !4 from 离你多远/N/A
2020-12-26 21:06:28 +08:00
离你多远 434049c4a3 update sa-token-doc/doc/use/token-style.md. 2020-12-26 21:04:33 +08:00
shengzhang 6277a1841b 完善注释 2020-12-26 20:54:15 +08:00
shengzhang 97ad4a783b 修改项目文件夹名字 2020-12-26 10:43:23 +08:00
省长 a503828e23 !3 update sa-token-doc/doc/use/token-style.md.
Merge pull request !3 from RockMan/N/A
2020-12-25 12:15:08 +08:00
RockMan 52abba6a98 update sa-token-doc/doc/use/token-style.md. 2020-12-25 12:11:28 +08:00
shengzhang ebe6b0917b 优化readme 2020-12-25 01:20:21 +08:00
shengzhang 4b1370e603 增加v1.6文档连接 2020-12-25 00:30:24 +08:00
shengzhang 9ddc1eb7d0 完善示例 2020-12-25 00:21:02 +08:00
shengzhang 34f1e1f2db 完善v1.7.0文档 2020-12-25 00:16:12 +08:00
shengzhang d9836f00ca v1.7.0 版本更新 2020-12-24 22:51:57 +08:00
shengzhang 5c684ac7f1 v1.7.0新特性,token临时过期时间设定 2020-12-24 18:11:12 +08:00
shengzhang ded6da5554 v1.7.0 新特性,在Cookie模式下timeout过期时间有效 2020-12-23 18:49:22 +08:00
shengzhang 149b2e54c9 ADD LICENSE 2020-12-22 01:22:32 +08:00
shengzhang aad953c6eb 重构为maven多模块架构... 2020-12-22 01:14:17 +08:00
shengzhang 4f22be308e 重构为maven多模块架构 2020-12-22 01:11:28 +08:00
shengzhang 4962742988 v1.6.0 版本更新... 2020-12-18 00:57:54 +08:00
shengzhang 1d9ed55438 v1.6.0 版本更新 2020-12-18 00:42:38 +08:00
shengzhang 4db058cdf0 v1.6.0 版本更新 2020-12-18 00:39:14 +08:00
shengzhang d776501c3d v1.6.0新特性:提供花式token生成方案.. 2020-12-17 02:41:30 +08:00
shengzhang 235e9afcd3 v1.6.0新特性:提供花式token生成方案 2020-12-17 02:19:56 +08:00
shengzhang 983af6691e 修改readme.md 2020-12-17 02:04:34 +08:00
shengzhang 6e10bce575 v1.5版本 升级 2020-12-16 02:10:51 +08:00
省长 19e81b257e !2 update README.md.
Merge pull request !2 from zhangjiaxiaozhuo/N/A
2020-12-15 21:10:31 +08:00
zhangjiaxiaozhuo a3fa535ddf update README.md. 2020-12-15 20:45:42 +08:00
shengzhang 4ec378e1de 更改首页提示语 2020-12-15 01:45:20 +08:00
shengzhang 9aee951dd6 首页闪光背景 2020-12-15 01:42:34 +08:00
shengzhang 60bd8dbce9 readme.me logo更换地址... 2020-12-15 01:24:38 +08:00
shengzhang 60a38c81b2 优化readme.md 2020-12-15 01:18:55 +08:00
shengzhang 8f14cdc097 优化readme.md ... 2020-12-15 01:13:04 +08:00
shengzhang 1a72945d60 优化readme.md 2020-12-15 01:06:12 +08:00
shengzhang ac9fdd5c76 优化文档... 2020-12-14 23:01:15 +08:00
shengzhang ee59f1a2a2 细化未登录异常类型、Cookie操作改为接口代理模式等功能点,为 v1.5.0 版本做准备 2020-12-14 01:34:11 +08:00
shengzhang 81dbf3394b 增加okhttps友链 2020-11-25 20:07:54 +08:00
shengzhang 6c770cd5ce 修改readme 2020-11-20 14:06:07 +08:00
101 changed files with 5299 additions and 2359 deletions
+13
View File
@@ -0,0 +1,13 @@
target/
node_modules/
bin/
.settings/
unpackage/
.classpath
.project
.factorypath
/.factorypath
.idea/
+169 -307
View File
@@ -1,339 +1,201 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Preamble
1. Definitions.
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
The precise terms and conditions for copying, distribution and
modification follow.
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
END OF TERMS AND CONDITIONS
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
APPENDIX: How to apply the Apache License to your work.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
Copyright 2011-2019 hubin.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
https://www.apache.org/licenses/LICENSE-2.0
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+81 -28
View File
@@ -1,56 +1,109 @@
<p align="center">
<img alt="logo" src="http://sa-token.dev33.cn/doc/logo.png" width="150" height="150" style="margin-bottom: 10px;">
<img alt="logo" src="https://gitee.com/sz6/sa-token/raw/master/sa-token-doc/doc/logo.png" width="150" height="150" style="margin-bottom: 10px;">
</p>
<h1 align="center" style="margin: 30px 0 30px; font-weight: bold;">sa-token v1.4.0</h1>
<h4 align="center">一个JavaWeb权限认证框架,强大、简单、好用</h4>
<h1 align="center" style="margin: 30px 0 30px; font-weight: bold;">sa-token v1.8.0</h1>
<h4 align="center">一个JavaWeb轻量级权限认证框架,功能全面,上手简单</h4>
<h4 align="center">
<a href="https://github.com/click33/sa-token"><img src="https://img.shields.io/badge/sa--token-v1.4.0-2B9939"></a>
<a href="https://github.com/click33/sa-token"><img src="https://img.shields.io/badge/language-java-2B9939"></a>
<a href="https://gitee.com/sz6/sa-token/stargazers"><img src="https://gitee.com/sz6/sa-token/badge/star.svg"></a>
<a href="https://github.com/click33/sa-token"><img src="https://img.shields.io/badge/sa--token-v1.8.0-2B9939"></a>
<a href="https://github.com/click33/sa-token/stargazers"><img src="https://img.shields.io/github/stars/click33/sa-token"></a>
<a href="https://github.com/click33/sa-token/watchers"><img src="https://img.shields.io/github/watchers/click33/sa-token"></a>
<a href="https://github.com/click33/sa-token/network/members"><img src="https://img.shields.io/github/forks/click33/sa-token"></a>
<a href="https://github.com/click33/sa-token/issues"><img src="https://img.shields.io/github/issues/click33/sa-token.svg"></a>
<a href="https://github.com/click33/sa-token/blob/master/LICENSE"><img src="https://img.shields.io/github/license/click33/sa-token.svg"></a>
</h4>
## sa-token 😋
- 在线文档:[http://sa-token.dev33.cn/](http://sa-token.dev33.cn/)
- 需求提交:我们深知一个优秀的项目需要海纳百川,[点我在线提交需求](http://sa-app.dev33.cn/wall.html?name=sa-token)
- 开源不易,求鼓励,**点个`star`吧**
## 框架优点
与其它权限认证框架相比,sa-token尽力保证两点:
---
## 😘 在线资料
- [官网首页:http://sa-token.dev33.cn/](http://sa-token.dev33.cn/)
- [在线文档:http://sa-token.dev33.cn/doc/index.html](http://sa-token.dev33.cn/doc/index.html)
- [需求提交:我们深知一个优秀的项目需要海纳百川,点我在线提交需求](http://sa-app.dev33.cn/wall.html?name=sa-token)
- [开源不易,求鼓励,点个star吧](https://github.com/click33/sa-token)
## ⭐ sa-token是什么?
**sa-token是一个JavaWeb轻量级权限认证框架,其API调用非常简单,有多简单呢?以登录验证为例,你只需要:**
``` java
// 在登录时写入当前会话的账号id
StpUtil.setLoginId(10001);
// 然后在任意需要校验登录处调用以下API --- 如果当前会话未登录,这句代码会抛出 `NotLoginException`异常
StpUtil.checkLogin();
```
**没有复杂的封装!不要任何的配置!只需这两行简单的调用,即可轻松完成系统登录鉴权!**
## 🔥 框架设计思想
与其它权限认证框架相比,`sa-token`尽力保证两点:
- 上手简单:能自动化的配置全部自动化,不让你费脑子
- 功能强大:能涵盖的功能全部涵盖,不让你用个框架还要自己给框架打各种补丁
## 涵盖功能
- 登录验证
- 权限验证
- 自定义session会话
- 踢人下线
- 模拟他人账号
- 持久层扩展(集成redis
- 多账号认证体系(比如一个商城项目的user表和admin表)
- 无cookie模式(APP、小程序等前后台分离场景)
- 注解式鉴权(优雅的将鉴权与业务代码分离)
- 零配置与Spring等框架集成
- ...
## 贡献代码
**如果上面的示例能够证明`sa-token`的简单,那么以下API则可以证明`sa-token`的强大**
``` java
StpUtil.setLoginId(10001); // 标记当前会话登录的账号id
StpUtil.getLoginId(); // 获取当前会话登录的账号id
StpUtil.isLogin(); // 获取当前会话是否已经登录, 返回true或false
StpUtil.logout(); // 当前会话注销登录
StpUtil.logoutByLoginId(10001); // 让账号为10001的会话注销登录(踢人下线)
StpUtil.hasRole("super-admin"); // 查询当前账号是否含有指定角色标识, 返回true或false
StpUtil.hasPermission("user:add"); // 查询当前账号是否含有指定权限, 返回true或false
StpUtil.getSession(); // 获取当前账号id的Session
StpUtil.getSessionByLoginId(10001); // 获取账号id为10001的Session
StpUtil.getTokenValueByLoginId(10001); // 获取账号id为10001的token令牌值
```
**sa-token的API众多,请恕此处无法为您逐一展示,更多示例请戳官方在线文档**
## 💦️ 涵盖功能
- **登录验证** —— 轻松登录鉴权,并提供五种细分场景值
- **权限验证** —— 拦截违规调用,不同角色不同授权
- **Session会话** —— 专业的数据缓存中心
- **踢人下线** —— 将违规用户立刻清退下线
- **模拟他人账号** —— 实时操作任意用户状态数据
- **持久层扩展** —— 可集成redis、MongoDB等专业缓存中间件
- **多账号认证体系** —— 比如一个商城项目的user表和admin表分开鉴权
- **无Cookie模式** —— APP、小程序等前后台分离场景
- **注解式鉴权** —— 优雅的将鉴权与业务代码分离
- **花式token生成** —— 内置六种token风格,还可自定义token生成策略
- **自动续签** —— 提供两种token过期策略,灵活搭配使用,还可自动续签
- **组件自动注入** —— 零配置与Spring等框架集成
- **更多功能正在集成中...** —— 如有您有好想法或者建议,欢迎加群交流
## 🔨 贡献代码
sa-token欢迎大家贡献代码,为框架添砖加瓦
1. 在github上fork一份到自己的仓库
2. clone自己的仓库到本地电脑
3. 在本地电脑修改、commit、push
4. 提交pr(点击:New Pull Request(提交pr前请保证自己fork的仓库是最新版本,如若不是先强制更新一下)
4. 提交pr(点击:New Pull Request
5. 等待合并
## 建议贡献的地方
## 🌱 建议贡献的地方
- 修复源码现有bug,或增加新的实用功能
- 完善在线文档,或者修复现有错误之处
- 更多demo示例:比如SSM版搭建步骤
- 您可以参考项目issues与需求墙进行贡献
- 如果更新实用功能,可在文档友情链接处留下自己的推广链接
## 交流群
## 🚀 友情链接
[**[ okhttps ]** 一个轻量级http通信框架,支持 WebSocket 以及 Stomp 协议](https://gitee.com/ejlchina-zhxu/okhttps)
## 😎 交流群
QQ交流群:[1002350610 点击加入](https://jq.qq.com/?_wv=1027&k=45H977HM) ,欢迎你的加入
+89
View File
@@ -0,0 +1,89 @@
<?xml version='1.0' encoding='utf-8'?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- 基础信息 -->
<groupId>cn.dev33</groupId>
<artifactId>sa-token-parent</artifactId>
<packaging>pom</packaging>
<version>1.8.0</version>
<!-- 项目介绍 -->
<name>sa-token</name>
<description>A Java Web lightweight authority authentication framework, comprehensive function, easy to use</description>
<url>https://github.com/click33/sa-token</url>
<!-- 所有模块 -->
<modules>
<module>sa-token-core</module>
<module>sa-token-spring-boot-starter</module>
<module>sa-token-dao-redis</module>
<module>sa-token-dao-redis-jackson</module>
</modules>
<!-- 开源协议 apache 2.0 -->
<licenses>
<license>
<name>Apache 2</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
<comments>A business-friendly OSS license</comments>
</license>
</licenses>
<!-- 一些属性 -->
<properties>
<jdk.version>1.8</jdk.version>
<project.build.sourceEncoding>utf-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>utf-8</project.reporting.outputEncoding>
</properties>
<!-- 仓库信息 -->
<scm>
<tag>master</tag>
<url>https://github.com/click33/sa-token.git</url>
<connection>scm:git:https://github.com/click33/sa-token.git</connection>
<developerConnection>scm:git:https://github.com/click33/sa-token.git</developerConnection>
</scm>
<!-- 作者信息 -->
<developers>
<developer>
<name>shengzhang</name>
<email>2393584716@qq.com</email>
</developer>
</developers>
<!-- 父仓库 -->
<parent>
<groupId>org.sonatype.oss</groupId>
<artifactId>oss-parent</artifactId>
<version>7</version>
</parent>
<!-- 仓库依赖 -->
<dependencies>
</dependencies>
<!-- 项目构建 -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
+28
View File
@@ -0,0 +1,28 @@
<?xml version='1.0' encoding='utf-8'?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-parent</artifactId>
<version>1.8.0</version>
</parent>
<packaging>jar</packaging>
<name>sa-token-core</name>
<artifactId>sa-token-core</artifactId>
<description>A Java Web lightweight authority authentication framework, comprehensive function, easy to use</description>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,152 @@
package cn.dev33.satoken;
import cn.dev33.satoken.action.SaTokenAction;
import cn.dev33.satoken.action.SaTokenActionDefaultImpl;
import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.config.SaTokenConfigFactory;
import cn.dev33.satoken.cookie.SaTokenCookie;
import cn.dev33.satoken.cookie.SaTokenCookieDefaultImpl;
import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.dao.SaTokenDaoDefaultImpl;
import cn.dev33.satoken.servlet.SaTokenServlet;
import cn.dev33.satoken.servlet.SaTokenServletDefaultImpl;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpInterfaceDefaultImpl;
import cn.dev33.satoken.util.SaTokenInsideUtil;
/**
* 管理sa-token所有接口对象
* @author kong
*
*/
public class SaTokenManager {
/**
* 配置文件 Bean
*/
private static SaTokenConfig config;
public static SaTokenConfig getConfig() {
if (config == null) {
initConfig();
}
return config;
}
public static void setConfig(SaTokenConfig config) {
SaTokenManager.config = config;
if(config.getIsV()) {
SaTokenInsideUtil.printSaToken();
}
}
public synchronized static void initConfig() {
if (config == null) {
setConfig(SaTokenConfigFactory.createConfig());
}
}
/**
* 持久化 Bean
*/
public static SaTokenDao saTokenDao;
public static SaTokenDao getSaTokenDao() {
if (saTokenDao == null) {
initSaTokenDao();
}
return saTokenDao;
}
public static void setSaTokenDao(SaTokenDao saTokenDao) {
if(SaTokenManager.saTokenDao != null && (SaTokenManager.saTokenDao instanceof SaTokenDaoDefaultImpl)) {
((SaTokenDaoDefaultImpl)SaTokenManager.saTokenDao).endRefreshTimer();
}
SaTokenManager.saTokenDao = saTokenDao;
}
public synchronized static void initSaTokenDao() {
if (saTokenDao == null) {
setSaTokenDao(new SaTokenDaoDefaultImpl());
}
}
/**
* 权限认证 Bean
*/
public static StpInterface stpInterface;
public static StpInterface getStpInterface() {
if (stpInterface == null) {
initStpInterface();
}
return stpInterface;
}
public static void setStpInterface(StpInterface stpInterface) {
SaTokenManager.stpInterface = stpInterface;
}
public synchronized static void initStpInterface() {
if (stpInterface == null) {
setStpInterface(new StpInterfaceDefaultImpl());
}
}
/**
* 框架行为 Bean
*/
public static SaTokenAction saTokenAction;
public static SaTokenAction getSaTokenAction() {
if (saTokenAction == null) {
initSaTokenAction();
}
return saTokenAction;
}
public static void setSaTokenAction(SaTokenAction saTokenAction) {
SaTokenManager.saTokenAction = saTokenAction;
}
public synchronized static void initSaTokenAction() {
if (saTokenAction == null) {
setSaTokenAction(new SaTokenActionDefaultImpl());
}
}
/**
* Cookie操作 Bean
*/
public static SaTokenCookie saTokenCookie;
public static SaTokenCookie getSaTokenCookie() {
if (saTokenCookie == null) {
initSaTokenCookie();
}
return saTokenCookie;
}
public static void setSaTokenCookie(SaTokenCookie saTokenCookie) {
SaTokenManager.saTokenCookie = saTokenCookie;
}
public synchronized static void initSaTokenCookie() {
if (saTokenCookie == null) {
setSaTokenCookie(new SaTokenCookieDefaultImpl());
}
}
/**
* Servlet操作 Bean
*/
public static SaTokenServlet saTokenServlet;
public static SaTokenServlet getSaTokenServlet() {
if (saTokenServlet == null) {
initSaTokenServlet();
}
return saTokenServlet;
}
public static void setSaTokenServlet(SaTokenServlet saTokenServlet) {
SaTokenManager.saTokenServlet = saTokenServlet;
}
public synchronized static void initSaTokenServlet() {
if (saTokenServlet == null) {
setSaTokenServlet(new SaTokenServletDefaultImpl());
}
}
}
@@ -0,0 +1,19 @@
package cn.dev33.satoken.action;
/**
* sa-token内置操作接口
* @author kong
*
*/
public interface SaTokenAction {
/**
* 生成一个token
* @param loginId 账号id
* @param loginKey 账号标识key
* @return 一个token
*/
public String createToken(Object loginId, String loginKey);
}
@@ -0,0 +1,57 @@
package cn.dev33.satoken.action;
import java.util.UUID;
import cn.dev33.satoken.SaTokenManager;
import cn.dev33.satoken.util.SaTokenInsideUtil;
/**
* 对 SaTokenAction 接口的默认实现
* @author kong
*
*/
public class SaTokenActionDefaultImpl implements SaTokenAction {
/**
* 生成一个token
*/
@Override
public String createToken(Object loginId, String loginKey) {
// 生成各种花式token
String tokenStyle = SaTokenManager.getConfig().getTokenStyle();
// uuid
if(tokenStyle.equals("uuid")) {
return UUID.randomUUID().toString();
}
// 简单uuid (不带下划线)
else if(tokenStyle.equals("simple-uuid")) {
return UUID.randomUUID().toString().replaceAll("-", "");
}
// 32位随机字符串
else if(tokenStyle.equals("random-32")) {
return SaTokenInsideUtil.getRandomString(32);
}
// 64位随机字符串
else if(tokenStyle.equals("random-64")) {
return SaTokenInsideUtil.getRandomString(64);
}
// 128位随机字符串
else if(tokenStyle.equals("random-128")) {
return SaTokenInsideUtil.getRandomString(128);
}
// tik风格 (2_14_16)
else if(tokenStyle.equals("tik")) {
return SaTokenInsideUtil.getRandomString(2) + "_" + SaTokenInsideUtil.getRandomString(14) + "_" + SaTokenInsideUtil.getRandomString(16) + "__";
}
// 默认,还是uuid
else {
return UUID.randomUUID().toString();
}
}
}
@@ -6,7 +6,8 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 标注一个路由方法当前会话必须已登录才能通过
* 标注一个路由方法当前会话必须已登录才能通过
* <p> 可标注在类上其效果等同于标注在此类的所有方法上
* @author kong
*
*/
@@ -7,6 +7,7 @@ import java.lang.annotation.Target;
/**
* 标注一个路由方法当前会话必须具有指定权限才可以通过
* <p> 可标注在类上其效果等同于标注在此类的所有方法上
* @author kong
*
*/
@@ -15,27 +16,15 @@ import java.lang.annotation.Target;
public @interface SaCheckPermission {
/**
* 权限码数组 String类型
* @return .
* 需要验证的权限码
* @return 需要验证的权限码
*/
String [] value() default {};
/**
* 权限码数组 int类型
* @return .
* 指定验证模式是AND还是OR默认AND
* @return 验证模式
*/
int [] valueInt() default {};
/**
* 权限码数组 long类型
* @return .
*/
long [] valueLong() default {};
/**
* 是否属于and型验证 true=必须全部具有false=只要具有一个就可以通过
* @return .
*/
boolean isAnd() default true;
SaMode mode() default SaMode.AND;
}
@@ -0,0 +1,30 @@
package cn.dev33.satoken.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 标注一个路由方法,当前会话必须具有指定角色标识才可以通过
* <p> 可标注在类上,其效果等同于标注在此类的所有方法上
* @author kong
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface SaCheckRole {
/**
* 需要验证的角色标识
* @return 需要验证的权限码
*/
String [] value() default {};
/**
* 指定验证模式是AND还是OR,默认AND
* @return 验证模式
*/
SaMode mode() default SaMode.AND;
}
@@ -0,0 +1,20 @@
package cn.dev33.satoken.annotation;
/**
* 指定注解鉴权的验证模式
* @author kong
*
*/
public enum SaMode {
/**
* 必须具有所有的选项
*/
AND,
/**
* 只需具有其中一个选项
*/
OR
}
@@ -0,0 +1,244 @@
package cn.dev33.satoken.config;
/**
* sa-token 配置类Model
* @author kong
*
*/
public class SaTokenConfig {
/** token名称 (同时也是cookie名称) */
private String tokenName = "satoken";
/** token有效期,单位/秒 默认30天, -1代表永久 */
private long timeout = 30 * 24 * 60 * 60;
/** token临时有效期 (指定时间内无操作就视为token过期) 单位/秒, 默认-1 代表不限制 (例如可以设置为1800代表30分钟内无操作就过期) */
private long activityTimeout = -1;
/** 是否允许同一账号并发登录 (为true时允许一起登录, 为false时新登录挤掉旧登录) */
private Boolean allowConcurrentLogin = true;
/** 在多人登录同一账号时,是否共用一个token (为true时所有登录共用一个token, 为false时每次登录新建一个token) */
private Boolean isShare = true;
/** 是否尝试从请求体里读取token */
private Boolean isReadBody = true;
/** 是否尝试从header里读取token */
private Boolean isReadHead = true;
/** 是否尝试从cookie里读取token */
private Boolean isReadCookie = true;
/** token风格 */
private String tokenStyle = "uuid";
/** 默认dao层实现类中,每次清理过期数据间隔的时间 (单位: 秒) ,默认值30秒,设置为-1代表不启动定时清理 */
private int dataRefreshPeriod = 30;
/** 获取token专属session时是否必须登录 (如果配置为true,会在每次获取token专属session时校验是否登录) */
private Boolean tokenSessionCheckLogin = true;
/** 是否在初始化配置时打印版本字符画 */
private Boolean isV = true;
/**
* @return tokenName
*/
public String getTokenName() {
return tokenName;
}
/**
* @param tokenName 要设置的 tokenName
*/
public void setTokenName(String tokenName) {
this.tokenName = tokenName;
}
/**
* @return timeout
*/
public long getTimeout() {
return timeout;
}
/**
* @param timeout 要设置的 timeout
*/
public void setTimeout(long timeout) {
this.timeout = timeout;
}
/**
* @return activityTimeout
*/
public long getActivityTimeout() {
return activityTimeout;
}
/**
* @param activityTimeout 要设置的 activityTimeout
*/
public void setActivityTimeout(long activityTimeout) {
this.activityTimeout = activityTimeout;
}
/**
* @return allowConcurrentLogin
*/
public Boolean getAllowConcurrentLogin() {
return allowConcurrentLogin;
}
/**
* @param allowConcurrentLogin 要设置的 allowConcurrentLogin
*/
public void setAllowConcurrentLogin(Boolean allowConcurrentLogin) {
this.allowConcurrentLogin = allowConcurrentLogin;
}
/**
* @return isShare
*/
public Boolean getIsShare() {
return isShare;
}
/**
* @param isShare 要设置的 isShare
*/
public void setIsShare(Boolean isShare) {
this.isShare = isShare;
}
/**
* @return isReadBody
*/
public Boolean getIsReadBody() {
return isReadBody;
}
/**
* @param isReadBody 要设置的 isReadBody
*/
public void setIsReadBody(Boolean isReadBody) {
this.isReadBody = isReadBody;
}
/**
* @return isReadHead
*/
public Boolean getIsReadHead() {
return isReadHead;
}
/**
* @param isReadHead 要设置的 isReadHead
*/
public void setIsReadHead(Boolean isReadHead) {
this.isReadHead = isReadHead;
}
/**
* @return isReadCookie
*/
public Boolean getIsReadCookie() {
return isReadCookie;
}
/**
* @param isReadCookie 要设置的 isReadCookie
*/
public void setIsReadCookie(Boolean isReadCookie) {
this.isReadCookie = isReadCookie;
}
/**
* @return tokenStyle
*/
public String getTokenStyle() {
return tokenStyle;
}
/**
* @param tokenStyle 要设置的 tokenStyle
*/
public void setTokenStyle(String tokenStyle) {
this.tokenStyle = tokenStyle;
}
/**
* @return dataRefreshPeriod
*/
public int getDataRefreshPeriod() {
return dataRefreshPeriod;
}
/**
* @param dataRefreshPeriod 要设置的 dataRefreshPeriod
*/
public void setDataRefreshPeriod(int dataRefreshPeriod) {
this.dataRefreshPeriod = dataRefreshPeriod;
}
/**
* @return tokenSessionCheckLogin
*/
public Boolean getTokenSessionCheckLogin() {
return tokenSessionCheckLogin;
}
/**
* @param tokenSessionCheckLogin 要设置的 tokenSessionCheckLogin
*/
public void setTokenSessionCheckLogin(Boolean tokenSessionCheckLogin) {
this.tokenSessionCheckLogin = tokenSessionCheckLogin;
}
/**
* @return isV
*/
public Boolean getIsV() {
return isV;
}
/**
* @param isV 要设置的 isV
*/
public void setIsV(Boolean isV) {
this.isV = isV;
}
@Override
public String toString() {
return "SaTokenConfig [tokenName=" + tokenName + ", timeout=" + timeout + ", activityTimeout=" + activityTimeout
+ ", allowConcurrentLogin=" + allowConcurrentLogin + ", isShare=" + isShare + ", isReadBody="
+ isReadBody + ", isReadHead=" + isReadHead + ", isReadCookie=" + isReadCookie + ", tokenStyle="
+ tokenStyle + ", dataRefreshPeriod=" + dataRefreshPeriod + ", tokenSessionCheckLogin="
+ tokenSessionCheckLogin + ", isV=" + isV + "]";
}
}
@@ -8,7 +8,7 @@ import java.util.Map;
import java.util.Properties;
/**
* 创建一个配置文件
* sa-token配置文件创建工厂类
* @author kong
*
*/
@@ -16,7 +16,7 @@ public class SaTokenConfigFactory {
/**
* 默认配置文件地址
* 默认配置文件地址
*/
public static String configPath = "sa-token.properties";
@@ -102,7 +102,7 @@ public class SaTokenConfigFactory {
* 将字符串转化为指定数据类型
* @param str
* @param cs 要转换的类型
* @return .
* @return 转化好的结果
*/
@SuppressWarnings("unchecked")
private static <T>T getObjectByClass(String str, Class<T> cs){
@@ -0,0 +1,49 @@
package cn.dev33.satoken.cookie;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* sa-token 对cookie的相关操作 接口类
* @author kong
*
*/
public interface SaTokenCookie {
/**
* 在request对象中获取指定Cookie
* @param request request对象
* @param cookieName Cookie名称
* @return 查找到的Cookie对象
*/
public Cookie getCookie(HttpServletRequest request, String cookieName);
/**
* 添加Cookie
* @param response response对象
* @param name Cookie名称
* @param value Cookie值
* @param path Cookie路径
* @param timeout 过期时间 (秒)
*/
public void addCookie(HttpServletResponse response, String name, String value, String path, int timeout);
/**
* 删除Cookie
* @param request request对象
* @param response response对象
* @param name Cookie名称
*/
public void delCookie(HttpServletRequest request, HttpServletResponse response, String name);
/**
* 修改Cookie的value值
* @param request request对象
* @param response response对象
* @param name Cookie名称
* @param value Cookie值
*/
public void updateCookie(HttpServletRequest request, HttpServletResponse response, String name, String value);
}
@@ -0,0 +1,46 @@
package cn.dev33.satoken.cookie;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* sa-token 对cookie的相关操作 接口实现类
* @author kong
*
*/
public class SaTokenCookieDefaultImpl implements SaTokenCookie {
/**
* 获取指定cookie
*/
@Override
public Cookie getCookie(HttpServletRequest request, String cookieName) {
return SaTokenCookieUtil.getCookie(request, cookieName);
}
/**
* 添加cookie
*/
@Override
public void addCookie(HttpServletResponse response, String name, String value, String path, int timeout) {
SaTokenCookieUtil.addCookie(response, name, value, path, timeout);
}
/**
* 删除cookie
*/
@Override
public void delCookie(HttpServletRequest request, HttpServletResponse response, String name) {
SaTokenCookieUtil.delCookie(request, response, name);
}
/**
* 修改cookie的value值
*/
@Override
public void updateCookie(HttpServletRequest request, HttpServletResponse response, String name, String value) {
SaTokenCookieUtil.updateCookie(request, response, name, value);
}
}
@@ -0,0 +1,87 @@
package cn.dev33.satoken.cookie;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Cookie操作工具类
* @author kong
*/
public class SaTokenCookieUtil {
/**
* 在request对象中获取指定Cookie
* @param request request对象
* @param cookieName Cookie名称
* @return 查找到的Cookie对象
*/
public static Cookie getCookie(HttpServletRequest request, String cookieName) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie != null && cookieName.equals(cookie.getName())) {
return cookie;
}
}
}
return null;
}
/**
* 添加cookie
* @param response response
* @param name Cookie名称
* @param value Cookie值
* @param path Cookie写入路径
* @param timeout Cookie有效期 (秒)
*/
public static void addCookie(HttpServletResponse response, String name, String value, String path, int timeout) {
Cookie cookie = new Cookie(name, value);
if (path == null) {
path = "/";
}
cookie.setPath(path);
cookie.setMaxAge(timeout);
response.addCookie(cookie);
}
/**
* 删除Cookie
* @param request request对象
* @param response response对象
* @param name Cookie名称
*/
public static void delCookie(HttpServletRequest request, HttpServletResponse response, String name) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie != null && (name).equals(cookie.getName())) {
addCookie(response, name, null, null, 0);
return;
}
}
}
}
/**
* 修改cookie的value值
* @param request request对象
* @param response response对象
* @param name Cookie名称
* @param value Cookie值
*/
public static void updateCookie(HttpServletRequest request, HttpServletResponse response, String name,
String value) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie != null && (name).equals(cookie.getName())) {
addCookie(response, name, value, cookie.getPath(), cookie.getMaxAge());
return;
}
}
}
}
}
@@ -0,0 +1,107 @@
package cn.dev33.satoken.dao;
import cn.dev33.satoken.session.SaSession;
/**
* sa-token持久层的接口
* @author kong
*/
public interface SaTokenDao {
/** 常量,表示一个key永不过期 (在一个key被标注为永远不过期时返回此值) */
public static final Long NEVER_EXPIRE = -1L;
/** 常量,表示系统中不存在这个缓存 (在对不存在的key获取剩余存活时间时返回此值) */
public static final Long NOT_VALUE_EXPIRE = -2L;
/**
* 根据key获取value,如果没有,则返回空
* @param key 键名称
* @return value
*/
public String getValue(String key);
/**
* 写入指定key-value键值对,并设定过期时间 (单位: 秒)
* @param key 键名称
* @param value 值
* @param timeout 过期时间 (单位: 秒)
*/
public void setValue(String key, String value, long timeout);
/**
* 修改指定key-value键值对 (过期时间取原来的值)
* @param key 键名称
* @param value 值
*/
public void updateValue(String key, String value);
/**
* 删除一个指定的key
* @param key 键名称
*/
public void deleteKey(String key);
/**
* 获取指定key的剩余存活时间 (单位: 秒)
* @param key 指定key
* @return 这个key的剩余存活时间
*/
public long getTimeout(String key);
/**
* 修改指定key的剩余存活时间 (单位: 秒)
* @param key 指定key
* @param timeout 过期时间
*/
public void updateTimeout(String key, long timeout);
/**
* 根据指定key的Session,如果没有,则返回空
* @param sessionId 键名称
* @return SaSession
*/
public SaSession getSession(String sessionId);
/**
* 将指定Session持久化
* @param session 要保存的session对象
* @param timeout 过期时间 (单位: 秒)
*/
public void saveSession(SaSession session, long timeout);
/**
* 更新指定session
* @param session 要更新的session对象
*/
public void updateSession(SaSession session);
/**
* 删除一个指定的session
* @param sessionId sessionId
*/
public void deleteSession(String sessionId);
/**
* 获取指定SaSession的剩余存活时间 (单位: 秒)
* @param sessionId 指定SaSession
* @return 这个SaSession的剩余存活时间 (单位: 秒)
*/
public long getSessionTimeout(String sessionId);
/**
* 修改指定SaSession的剩余存活时间 (单位: 秒)
* @param sessionId sessionId
* @param timeout 过期时间
*/
public void updateSessionTimeout(String sessionId, long timeout);
}
@@ -0,0 +1,214 @@
package cn.dev33.satoken.dao;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.concurrent.ConcurrentHashMap;
import cn.dev33.satoken.SaTokenManager;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.util.SaTaskUtil;
import cn.dev33.satoken.util.SaTaskUtil.FunctionRunClass;
/**
* sa-token持久层默认的实现类 , 基于内存Map
* @author kong
*
*/
public class SaTokenDaoDefaultImpl implements SaTokenDao {
/**
* 所有数据集合
*/
public Map<String, Object> dataMap = new ConcurrentHashMap<String, Object>();
/**
* 过期时间集合 (单位: 毫秒) , 记录所有key的到期时间 [注意不是剩余存活时间]
*/
public Map<String, Long> expireMap = new ConcurrentHashMap<String, Long>();
/**
* 构造函数
*/
public SaTokenDaoDefaultImpl() {
initRefreshTimer();
}
// ------------------------ String 读写操作
@Override
public String getValue(String key) {
clearKeyByTimeout(key);
return (String)dataMap.get(key);
}
@Override
public void setValue(String key, String value, long timeout) {
dataMap.put(key, value);
expireMap.put(key, (timeout == SaTokenDao.NEVER_EXPIRE) ? (SaTokenDao.NEVER_EXPIRE) : (System.currentTimeMillis() + timeout * 1000));
}
@Override
public void updateValue(String key, String value) {
if(getKeyTimeout(key) == SaTokenDao.NOT_VALUE_EXPIRE) {
return;
}
dataMap.put(key, value);
}
@Override
public void deleteKey(String key) {
dataMap.remove(key);
expireMap.remove(key);
}
@Override
public long getTimeout(String key) {
return getKeyTimeout(key);
}
@Override
public void updateTimeout(String key, long timeout) {
expireMap.put(key, System.currentTimeMillis() + timeout * 1000);
}
// ------------------------ Session 读写操作
@Override
public SaSession getSession(String sessionId) {
clearKeyByTimeout(sessionId);
return (SaSession)dataMap.get(sessionId);
}
@Override
public void saveSession(SaSession session, long timeout) {
dataMap.put(session.getId(), session);
expireMap.put(session.getId(), (timeout == SaTokenDao.NEVER_EXPIRE) ? (SaTokenDao.NEVER_EXPIRE) : (System.currentTimeMillis() + timeout * 1000));
}
@Override
public void updateSession(SaSession session) {
if(getKeyTimeout(session.getId()) == SaTokenDao.NOT_VALUE_EXPIRE) {
return;
}
// 无动作
}
@Override
public void deleteSession(String sessionId) {
dataMap.remove(sessionId);
expireMap.remove(sessionId);
}
@Override
public long getSessionTimeout(String sessionId) {
return getKeyTimeout(sessionId);
}
@Override
public void updateSessionTimeout(String sessionId, long timeout) {
expireMap.put(sessionId, System.currentTimeMillis() + timeout * 1000);
}
// ------------------------ 过期时间相关操作
/**
* 如果指定key已经过期,则立即清除它
* @param key 指定key
*/
void clearKeyByTimeout(String key) {
Long expirationTime = expireMap.get(key);
// 清除条件:如果不为空 && 不是[永不过期] && 已经超过过期时间
if(expirationTime != null && expirationTime != SaTokenDao.NEVER_EXPIRE && expirationTime < System.currentTimeMillis()) {
dataMap.remove(key);
expireMap.remove(key);
}
}
/**
* 获取指定key的剩余存活时间 (单位:秒)
*/
long getKeyTimeout(String key) {
// 先检查是否已经过期
clearKeyByTimeout(key);
// 获取过期时间
Long expire = expireMap.get(key);
// 如果根本没有这个值
if(expire == null) {
return SaTokenDao.NOT_VALUE_EXPIRE;
}
// 如果被标注为永不过期
if(expire == SaTokenDao.NEVER_EXPIRE) {
return SaTokenDao.NEVER_EXPIRE;
}
// ---- 计算剩余时间并返回
long timeout = (expire - System.currentTimeMillis()) / 1000;
// 小于零时,视为不存在
if(timeout < 0) {
dataMap.remove(key);
expireMap.remove(key);
return SaTokenDao.NOT_VALUE_EXPIRE;
}
return timeout;
}
// --------------------- 定时清理过期数据
/**
* 定时任务对象
*/
public Timer refreshTimer;
/**
* 清理所有已经过期的key
*/
public void refreshDataMap() {
Iterator<String> keys = expireMap.keySet().iterator();
while (keys.hasNext()) {
clearKeyByTimeout(keys.next());
}
}
/**
* 初始化定时任务
*/
public void initRefreshTimer() {
// 如果已经被初始化过了, 则停止它
if(this.refreshTimer != null) {
this.endRefreshTimer();
}
// 开始新的定时任务
if(SaTokenManager.getConfig().getDataRefreshPeriod() < 0) {
return;
}
int period = SaTokenManager.getConfig().getDataRefreshPeriod() * 1000;
this.refreshTimer = SaTaskUtil.setInterval(new FunctionRunClass() {
@Override
public void run() {
refreshDataMap();
}
}, period, period);
}
/**
* 结束定时任务
*/
public void endRefreshTimer() {
this.refreshTimer.cancel();
}
}
@@ -0,0 +1,125 @@
package cn.dev33.satoken.exception;
import java.util.Arrays;
import java.util.List;
/**
* 一个异常:代表用户没有登录
* @author kong
*/
public class NotLoginException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 6806129545290130142L;
// ------------------- 异常类型常量 --------------------
/*
* 这里简述一下为什么要把常量设计为String类型
* 因为loginId刚取出的时候类型为String,为了避免两者相比较时不必要的类型转换带来的性能消耗,故在此直接将常量类型设计为String
*/
/** 表示未提供token */
public static final String NOT_TOKEN = "-1";
public static final String NOT_TOKEN_MESSAGE = "未提供token";
/** 表示token无效 */
public static final String INVALID_TOKEN = "-2";
public static final String INVALID_TOKEN_MESSAGE = "token无效";
/** 表示token已过期 */
public static final String TOKEN_TIMEOUT = "-3";
public static final String TOKEN_TIMEOUT_MESSAGE = "token已过期";
/** 表示token已被顶下线 */
public static final String BE_REPLACED = "-4";
public static final String BE_REPLACED_MESSAGE = "token已被顶下线";
/** 表示token已被踢下线 */
public static final String KICK_OUT = "-5";
public static final String KICK_OUT_MESSAGE = "token已被踢下线";
/** 默认的提示语 */
public static final String DEFAULT_MESSAGE = "当前会话未登录";
/**
* 代表异常token的标志集合
*/
public static final List<String> ABNORMAL_LIST = Arrays.asList(NOT_TOKEN, INVALID_TOKEN, TOKEN_TIMEOUT, BE_REPLACED, KICK_OUT);
/**
* 异常类型
*/
private String type;
/**
* 获取异常类型
* @return 异常类型
*/
public String getType() {
return type;
}
/**
* loginKey
*/
private String loginKey;
/**
* 获得loginKey
* @return loginKey
*/
public String getLoginKey() {
return loginKey;
}
/**
* 构造方法创建一个
* @param message 异常消息
* @param loginKey loginKey
* @param type 类型
*/
public NotLoginException(String message, String loginKey, String type) {
// 这里到底要不要拼接上login_key呢?纠结
super(message);
this.loginKey = loginKey;
this.type = type;
}
/**
* 静态方法构建一个NotLoginException
* @param loginKey loginKey
* @param type 场景类型
* @return 构建完毕的异常对象
*/
public static NotLoginException newInstance(String loginKey, String type) {
String message = null;
if(type.equals(NOT_TOKEN)) {
message = NOT_TOKEN_MESSAGE;
}
else if(type.equals(INVALID_TOKEN)) {
message = INVALID_TOKEN_MESSAGE;
}
else if(type.equals(TOKEN_TIMEOUT)) {
message = TOKEN_TIMEOUT_MESSAGE;
}
else if(type.equals(BE_REPLACED)) {
message = BE_REPLACED_MESSAGE;
}
else if(type.equals(KICK_OUT)) {
message = KICK_OUT_MESSAGE;
}
else {
message = DEFAULT_MESSAGE;
}
return new NotLoginException(message, loginKey, type);
}
}
@@ -8,41 +8,40 @@ import cn.dev33.satoken.stp.StpUtil;
*
*/
public class NotPermissionException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 6806129545290130142L;
/**
* 权限码
*/
private Object code;
/** 权限码 */
private String code;
/**
* @return 获得权限码
*/
public Object getCode() {
public String getCode() {
return code;
}
/**
* login_key
* loginKey
*/
private String loginKey;
/**
* 获得login_key
* @return login_key
* 获得loginKey
* @return loginKey
*/
public String getLoginKey() {
return loginKey;
}
public NotPermissionException(Object code) {
public NotPermissionException(String code) {
this(code, StpUtil.stpLogic.loginKey);
}
public NotPermissionException(Object code, String loginKey) {
// 这里到底要不要拼接上login_key呢纠结
public NotPermissionException(String code, String loginKey) {
// 这里到底要不要拼接上loginKey呢纠结
super("无此权限:" + code);
this.code = code;
this.loginKey = loginKey;
@@ -0,0 +1,51 @@
package cn.dev33.satoken.exception;
import cn.dev33.satoken.stp.StpUtil;
/**
* 没有指定角色标识,抛出的异常
* @author kong
*
*/
public class NotRoleException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 8243974276159004739L;
/** 角色标识 */
private String role;
/**
* @return 获得角色标识
*/
public String getRole() {
return role;
}
/**
* loginKey
*/
private String loginKey;
/**
* 获得loginKey
* @return loginKey
*/
public String getLoginKey() {
return loginKey;
}
public NotRoleException(String role) {
this(role, StpUtil.stpLogic.loginKey);
}
public NotRoleException(String role, String loginKey) {
// 这里到底要不要拼接上loginKey呢?纠结
super("无此角色:" + role);
this.role = role;
this.loginKey = loginKey;
}
}
@@ -0,0 +1,25 @@
package cn.dev33.satoken.exception;
/**
* sa-token框架内部逻辑发生错误抛出的异常
* @author kong
*
*/
public class SaTokenException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 6806129545290130132L;
/**
* 构建一个异常
* @param message 异常描述信息
*/
public SaTokenException(String message) {
super(message);
}
}
@@ -0,0 +1,27 @@
package cn.dev33.satoken.servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet相关操作
* @author kong
*
*/
public interface SaTokenServlet {
/**
* 获取当前请求的 Request 对象
* @return 当前请求的Request对象
*/
public HttpServletRequest getRequest();
/**
* 获取当前请求的 Response 对象
* @return 当前请求的response对象
*/
public HttpServletResponse getResponse();
}
@@ -0,0 +1,30 @@
package cn.dev33.satoken.servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* sa-token 对SaTokenServlet接口默认实现类
* @author kong
*
*/
public class SaTokenServletDefaultImpl implements SaTokenServlet {
/**
* 获取当前请求的Request对象
*/
@Override
public HttpServletRequest getRequest() {
throw new RuntimeException("请实现SaTokenServlet接口后进行Servlet相关操作");
}
/**
* 获取当前请求的Response对象
*/
@Override
public HttpServletResponse getResponse() {
throw new RuntimeException("请实现SaTokenServlet接口后进行Servlet相关操作");
}
}
@@ -0,0 +1,221 @@
package cn.dev33.satoken.session;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import cn.dev33.satoken.SaTokenManager;
/**
* session会话
* @author kong
*
*/
public class SaSession implements Serializable {
private static final long serialVersionUID = 1L;
/** 此会话的id */
private String id;
/** 此会话的创建时间 */
private long createTime;
/** 此会话的所有数据 */
private Map<String, Object> dataMap = new ConcurrentHashMap<String, Object>();
/**
* 构建一个 session对象
*/
public SaSession() {}
/**
* 构建一个 session对象
* @param id session的id
*/
public SaSession(String id) {
this.id = id;
this.createTime = System.currentTimeMillis();
}
/**
* 获取此会话id
* @return 此会话的id
*/
public String getId() {
return id;
}
/**
* 返回当前会话创建时间
* @return 时间戳
*/
public long getCreateTime() {
return createTime;
}
// ----------------------- tokenSign相关
/**
* 本session绑定的token签名列表
*/
private List<TokenSign> tokenSignList = new Vector<TokenSign>();
/**
* 返回token签名列表
* @return token签名列表
*/
public List<TokenSign> getTokenSignList() {
return new Vector<>(tokenSignList);
}
/**
* 查找一个token签名
* @param tokenValue token值
* @return 查找到的tokenSign
*/
public TokenSign getTokenSign(String tokenValue) {
for (TokenSign tokenSign : getTokenSignList()) {
if(tokenSign.getValue().equals(tokenValue)){
return tokenSign;
}
}
return null;
}
/**
* 添加一个token签名
* @param tokenSign token签名
*/
public void addTokenSign(TokenSign tokenSign) {
// 如果已经存在于列表中,则无需再次添加
for (TokenSign tokenSign2 : getTokenSignList()) {
if(tokenSign2.getValue().equals(tokenSign.getValue())){
return;
}
}
// 添加并更新
tokenSignList.add(tokenSign);
update();
}
/**
* 移除一个token签名
* @param tokenValue token名称
*/
public void removeTokenSign(String tokenValue) {
TokenSign tokenSign = getTokenSign(tokenValue);
if(tokenSignList.remove(tokenSign)) {
update();
}
}
// ----------------------- 存取值
/**
* 写入一个值
* @param key 名称
* @param value 值
*/
public void setAttribute(String key, Object value) {
dataMap.put(key, value);
update();
}
/**
* 取出一个值
* @param key 名称
* @return 值
*/
public Object getAttribute(String key) {
return dataMap.get(key);
}
/**
* 取值,并指定取不到值时的默认值
* @param key 名称
* @param defaultValue 取不到值的时候返回的默认值
* @return value
*/
public Object getAttribute(String key, Object defaultValue) {
Object value = getAttribute(key);
if(value != null) {
return value;
}
return defaultValue;
}
/**
* 移除一个值
* @param key 要移除的值的名字
*/
public void removeAttribute(String key) {
dataMap.remove(key);
update();
}
/**
* 清空所有值
*/
public void clearAttribute() {
dataMap.clear();
update();
}
/**
* 是否含有指定key
* @param key 是否含有指定值
* @return 是否含有
*/
public boolean containsAttribute(String key) {
return dataMap.keySet().contains(key);
}
/**
* 返回当前session会话所有key
* @return 所有值的key列表
*/
public Set<String> attributeKeys() {
return dataMap.keySet();
}
/**
* 获取数据集合(如果更新map里的值,请调用session.update()方法避免数据过时
* @return 返回底层储存值的map对象
*/
public Map<String, Object> getDataMap() {
return dataMap;
}
// ----------------------- 一些操作
/**
* 将这个session从持久库更新一下
*/
public void update() {
SaTokenManager.getSaTokenDao().updateSession(this);
}
/** 注销会话(注销后,此session会话将不再存储服务器上) */
public void logout() {
SaTokenManager.getSaTokenDao().deleteSession(this.id);
}
/** 如果这个token的tokenSign数量为零,则直接注销会话 */
public void logoutByTokenSignCountToZero() {
if(tokenSignList.size() == 0) {
logout();
}
}
}
@@ -12,34 +12,42 @@ public class SaSessionCustomUtil {
/**
* 添加上指定前缀防止恶意伪造session
*/
public static String session_key = "custom";
public static String sessionKey = "custom";
/**
* 组织一下自定义session的id
* @param sessionId 会话id
* @return sessionId
*/
public static String getSessionKey(String sessionId) {
return SaTokenManager.getConfig().getTokenName() + ":" + session_key + ":session:" + sessionId;
return SaTokenManager.getConfig().getTokenName() + ":" + sessionKey + ":session:" + sessionId;
}
/**
* 指定key的session是否存在
* 指定key的session是否存在
* @param sessionId session的id
* @return 是否存在
*/
public boolean isExists(String sessionId) {
return SaTokenManager.getDao().getSaSession(getSessionKey(sessionId)) != null;
return SaTokenManager.getSaTokenDao().getSession(getSessionKey(sessionId)) != null;
}
/**
* 获取指定key的session
* 获取指定key的session
* @param sessionId key
* @param isCreate 如果没有是否新建并返回
* @return
* @return SaSession
*/
public static SaSession getSessionById(String sessionId, boolean isCreate) {
SaSession session = SaTokenManager.getDao().getSaSession(getSessionKey(sessionId));
SaSession session = SaTokenManager.getSaTokenDao().getSession(getSessionKey(sessionId));
if(session == null && isCreate) {
session = new SaSession(getSessionKey(sessionId));
SaTokenManager.getDao().saveSaSession(session, SaTokenManager.getConfig().getTimeout());
SaTokenManager.getSaTokenDao().saveSession(session, SaTokenManager.getConfig().getTimeout());
}
return session;
}
/**
* 获取指定key的session, 如果没有则新建并返回
* @param sessionId key
@@ -50,11 +58,11 @@ public class SaSessionCustomUtil {
}
/**
* 删除指定key的session
* 删除指定key的session
* @param sessionId 删除指定key
*/
public static void delSessionById(String sessionId) {
SaTokenManager.getDao().delSaSession(getSessionKey(sessionId));
public static void deleteSessionById(String sessionId) {
SaTokenManager.getSaTokenDao().deleteSession(getSessionKey(sessionId));
}
@@ -0,0 +1,68 @@
package cn.dev33.satoken.session;
import java.io.Serializable;
/**
* 挂在到SaSession上的token签名
* @author kong
*
*/
public class TokenSign implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1406115065849845073L;
/**
* token值
*/
private String value;
/**
* 所在设备标识
*/
private String device;
/** 构建一个 */
public TokenSign() {}
/**
* 构建一个
* @param value token值
* @param device 所在设备标识
*/
public TokenSign(String value, String device) {
this.value = value;
this.device = device;
}
/**
* @return value
*/
public String getValue() {
return value;
}
/**
* @return device
*/
public String getDevice() {
return device;
}
@Override
public String toString() {
return "TokenSign [value=" + value + ", device=" + device + "]";
}
}
@@ -0,0 +1,213 @@
package cn.dev33.satoken.stp;
/**
* 用来描述一个token常用信息的类
* @author kong
*
*/
public class SaTokenInfo {
/** token名称 */
public String tokenName;
/** token值 */
public String tokenValue;
/** 当前是否已经登录 */
public Boolean isLogin;
/** 当前loginId,未登录时为null */
public Object loginId;
/** 当前loginKey */
public String loginKey;
/** token剩余有效期 (单位: 秒) */
public long tokenTimeout;
/** session剩余有效时间 (单位: 秒) */
public long sessionTimeout;
/** token专属session剩余有效时间 (单位: 秒) */
public long tokenSessionTimeout;
/**
* token剩余无操作有效时间
*/
public long tokenActivityTimeout;
/**
* @return tokenName token名称
*/
public String getTokenName() {
return tokenName;
}
/**
* @param tokenName 要设置的 tokenName
* @return 对象自身
*/
public SaTokenInfo setTokenName(String tokenName) {
this.tokenName = tokenName;
return this;
}
/**
* @return tokenValue
*/
public String getTokenValue() {
return tokenValue;
}
/**
* @param tokenValue 要设置的 tokenValue
* @return 对象自身
*/
public SaTokenInfo setTokenValue(String tokenValue) {
this.tokenValue = tokenValue;
return this;
}
/**
* @return isLogin
*/
public Boolean getIsLogin() {
return isLogin;
}
/**
* @param isLogin 要设置的 isLogin
* @return 对象自身
*/
public SaTokenInfo setIsLogin(Boolean isLogin) {
this.isLogin = isLogin;
return this;
}
/**
* @return loginId
*/
public Object getLoginId() {
return loginId;
}
/**
* @param loginId 要设置的 loginId
* @return 对象自身
*/
public SaTokenInfo setLoginId(Object loginId) {
this.loginId = loginId;
return this;
}
/**
* @return loginKey
*/
public String getLoginKey() {
return loginKey;
}
/**
* @param loginKey 要设置的 loginKey
* @return 对象自身
*/
public SaTokenInfo setLoginKey(String loginKey) {
this.loginKey = loginKey;
return this;
}
/**
* @return tokenTimeout
*/
public long getTokenTimeout() {
return tokenTimeout;
}
/**
* @param tokenTimeout 要设置的 tokenTimeout
* @return 对象自身
*/
public SaTokenInfo setTokenTimeout(long tokenTimeout) {
this.tokenTimeout = tokenTimeout;
return this;
}
/**
* @return sessionTimeout
*/
public long getSessionTimeout() {
return sessionTimeout;
}
/**
* @param sessionTimeout 要设置的 sessionTimeout
* @return 对象自身
*/
public SaTokenInfo setSessionTimeout(long sessionTimeout) {
this.sessionTimeout = sessionTimeout;
return this;
}
/**
* @return tokenSessionTimeout
*/
public long getTokenSessionTimeout() {
return tokenSessionTimeout;
}
/**
* @param tokenSessionTimeout 要设置的 tokenSessionTimeout
* @return 对象自身
*/
public SaTokenInfo setTokenSessionTimeout(long tokenSessionTimeout) {
this.tokenSessionTimeout = tokenSessionTimeout;
return this;
}
/**
* @return tokenActivityTimeout
*/
public long getTokenActivityTimeout() {
return tokenActivityTimeout;
}
/**
* @param tokenActivityTimeout 要设置的 tokenActivityTimeout
* @return 对象自身
*/
public SaTokenInfo setTokenActivityTimeout(long tokenActivityTimeout) {
this.tokenActivityTimeout = tokenActivityTimeout;
return this;
}
@Override
public String toString() {
return "SaTokenInfo [tokenName=" + tokenName + ", tokenValue=" + tokenValue + ", isLogin=" + isLogin
+ ", loginId=" + loginId + ", loginKey=" + loginKey + ", tokenTimeout=" + tokenTimeout
+ ", sessionTimeout=" + sessionTimeout + ", tokenSessionTimeout=" + tokenSessionTimeout
+ ", tokenActivityTimeout=" + tokenActivityTimeout + "]";
}
}
@@ -0,0 +1,28 @@
package cn.dev33.satoken.stp;
import java.util.List;
/**
* 开放权限验证接口,方便重写
* @author kong
*/
public interface StpInterface {
/**
* 返回指定loginId所拥有的权限码集合
* @param loginId 账号id
* @param loginKey 具体的stp标识
* @return 该账号id具有的权限码集合
*/
public List<String> getPermissionList(Object loginId, String loginKey);
/**
* 返回指定loginId所拥有的角色标识集合
* @param loginId 账号id
* @param loginKey 具体的stp标识
* @return 该账号id具有的角色标识集合
*/
public List<String> getRoleList(Object loginId, String loginKey);
}
@@ -0,0 +1,22 @@
package cn.dev33.satoken.stp;
import java.util.ArrayList;
import java.util.List;
/**
* 对StpInterface接口默认的实现类
* @author kong
*/
public class StpInterfaceDefaultImpl implements StpInterface {
@Override
public List<String> getPermissionList(Object loginId, String loginKey) {
return new ArrayList<String>();
}
@Override
public List<String> getRoleList(Object loginId, String loginKey) {
return new ArrayList<String>();
}
}
@@ -0,0 +1,923 @@
package cn.dev33.satoken.stp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import cn.dev33.satoken.SaTokenManager;
import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.TokenSign;
import cn.dev33.satoken.util.SaTokenConsts;
import cn.dev33.satoken.util.SaTokenInsideUtil;
/**
* sa-token 权限验证,逻辑实现类
* <p>
* (stp = sa-token-permission 的缩写 )
* @author kong
*/
public class StpLogic {
/**
* 持久化的key前缀,多账号认证体系时以此值区分,比如:login、user、admin
*/
public String loginKey = "";
/**
* 初始化StpLogic, 并制定loginKey
* @param loginKey 账号标识
*/
public StpLogic(String loginKey) {
this.loginKey = loginKey;
}
// =================== 获取token 相关 ===================
/**
* 返回token名称
* @return 此StpLogic的token名称
*/
public String getTokenName() {
return getKeyTokenName();
}
/**
* 随机生成一个tokenValue
* @param loginId loginId
* @return 生成的tokenValue
*/
public String createTokenValue(Object loginId) {
// 去除掉所有逗号
return SaTokenManager.getSaTokenAction().createToken(loginId, loginKey).replaceAll(",", "");
}
/**
* 获取当前tokenValue
* @return 当前tokenValue
*/
public String getTokenValue(){
// 0. 获取相应对象
HttpServletRequest request = SaTokenManager.getSaTokenServlet().getRequest();
SaTokenConfig config = getConfig();
String keyTokenName = getTokenName();
String tokenValue = null;
// 1. 尝试从request里读取
if(request.getAttribute(SaTokenConsts.JUST_CREATED_SAVE_KEY) != null) {
tokenValue = String.valueOf(request.getAttribute(SaTokenConsts.JUST_CREATED_SAVE_KEY));
}
// 2. 尝试从请求体里面读取
if(tokenValue == null && config.getIsReadBody() == true){
tokenValue = request.getParameter(keyTokenName);
}
// 3. 尝试从header力读取
if(tokenValue == null && config.getIsReadHead() == true){
tokenValue = request.getHeader(keyTokenName);
}
// 4. 尝试从cookie里读取
if(tokenValue == null && config.getIsReadCookie() == true){
Cookie cookie = SaTokenManager.getSaTokenCookie().getCookie(request, keyTokenName);
if(cookie != null){
tokenValue = cookie.getValue();
}
}
// 5. 返回
return tokenValue;
}
/**
* 获取当前StpLogin的loginKey
* @return 当前StpLogin的loginKey
*/
public String getLoginKey(){
return loginKey;
}
/**
* 获取当前会话的token信息
* @return token信息
*/
public SaTokenInfo getTokenInfo() {
SaTokenInfo info = new SaTokenInfo();
info.tokenName = getTokenName();
info.tokenValue = getTokenValue();
info.isLogin = isLogin();
info.loginId = getLoginIdDefaultNull();
info.loginKey = getLoginKey();
info.tokenTimeout = getTokenTimeout();
info.sessionTimeout = getSessionTimeout();
info.tokenSessionTimeout = getTokenSessionTimeout();
info.tokenActivityTimeout = getTokenActivityTimeout();
return info;
}
// =================== 登录相关操作 ===================
/**
* 在当前会话上登录id
* @param loginId 登录id,建议的类型:(long | int | String
*/
public void setLoginId(Object loginId) {
// ------ 0、如果当前会话已经登录上了此LoginId,则立即返回
Object loggedId = getLoginIdDefaultNull();
if(loggedId != null && loggedId.toString().equals(loginId.toString())) {
return;
}
// ------ 1、获取相应对象
HttpServletRequest request = SaTokenManager.getSaTokenServlet().getRequest();
SaTokenConfig config = getConfig();
SaTokenDao dao = SaTokenManager.getSaTokenDao();
// ------ 2、生成一个token
String tokenValue = null;
// --- 如果允许并发登录
if(config.getAllowConcurrentLogin() == true) {
// 如果配置为共享token, 则尝试从session签名记录里取出token
if(config.getIsShare() == true) {
tokenValue = getTokenValueByLoginId(loginId);
}
} else {
// --- 如果不允许并发登录
// 如果此时[id-session]不为null,说明此账号在其他地正在登录,现在需要先把其它地的token标记为被顶下线
SaSession session = getSessionByLoginId(loginId, false);
if(session != null) {
List<String> tokenValueList = getTokenValueListByLoginId(loginId);
for (String token : tokenValueList) {
dao.updateValue(getKeyTokenValue(token), NotLoginException.BE_REPLACED); // 1. 将此token 标记为已顶替
clearLastActivity(token); // 2. 清理掉[token-最后操作时间]
session.removeTokenSign(token); // 3. 清理账号session上的token签名
}
}
}
// 如果至此,仍未成功创建tokenValue
if(tokenValue == null) {
tokenValue = createTokenValue(loginId);
}
// ------ 3. 获取[id-session] (如果还没有创建session, 则新建, 如果已经创建,则续期)
SaSession session = getSessionByLoginId(loginId, false);
if(session == null) {
session = getSessionByLoginId(loginId);
} else {
dao.updateSessionTimeout(session.getId(), config.getTimeout());
}
// 在session上记录token签名
session.addTokenSign(new TokenSign(tokenValue, SaTokenConsts.DEFAULT_LOGIN_DEVICE));
// ------ 4. 持久化其它数据
dao.setValue(getKeyTokenValue(tokenValue), String.valueOf(loginId), config.getTimeout()); // token -> uid
request.setAttribute(SaTokenConsts.JUST_CREATED_SAVE_KEY, tokenValue); // 将token保存到本次request里
setLastActivityToNow(tokenValue); // 写入 [最后操作时间]
if(config.getIsReadCookie() == true){ // cookie注入
SaTokenManager.getSaTokenCookie().addCookie(SaTokenManager.getSaTokenServlet().getResponse(), getTokenName(), tokenValue, "/", (int)config.getTimeout());
}
}
/**
* 当前会话注销登录
*/
public void logout() {
// 如果连token都没有,那么无需执行任何操作
String tokenValue = getTokenValue();
if(tokenValue == null) {
return;
}
// 如果打开了cookie模式,第一步,先把cookie清除掉
if(getConfig().getIsReadCookie() == true){
SaTokenManager.getSaTokenCookie().delCookie(SaTokenManager.getSaTokenServlet().getRequest(), SaTokenManager.getSaTokenServlet().getResponse(), getTokenName());
}
logoutByTokenValue(tokenValue);
}
/**
* 指定token的会话注销登录
* @param tokenValue 指定token
*/
public void logoutByTokenValue(String tokenValue) {
// 1. 清理掉[token-最后操作时间]
clearLastActivity(tokenValue);
// 2. 尝试清除token-id键值对 (先从db中获取loginId值,如果根本查不到loginId,那么无需继续操作 )
String loginId = SaTokenManager.getSaTokenDao().getValue(getKeyTokenValue(tokenValue));
if(loginId == null || NotLoginException.ABNORMAL_LIST.contains(loginId)) {
return;
}
SaTokenManager.getSaTokenDao().deleteKey(getKeyTokenValue(tokenValue));
// 2. 尝试清理账号session上的token签名 (如果为null或已被标记为异常, 那么无需继续执行 )
SaSession session = getSessionByLoginId(loginId, false);
if(session == null) {
return;
}
session.removeTokenSign(tokenValue);
// 3. 尝试注销session
session.logoutByTokenSignCountToZero();
}
/**
* 指定loginId的会话注销登录(踢人下线)
* <p> 当对方再次访问系统时,会抛出NotLoginException异常,场景值=-2
* @param loginId 账号id
*/
public void logoutByLoginId(Object loginId) {
// 先获取这个账号的[id-session], 如果为null,则不执行任何操作
SaSession session = getSessionByLoginId(loginId);
if(session == null) {
return;
}
// 循环token签名列表,开始删除相关信息
List<TokenSign> tokenSignList = session.getTokenSignList();
for (TokenSign tokenSign : tokenSignList) {
// 1. 获取token
String tokenValue = tokenSign.getValue();
// 2. 清理掉[token-最后操作时间]
clearLastActivity(tokenValue);
// 3. 标记:已被踢下线
SaTokenManager.getSaTokenDao().updateValue(getKeyTokenValue(tokenValue), NotLoginException.KICK_OUT); // 标记:已被踢下线
// 4. 清理账号session上的token签名
session.removeTokenSign(tokenValue);
}
// 尝试注销session
session.logoutByTokenSignCountToZero();
}
// 查询相关
/**
* 获取当前会话是否已经登录
* @return 是否已登录
*/
public boolean isLogin() {
// 判断条件:不为null,并且不在异常项集合里
return getLoginIdDefaultNull() != null;
}
/**
* 检验当前会话是否已经登录,如未登录,则抛出异常
*/
public void checkLogin() {
getLoginId();
}
/**
* 获取当前会话账号id, 如果未登录,则抛出异常
* @return 账号id
*/
public Object getLoginId() {
// 如果获取不到token,则抛出:无token
String tokenValue = getTokenValue();
if(tokenValue == null) {
throw NotLoginException.newInstance(loginKey, NotLoginException.NOT_TOKEN);
}
// 查找此token对应loginId, 则抛出:无效token
String loginId = SaTokenManager.getSaTokenDao().getValue(getKeyTokenValue(tokenValue));
if(loginId == null) {
throw NotLoginException.newInstance(loginKey, NotLoginException.INVALID_TOKEN);
}
// 如果是已经过期,则抛出已经过期
if(loginId.equals(NotLoginException.TOKEN_TIMEOUT)) {
throw NotLoginException.newInstance(loginKey, NotLoginException.TOKEN_TIMEOUT);
}
// 如果是已经被顶替下去了, 则抛出:已被顶下线
if(loginId.equals(NotLoginException.BE_REPLACED)) {
throw NotLoginException.newInstance(loginKey, NotLoginException.BE_REPLACED);
}
// 如果是已经被踢下线了, 则抛出:已被踢下线
if(loginId.equals(NotLoginException.KICK_OUT)) {
throw NotLoginException.newInstance(loginKey, NotLoginException.KICK_OUT);
}
// 检查是否已经 [临时过期],同时更新[最后操作时间]
checkActivityTimeout(tokenValue);
updateLastActivityToNow(tokenValue);
// 至此,返回loginId
return loginId;
}
/**
* 获取当前会话登录id, 如果未登录,则返回默认值
* @param <T> 返回类型
* @param defaultValue 默认值
* @return 登录id
*/
@SuppressWarnings("unchecked")
public <T>T getLoginId(T defaultValue) {
Object loginId = getLoginIdDefaultNull();
// 如果loginId为null,则返回默认值
if(loginId == null) {
return defaultValue;
}
// 开始尝试类型转换,只尝试三种类型:int、long、String
if(defaultValue instanceof Integer) {
return (T)Integer.valueOf(loginId.toString());
}
if(defaultValue instanceof Long) {
return (T)Long.valueOf(loginId.toString());
}
if(defaultValue instanceof String) {
return (T)loginId.toString();
}
return (T)loginId;
}
/**
* 获取当前会话登录id, 如果未登录,则返回null
* @return 账号id
*/
public Object getLoginIdDefaultNull() {
// 如果连token都是空的,则直接返回
String tokenValue = getTokenValue();
if(tokenValue == null) {
return null;
}
// loginId为null或者在异常项里面,均视为未登录
Object loginId = SaTokenManager.getSaTokenDao().getValue(getKeyTokenValue(tokenValue));
if(loginId == null || NotLoginException.ABNORMAL_LIST.contains(loginId)) {
return null;
}
// 如果已经[临时过期]
if(getTokenActivityTimeoutByToken(tokenValue) == SaTokenDao.NOT_VALUE_EXPIRE) {
return null;
}
// 执行到此,证明loginId已经是个正常的账号id了
return loginId;
}
/**
* 获取当前会话登录id, 并转换为String
* @return 账号id
*/
public String getLoginIdAsString() {
return String.valueOf(getLoginId());
}
/**
* 获取当前会话登录id, 并转换为int
* @return 账号id
*/
public int getLoginIdAsInt() {
// Object loginId = getLoginId();
// if(loginId instanceof Integer) {
// return (Integer)loginId;
// }
return Integer.valueOf(String.valueOf(getLoginId()));
}
/**
* 获取当前会话登录id, 并转换为long
* @return 账号id
*/
public long getLoginIdAsLong() {
// Object loginId = getLoginId();
// if(loginId instanceof Long) {
// return (Long)loginId;
// }
return Long.valueOf(String.valueOf(getLoginId()));
}
/**
* 获取指定token对应的登录id,如果未登录,则返回 null
* @param tokenValue token
* @return 登录id
*/
public Object getLoginIdByToken(String tokenValue) {
if(tokenValue != null) {
Object loginId = SaTokenManager.getSaTokenDao().getValue(getKeyTokenValue(tokenValue));
if(loginId != null) {
return loginId;
}
}
return null;
}
// =================== session相关 ===================
/**
* 获取指定key的session, 如果session尚未创建,isCreate=是否新建并返回
* @param sessionId sessionId
* @param isCreate 是否新建
* @return session对象
*/
public SaSession getSessionBySessionId(String sessionId, boolean isCreate) {
SaSession session = SaTokenManager.getSaTokenDao().getSession(sessionId);
if(session == null && isCreate) {
session = new SaSession(sessionId);
SaTokenManager.getSaTokenDao().saveSession(session, getConfig().getTimeout());
}
return session;
}
/**
* 获取指定loginId的session, 如果session尚未创建,isCreate=是否新建并返回
* @param loginId 账号id
* @param isCreate 是否新建
* @return SaSession
*/
public SaSession getSessionByLoginId(Object loginId, boolean isCreate) {
return getSessionBySessionId(getKeySession(loginId), isCreate);
}
/**
* 获取指定loginId的session,如果session尚未创建,则新建并返回
* @param loginId 账号id
* @return session会话
*/
public SaSession getSessionByLoginId(Object loginId) {
return getSessionByLoginId(loginId, true);
}
/**
* 获取当前会话的session, 如果session尚未创建,isCreate=是否新建并返回
* @param isCreate 是否新建
* @return 当前会话的session
*/
public SaSession getSession(boolean isCreate) {
return getSessionByLoginId(getLoginId(), isCreate);
}
/**
* 获取当前会话的session,如果session尚未创建,则新建并返回
* @return 当前会话的session
*/
public SaSession getSession() {
return getSession(true);
}
// =================== token专属session ===================
/**
* 获取指定token的专属session,如果session尚未创建,isCreate代表是否新建并返回
* @param tokenValue token值
* @param isCreate 是否新建
* @return session会话
*/
public SaSession getTokenSessionByToken(String tokenValue, boolean isCreate) {
return getSessionBySessionId(getKeyTokenSession(tokenValue), isCreate);
}
/**
* 获取指定token的专属session,如果session尚未创建,则新建并返回
* @param tokenValue token值
* @return session会话
*/
public SaSession getTokenSessionByToken(String tokenValue) {
return getSessionBySessionId(getKeyTokenSession(tokenValue), true);
}
/**
* 获取当前token的专属-session,如果session尚未创建,isCreate代表是否新建并返回
* @param isCreate 是否新建
* @return session会话
*/
public SaSession getTokenSession(boolean isCreate) {
// 如果配置了需要校验登录状态,则验证一下
if(getConfig().getTokenSessionCheckLogin()) {
checkLogin();
} else {
// 如果配置忽略token登录校验,则必须保证token不为null (token为null的时候随机创建一个)
String tokenValue = getTokenValue();
if(tokenValue == null || Objects.equals(tokenValue, "")) {
setLoginId(SaTokenInsideUtil.getMarking28());
}
}
// 返回这个token对应的专属session
return getSessionBySessionId(getKeyTokenSession(getTokenValue()), isCreate);
}
/**
* 获取当前token的专属-session,如果session尚未创建,则新建并返回
* @return session会话
*/
public SaSession getTokenSession() {
return getTokenSession(true);
}
// =================== [临时过期] 验证相关 ===================
/**
* 写入指定token的 [最后操作时间] 为当前时间戳
* @param tokenValue 指定token
*/
protected void setLastActivityToNow(String tokenValue) {
// 如果token == null 或者 设置了[永不过期], 则立即返回
if(tokenValue == null || getConfig().getActivityTimeout() == SaTokenDao.NEVER_EXPIRE) {
return;
}
// 将[最后操作时间]标记为当前时间戳
SaTokenManager.getSaTokenDao().setValue(getKeyLastActivityTime(tokenValue), String.valueOf(System.currentTimeMillis()), getConfig().getTimeout());
}
/**
* 清除指定token的 [最后操作时间]
* @param tokenValue 指定token
*/
protected void clearLastActivity(String tokenValue) {
// 如果token == null 或者 设置了[永不过期], 则立即返回
if(tokenValue == null || getConfig().getActivityTimeout() == SaTokenDao.NEVER_EXPIRE) {
return;
}
// 删除[最后操作时间]
SaTokenManager.getSaTokenDao().deleteKey(getKeyLastActivityTime(tokenValue));
// 清除标记
SaTokenManager.getSaTokenServlet().getRequest().removeAttribute(SaTokenConsts.TOKEN_ACTIVITY_TIMEOUT_CHECKED_KEY);
}
/**
* 检查指定token 是否已经[临时过期],如果已经过期则抛出异常
* @param tokenValue 指定token
*/
public void checkActivityTimeout(String tokenValue) {
// 如果token == null 或者 设置了[永不过期], 则立即返回
if(tokenValue == null || getConfig().getActivityTimeout() == SaTokenDao.NEVER_EXPIRE) {
return;
}
// 如果本次请求已经有了[检查标记], 则立即返回
HttpServletRequest request = SaTokenManager.getSaTokenServlet().getRequest();
if(request.getAttribute(SaTokenConsts.TOKEN_ACTIVITY_TIMEOUT_CHECKED_KEY) != null) {
return;
}
// ------------ 验证是否已经 [临时过期]
// 获取 [临时剩余时间]
long timeout = getTokenActivityTimeoutByToken(tokenValue);
// -1 代表此token已经被设置永不过期,无须继续验证
if(timeout == SaTokenDao.NEVER_EXPIRE) {
return;
}
// -2 代表已过期,抛出异常
if(timeout == SaTokenDao.NOT_VALUE_EXPIRE) {
throw NotLoginException.newInstance(loginKey, NotLoginException.TOKEN_TIMEOUT);
}
// --- 至此,验证已通过
// 打上[检查标记],标记一下当前请求已经通过验证,避免一次请求多次验证,造成不必要的性能消耗
request.setAttribute(SaTokenConsts.TOKEN_ACTIVITY_TIMEOUT_CHECKED_KEY, true);
}
/**
* 检查当前token 是否已经[临时过期],如果已经过期则抛出异常
*/
public void checkActivityTimeout() {
checkActivityTimeout(getTokenValue());
}
/**
* 续签指定token:(将 [最后操作时间] 更新为当前时间戳)
* @param tokenValue 指定token
*/
public void updateLastActivityToNow(String tokenValue) {
// 如果token == null 或者 设置了[永不过期], 则立即返回
if(tokenValue == null || getConfig().getActivityTimeout() == SaTokenDao.NEVER_EXPIRE) {
return;
}
SaTokenManager.getSaTokenDao().updateValue(getKeyLastActivityTime(tokenValue), String.valueOf(System.currentTimeMillis()));
}
/**
* 续签当前token:(将 [最后操作时间] 更新为当前时间戳)
* <h1>请注意: 即时token已经 [临时过期] 也可续签成功,
* 如果此场景下需要提示续签失败,可在此之前调用 checkActivityTimeout() 强制检查是否过期即可 </h1>
*/
public void updateLastActivityToNow() {
updateLastActivityToNow(getTokenValue());
}
// =================== 过期时间相关 ===================
/**
* 获取当前登录者的token剩余有效时间 (单位: 秒)
* @return token剩余有效时间
*/
public long getTokenTimeout() {
return SaTokenManager.getSaTokenDao().getTimeout(getKeyTokenValue(getTokenValue()));
}
/**
* 获取指定loginId的token剩余有效时间 (单位: 秒)
* @param loginId 指定loginId
* @return token剩余有效时间
*/
public long getTokenTimeoutByLoginId(Object loginId) {
return SaTokenManager.getSaTokenDao().getTimeout(getKeyTokenValue(getTokenValueByLoginId(loginId)));
}
/**
* 获取当前登录者的Session剩余有效时间 (单位: 秒)
* @return token剩余有效时间
*/
public long getSessionTimeout() {
return getSessionTimeoutByLoginId(getLoginIdDefaultNull());
}
/**
* 获取指定loginId的Session剩余有效时间 (单位: 秒)
* @param loginId 指定loginId
* @return token剩余有效时间
*/
public long getSessionTimeoutByLoginId(Object loginId) {
return SaTokenManager.getSaTokenDao().getSessionTimeout(getKeySession(loginId));
}
/**
* 获取当前token的专属Session剩余有效时间 (单位: 秒)
* @return token剩余有效时间
*/
public long getTokenSessionTimeout() {
return getTokenSessionTimeoutByTokenValue(getTokenValue());
}
/**
* 获取指定token的专属Session剩余有效时间 (单位: 秒)
* @param tokenValue 指定token
* @return token剩余有效时间
*/
public long getTokenSessionTimeoutByTokenValue(String tokenValue) {
return SaTokenManager.getSaTokenDao().getSessionTimeout(getKeyTokenSession(tokenValue));
}
/**
* 获取当前token[临时过期]剩余有效时间 (单位: 秒)
* @return token[临时过期]剩余有效时间
*/
public long getTokenActivityTimeout() {
return getTokenActivityTimeoutByToken(getTokenValue());
}
/**
* 获取指定token[临时过期]剩余有效时间 (单位: 秒)
* @param tokenValue 指定token
* @return token[临时过期]剩余有效时间
*/
public long getTokenActivityTimeoutByToken(String tokenValue) {
// 如果token为null , 则返回 -2
if(tokenValue == null) {
return SaTokenDao.NOT_VALUE_EXPIRE;
}
// 如果设置了永不过期, 则返回 -1
if(getConfig().getActivityTimeout() == SaTokenDao.NEVER_EXPIRE) {
return SaTokenDao.NEVER_EXPIRE;
}
// ------ 开始查询
// 获取相关数据
String keyLastActivityTime = getKeyLastActivityTime(tokenValue);
String lastActivityTimeString = SaTokenManager.getSaTokenDao().getValue(keyLastActivityTime);
// 查不到,返回-2
if(lastActivityTimeString == null) {
return SaTokenDao.NOT_VALUE_EXPIRE;
}
// 计算相差时间
long lastActivityTime = Long.valueOf(lastActivityTimeString);
long apartSecond = (System.currentTimeMillis() - lastActivityTime) / 1000;
long timeout = getConfig().getActivityTimeout() - apartSecond;
// 如果 < 0, 代表已经过期 ,返回-2
if(timeout < 0) {
return SaTokenDao.NOT_VALUE_EXPIRE;
}
return timeout;
}
// =================== 角色验证操作 ===================
/**
* 指定账号id是否含有角色标识
* @param loginId 账号id
* @param role 角色标识
* @return 是否含有指定角色标识
*/
public boolean hasRole(Object loginId, String role) {
List<String> roleList = SaTokenManager.getStpInterface().getRoleList(loginId, loginKey);
return !(roleList == null || roleList.contains(role) == false);
}
/**
* 当前账号id是否含有指定角色标识
* @param role 角色标识
* @return 是否含有指定角色标识
*/
public boolean hasRole(String role) {
return hasRole(getLoginId(), role);
}
/**
* 当前账号是否含有指定角色标识,没有就抛出异常
* @param role 角色标识
*/
public void checkRole(String role) {
if(hasRole(role) == false) {
throw new NotRoleException(role, this.loginKey);
}
}
/**
* 当前账号是否含有指定角色标识, [指定多个,必须全都有]
* @param roleArray 角色标识数组
*/
public void checkRoleAnd(String... roleArray){
Object loginId = getLoginId();
List<String> roleList = SaTokenManager.getStpInterface().getRoleList(loginId, loginKey);
for (String role : roleArray) {
if(roleList.contains(role) == false) {
throw new NotRoleException(role, this.loginKey); // 没有权限抛出异常
}
}
}
/**
* 当前账号是否含有指定角色标识, [指定多个,有一个就可以通过]
* @param roleArray 角色标识数组
*/
public void checkRoleOr(String... roleArray){
Object loginId = getLoginId();
List<String> roleList = SaTokenManager.getStpInterface().getRoleList(loginId, loginKey);
for (String role : roleArray) {
if(roleList.contains(role) == true) {
return; // 有的话提前退出
}
}
if(roleArray.length > 0) {
throw new NotRoleException(roleArray[0], this.loginKey); // 没有权限抛出异常
}
}
// =================== 权限验证操作 ===================
/**
* 指定账号id是否含有指定权限
* @param loginId 账号id
* @param permission 权限码
* @return 是否含有指定权限
*/
public boolean hasPermission(Object loginId, String permission) {
List<String> permissionList = SaTokenManager.getStpInterface().getPermissionList(loginId, loginKey);
return !(permissionList == null || permissionList.contains(permission) == false);
}
/**
* 当前账号id是否含有指定权限
* @param permission 权限码
* @return 是否含有指定权限
*/
public boolean hasPermission(String permission) {
return hasPermission(getLoginId(), permission);
}
/**
* 当前账号是否含有指定权限, 没有就抛出异常
* @param permission 权限码
*/
public void checkPermission(String permission) {
if(hasPermission(permission) == false) {
throw new NotPermissionException(permission, this.loginKey);
}
}
/**
* 当前账号是否含有指定权限, [指定多个,必须全都有]
* @param permissionArray 权限码数组
*/
public void checkPermissionAnd(String... permissionArray){
Object loginId = getLoginId();
List<String> permissionList = SaTokenManager.getStpInterface().getPermissionList(loginId, loginKey);
for (String permission : permissionArray) {
if(permissionList.contains(permission) == false) {
throw new NotPermissionException(permission, this.loginKey); // 没有权限抛出异常
}
}
}
/**
* 当前账号是否含有指定权限, [指定多个,有一个就可以通过]
* @param permissionArray 权限码数组
*/
public void checkPermissionOr(String... permissionArray){
Object loginId = getLoginId();
List<String> permissionList = SaTokenManager.getStpInterface().getPermissionList(loginId, loginKey);
for (String permission : permissionArray) {
if(permissionList.contains(permission) == true) {
return; // 有的话提前退出
}
}
if(permissionArray.length > 0) {
throw new NotPermissionException(permissionArray[0], this.loginKey); // 没有权限抛出异常
}
}
// =================== id 反查token 相关操作 ===================
/**
* 获取指定loginId的tokenValue
* <p> 在配置为允许并发登录时,此方法只会返回队列的最后一个token,
* 如果你需要返回此账号id的所有token,请调用 getTokenValueListByLoginId
* @param loginId 账号id
* @return token值
*/
public String getTokenValueByLoginId(Object loginId) {
List<String> tokenValueList = getTokenValueListByLoginId(loginId);
return tokenValueList.size() == 0 ? null : tokenValueList.get(tokenValueList.size() - 1);
}
/**
* 获取指定loginId的tokenValue
* @param loginId 账号id
* @return 此loginId的所有相关token
*/
public List<String> getTokenValueListByLoginId(Object loginId) {
// 如果session为null的话直接返回空集合
SaSession session = getSessionByLoginId(loginId, false);
if(session == null) {
return Arrays.asList();
}
// 遍历解析
List<TokenSign> tokenSignList = session.getTokenSignList();
List<String> tokenValueList = new ArrayList<>();
for (TokenSign tokenSign : tokenSignList) {
tokenValueList.add(tokenSign.getValue());
}
return tokenValueList;
}
// =================== 返回相应key ===================
/**
* 获取key:客户端 tokenName
* @return key
*/
public String getKeyTokenName() {
return getConfig().getTokenName();
}
/**
* 获取key tokenValue 持久化 token-id
* @param tokenValue token值
* @return key
*/
public String getKeyTokenValue(String tokenValue) {
return getConfig().getTokenName() + ":" + loginKey + ":token:" + tokenValue;
}
/**
* 获取key session 持久化
* @param loginId 账号id
* @return key
*/
public String getKeySession(Object loginId) {
return getConfig().getTokenName() + ":" + loginKey + ":session:" + loginId;
}
/**
* 获取key tokenValue的专属session
* @param tokenValue token值
* @return key
*/
public String getKeyTokenSession(String tokenValue) {
return getConfig().getTokenName() + ":" + loginKey + ":token-session:" + tokenValue;
}
/**
* 获取key: 指定token的最后操作时间 持久化
* @param tokenValue token值
* @return key
*/
public String getKeyLastActivityTime(String tokenValue) {
return getConfig().getTokenName() + ":" + loginKey + ":last-activity:" + tokenValue;
}
// =================== Bean对象代理 ===================
/**
* 返回配置对象
* @return 配置对象
*/
public SaTokenConfig getConfig() {
// 为什么再次代理一层? 为某些极端业务场景下[需要不同StpLogic不同配置]提供便利
return SaTokenManager.getConfig();
}
}
@@ -0,0 +1,395 @@
package cn.dev33.satoken.stp;
import java.util.List;
import cn.dev33.satoken.session.SaSession;
/**
* 一个默认的实现
* @author kong
*/
public class StpUtil {
/**
* 底层的 StpLogic 对象
*/
public static StpLogic stpLogic = new StpLogic("login");
// =================== 获取token 相关 ===================
/**
* 返回token名称
* @return 此StpLogic的token名称
*/
public static String getTokenName() {
return stpLogic.getTokenName();
}
/**
* 获取当前tokenValue
* @return 当前tokenValue
*/
public static String getTokenValue() {
return stpLogic.getTokenValue();
}
/**
* 获取当前StpLogin的loginKey
* @return 当前StpLogin的loginKey
*/
public static String getLoginKey(){
return stpLogic.getLoginKey();
}
/**
* 获取当前会话的token信息
* @return token信息
*/
public static SaTokenInfo getTokenInfo() {
return stpLogic.getTokenInfo();
}
// =================== 登录相关操作 ===================
/**
* 在当前会话上登录id
* @param loginId 登录id,建议的类型:(long | int | String
*/
public static void setLoginId(Object loginId) {
stpLogic.setLoginId(loginId);
}
/**
* 当前会话注销登录
*/
public static void logout() {
stpLogic.logout();
}
/**
* 指定token的会话注销登录
* @param tokenValue 指定token
*/
public static void logoutByTokenValue(String tokenValue) {
stpLogic.logoutByTokenValue(tokenValue);
}
/**
* 指定loginId的会话注销登录(踢人下线)
* <p> 当对方再次访问系统时,会抛出NotLoginException异常,场景值=-2
* @param loginId 账号id
*/
public static void logoutByLoginId(Object loginId) {
stpLogic.logoutByLoginId(loginId);
}
// 查询相关
/**
* 获取当前会话是否已经登录
* @return 是否已登录
*/
public static boolean isLogin() {
return stpLogic.isLogin();
}
/**
* 检验当前会话是否已经登录,如未登录,则抛出异常
*/
public static void checkLogin() {
stpLogic.checkLogin();
}
/**
* 获取当前会话账号id, 如果未登录,则抛出异常
* @return 账号id
*/
public static Object getLoginId() {
return stpLogic.getLoginId();
}
/**
* 获取当前会话登录id, 如果未登录,则返回默认值
* @param <T> 返回类型
* @param defaultValue 默认值
* @return 登录id
*/
public static <T> T getLoginId(T defaultValue) {
return stpLogic.getLoginId(defaultValue);
}
/**
* 获取当前会话登录id, 如果未登录,则返回null
* @return 账号id
*/
public static Object getLoginIdDefaultNull() {
return stpLogic.getLoginIdDefaultNull();
}
/**
* 获取当前会话登录id, 并转换为String
* @return 账号id
*/
public static String getLoginIdAsString() {
return stpLogic.getLoginIdAsString();
}
/**
* 获取当前会话登录id, 并转换为int
* @return 账号id
*/
public static int getLoginIdAsInt() {
return stpLogic.getLoginIdAsInt();
}
/**
* 获取当前会话登录id, 并转换为long
* @return 账号id
*/
public static long getLoginIdAsLong() {
return stpLogic.getLoginIdAsLong();
}
/**
* 获取指定token对应的登录id,如果未登录,则返回 null
* @param tokenValue token
* @return 登录id
*/
public static Object getLoginIdByToken(String tokenValue) {
return stpLogic.getLoginIdByToken(tokenValue);
}
// =================== session相关 ===================
/**
* 获取指定loginId的session, 如果session尚未创建,isCreate=是否新建并返回
* @param loginId 账号id
* @param isCreate 是否新建
* @return SaSession
*/
public static SaSession getSessionByLoginId(Object loginId, boolean isCreate) {
return stpLogic.getSessionByLoginId(loginId, isCreate);
}
/**
* 获取指定loginId的session,如果session尚未创建,则新建并返回
* @param loginId 账号id
* @return session会话
*/
public static SaSession getSessionByLoginId(Object loginId) {
return stpLogic.getSessionByLoginId(loginId);
}
/**
* 获取当前会话的session, 如果session尚未创建,isCreate=是否新建并返回
* @param isCreate 是否新建
* @return 当前会话的session
*/
public static SaSession getSession(boolean isCreate) {
return stpLogic.getSession(isCreate);
}
/**
* 获取当前会话的session,如果session尚未创建,则新建并返回
* @return 当前会话的session
*/
public static SaSession getSession() {
return stpLogic.getSession();
}
// =================== token专属session ===================
/**
* 获取指定token的专属session,如果session尚未创建,则新建并返回
* @param tokenValue token值
* @return session会话
*/
public static SaSession getTokenSessionByToken(String tokenValue) {
return stpLogic.getTokenSessionByToken(tokenValue);
}
/**
* 获取当前token的专属-session,如果session尚未创建,则新建并返回
* @return session会话
*/
public static SaSession getTokenSession() {
return stpLogic.getTokenSession();
}
// =================== [临时过期] 验证相关 ===================
/**
* 检查当前token 是否已经[临时过期],如果已经过期则抛出异常
*/
public static void checkActivityTimeout() {
stpLogic.checkActivityTimeout();
}
/**
* 续签当前token:(将 [最后操作时间] 更新为当前时间戳)
* <h1>请注意: 即时token已经 [临时过期] 也可续签成功,
* 如果此场景下需要提示续签失败,可在此之前调用 checkActivityTimeout() 强制检查是否过期即可 </h1>
*/
public static void updateLastActivityToNow() {
stpLogic.updateLastActivityToNow();
}
// =================== 过期时间相关 ===================
/**
* 获取当前登录者的token剩余有效时间 (单位: 秒)
* @return token剩余有效时间
*/
public static long getTokenTimeout() {
return stpLogic.getTokenTimeout();
}
/**
* 获取当前登录者的Session剩余有效时间 (单位: 秒)
* @return token剩余有效时间
*/
public static long getSessionTimeout() {
return stpLogic.getSessionTimeout();
}
/**
* 获取当前token的专属Session剩余有效时间 (单位: 秒)
* @return token剩余有效时间
*/
public static long getTokenSessionTimeout() {
return stpLogic.getTokenSessionTimeout();
}
/**
* 获取当前token[临时过期]剩余有效时间 (单位: 秒)
* @return token[临时过期]剩余有效时间
*/
public static long getTokenActivityTimeout() {
return stpLogic.getTokenActivityTimeout();
}
// =================== 角色验证操作 ===================
/**
* 指定账号id是否含有角色标识
* @param loginId 账号id
* @param role 角色标识
* @return 是否含有指定角色标识
*/
public static boolean hasRole(Object loginId, String role) {
return stpLogic.hasRole(loginId, role);
}
/**
* 当前账号id是否含有指定角色标识
* @param role 角色标识
* @return 是否含有指定角色标识
*/
public static boolean hasRole(String role) {
return stpLogic.hasRole(role);
}
/**
* 当前账号是否含有指定角色标识,没有就抛出异常
* @param role 角色标识
*/
public static void checkRole(String role) {
stpLogic.checkRole(role);
}
/**
* 当前账号是否含有指定角色标识, [指定多个,必须全都有]
* @param roleArray 角色标识数组
*/
public static void checkRoleAnd(String... roleArray){
stpLogic.checkRoleAnd(roleArray);
}
/**
* 当前账号是否含有指定角色标识, [指定多个,有一个就可以通过]
* @param roleArray 角色标识数组
*/
public static void checkRoleOr(String... roleArray){
stpLogic.checkRoleOr(roleArray);
}
// =================== 权限验证操作 ===================
/**
* 指定账号id是否含有指定权限
* @param loginId 账号id
* @param permissionCode 权限码
* @return 是否含有指定权限
*/
public static boolean hasPermission(Object loginId, String permissionCode) {
return stpLogic.hasPermission(loginId, permissionCode);
}
/**
* 当前账号id是否含有指定权限
* @param permissionCode 权限码
* @return 是否含有指定权限
*/
public static boolean hasPermission(String permissionCode) {
return stpLogic.hasPermission(permissionCode);
}
/**
* 当前账号是否含有指定权限, 没有就抛出异常
* @param permissionCode 权限码
*/
public static void checkPermission(String permissionCode) {
stpLogic.checkPermission(permissionCode);
}
/**
* 当前账号是否含有指定权限, [指定多个,必须全都有]
* @param permissionCodeArray 权限码数组
*/
public static void checkPermissionAnd(String... permissionCodeArray) {
stpLogic.checkPermissionAnd(permissionCodeArray);
}
/**
* 当前账号是否含有指定权限, [指定多个,有一个就可以通过]
* @param permissionCodeArray 权限码数组
*/
public static void checkPermissionOr(String... permissionCodeArray) {
stpLogic.checkPermissionOr(permissionCodeArray);
}
// =================== id 反查token 相关操作 ===================
/**
* 获取指定loginId的tokenValue
* <p> 在配置为允许并发登录时,此方法只会返回队列的最后一个token,
* 如果你需要返回此账号id的所有token,请调用 getTokenValueListByLoginId
* @param loginId 账号id
* @return token值
*/
public static String getTokenValueByLoginId(Object loginId) {
return stpLogic.getTokenValueByLoginId(loginId);
}
/**
* 获取指定loginId的tokenValue
* @param loginId 账号id
* @return 此loginId的所有相关token
*/
public static List<String> getTokenValueListByLoginId(Object loginId) {
return stpLogic.getTokenValueListByLoginId(loginId);
}
}
@@ -0,0 +1,57 @@
package cn.dev33.satoken.util;
import java.util.Timer;
import java.util.TimerTask;
/**
* 任务调度Util
* @author kong
*
*/
public class SaTaskUtil {
/**
* 延时指定毫秒执行一个函数
* @param fc 要执行的函数
* @param delay 延时的毫秒数
* @return timer任务对象
*/
public static Timer setTimeout(FunctionRunClass fc, int delay) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
fc.run();
timer.cancel();
}
}, delay);
return timer;
}
/**
* 延时delay毫秒,每隔period毫秒执行一个函数
* @param fc 要执行的函数
* @param delay 延时的毫秒数
* @param period 每隔多少毫秒执行一次
* @return timer任务对象
*/
public static Timer setInterval(FunctionRunClass fc, int delay, int period) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
fc.run();
}
}, delay, period);
return timer;
}
/**
* 封装一个内部类,便于操作
* @author kong
*/
public static interface FunctionRunClass{
public void run();
}
}
@@ -0,0 +1,45 @@
package cn.dev33.satoken.util;
/**
* 定义sa-token的所有常量
* @author kong
*
*/
public class SaTokenConsts {
/**
* sa-token 版本号
*/
public static final String VERSION_NO = "v1.8.0";
/**
* sa-token 开源地址
*/
public static final String GITHUB_URL = "https://github.com/click33/sa-token";
/**
* 如果token为本次请求新创建的,则以此字符串为key存储在当前request中 JUST_CREATED_SAVE_KEY
*/
public static final String JUST_CREATED_SAVE_KEY = "JUST_CREATED_SAVE_KEY_";
/**
* 如果本次请求已经验证过[无操作过期], 则以此值存储在当前request中 TOKEN_ACTIVITY_TIMEOUT_CHECKED_KEY
*/
public static final String TOKEN_ACTIVITY_TIMEOUT_CHECKED_KEY = "TOKEN_ACTIVITY_TIMEOUT_CHECKED_KEY_";
/**
* 在登录时,默认使用的设备名称
*/
public static final String DEFAULT_LOGIN_DEVICE = "default-device";
// /**
// * 在用一个字符串存储多个token时,所使用的分隔符
// */
// public static final String MULTIPLE_TOKEN_SEPARATOR = ",";
}
@@ -0,0 +1,52 @@
package cn.dev33.satoken.util;
import java.util.Random;
/**
* sa-token 工具类
* @author kong
*
*/
public class SaTokenInsideUtil {
/**
* 打印 sa-token 版本字符画
*/
public static void printSaToken() {
String str =
"____ ____ ___ ____ _ _ ____ _ _ \r\n" +
"[__ |__| __ | | | |_/ |___ |\\ | \r\n" +
"___] | | | |__| | \\_ |___ | \\| \r\n" +
"sa-token" + SaTokenConsts.VERSION_NO + " \r\n" +
"GitHub" + SaTokenConsts.GITHUB_URL; // + "\r\n";
System.out.println(str);
}
/**
* 生成指定长度的随机字符串
* @param length 字符串的长度
* @return 一个随机字符串
*/
public static String getRandomString(int length) {
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(62);
sb.append(str.charAt(number));
}
return sb.toString();
}
/**
* 以当前时间戳和随机int数字拼接一个随机字符串
* @return 随机字符串
*/
public static String getMarking28() {
return System.currentTimeMillis() + "" + new Random().nextInt(Integer.MAX_VALUE);
}
}
+12
View File
@@ -0,0 +1,12 @@
target/
node_modules/
bin/
.settings/
unpackage/
.classpath
.project
.factorypath
.idea/
+35
View File
@@ -0,0 +1,35 @@
<?xml version='1.0' encoding='utf-8'?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-parent</artifactId>
<version>1.8.0</version>
</parent>
<packaging>jar</packaging>
<name>sa-token-dao-redis-jackson</name>
<artifactId>sa-token-dao-redis-jackson</artifactId>
<description>sa-token integrate redis (to jackson)</description>
<dependencies>
<!-- sa-token-spring-boot-starter -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-spring-boot-starter</artifactId>
<version>1.8.0</version>
</dependency>
<!-- RedisTemplate 相关操作API -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.3.7.RELEASE</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,185 @@
package cn.dev33.satoken.dao;
import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.dev33.satoken.session.SaSession;
/**
* sa-token持久层的实现类, 基于redis (to jackson)
*/
@Component
public class SaTokenDaoRedisJackson implements SaTokenDao {
/**
* ObjectMapper对象 (以public作用于暴露出此对象,方便开发者二次更改配置)
*/
public ObjectMapper objectMapper;
/**
* string专用
*/
@Autowired
public StringRedisTemplate stringRedisTemplate;
/**
* SaSession专用
*/
public RedisTemplate<String, SaSession> sessionRedisTemplate;
@Autowired
public void setSessionRedisTemplate(RedisConnectionFactory connectionFactory) {
// 指定相应的序列化方案
StringRedisSerializer keySerializer = new StringRedisSerializer();
GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();
// 通过反射获取Mapper对象, 配置[忽略未知字段], 增强兼容性
try {
Field field = GenericJackson2JsonRedisSerializer.class.getDeclaredField("mapper");
field.setAccessible(true);
ObjectMapper objectMapper = (ObjectMapper) field.get(valueSerializer);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
this.objectMapper = objectMapper;
} catch (Exception e) {
System.err.println(e.getMessage());
}
// 构建RedisTemplate
RedisTemplate<String, SaSession> template = new RedisTemplate<String, SaSession>();
template.setConnectionFactory(connectionFactory);
template.setKeySerializer(keySerializer);
template.setHashKeySerializer(keySerializer);
template.setValueSerializer(valueSerializer);
template.setHashValueSerializer(valueSerializer);
template.afterPropertiesSet();
if(this.sessionRedisTemplate == null) {
this.sessionRedisTemplate = template;
}
}
/**
* 根据key获取value,如果没有,则返回空
*/
@Override
public String getValue(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
/**
* 写入指定key-value键值对,并设定过期时间(单位:秒)
*/
@Override
public void setValue(String key, String value, long timeout) {
// 判断是否为永不过期
if(timeout == SaTokenDao.NEVER_EXPIRE) {
stringRedisTemplate.opsForValue().set(key, value);
} else {
stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
}
}
/**
* 修改指定key-value键值对 (过期时间取原来的值)
*/
@Override
public void updateValue(String key, String value) {
long expire = getTimeout(key);
if(expire == SaTokenDao.NOT_VALUE_EXPIRE) { // -2 = 无此键
return;
}
this.setValue(key, value, expire);
}
/**
* 删除一个指定的key
*/
@Override
public void deleteKey(String key) {
stringRedisTemplate.delete(key);
}
/**
* 根据key获取value,如果没有,则返回空
*/
@Override
public long getTimeout(String key) {
return stringRedisTemplate.getExpire(key);
}
/**
* 修改指定key的剩余存活时间 (单位: 秒)
*/
@Override
public void updateTimeout(String key, long timeout) {
stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
/**
* 根据指定key的Session,如果没有,则返回空
*/
@Override
public SaSession getSession(String sessionId) {
return sessionRedisTemplate.opsForValue().get(sessionId);
}
/**
* 将指定Session持久化
*/
@Override
public void saveSession(SaSession session, long timeout) {
// 判断是否为永不过期
if(timeout == SaTokenDao.NEVER_EXPIRE) {
sessionRedisTemplate.opsForValue().set(session.getId(), session);
} else {
sessionRedisTemplate.opsForValue().set(session.getId(), session, timeout, TimeUnit.SECONDS);
}
}
/**
* 更新指定session
*/
@Override
public void updateSession(SaSession session) {
long expire = getSessionTimeout(session.getId());
if(expire == SaTokenDao.NOT_VALUE_EXPIRE) { // -2 = 无此键
return;
}
this.saveSession(session, expire);
}
/**
* 删除一个指定的session
*/
@Override
public void deleteSession(String sessionId) {
sessionRedisTemplate.delete(sessionId);
}
/**
* 获取指定SaSession的剩余存活时间 (单位: 秒)
*/
@Override
public long getSessionTimeout(String sessionId) {
return sessionRedisTemplate.getExpire(sessionId);
}
/**
* 修改指定SaSession的剩余存活时间 (单位: 秒)
*/
@Override
public void updateSessionTimeout(String sessionId, long timeout) {
sessionRedisTemplate.expire(sessionId, timeout, TimeUnit.SECONDS);
}
}
@@ -0,0 +1 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=cn.dev33.satoken.dao.SaTokenDaoRedisJackson
+12
View File
@@ -0,0 +1,12 @@
target/
node_modules/
bin/
.settings/
unpackage/
.classpath
.project
.factorypath
.idea/
+35
View File
@@ -0,0 +1,35 @@
<?xml version='1.0' encoding='utf-8'?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-parent</artifactId>
<version>1.8.0</version>
</parent>
<packaging>jar</packaging>
<name>sa-token-dao-redis</name>
<artifactId>sa-token-dao-redis</artifactId>
<description>sa-token integrate redis</description>
<dependencies>
<!-- sa-token-spring-boot-starter -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-spring-boot-starter</artifactId>
<version>1.8.0</version>
</dependency>
<!-- RedisTemplate 相关操作API -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.3.7.RELEASE</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,166 @@
package cn.dev33.satoken.dao;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import cn.dev33.satoken.session.SaSession;
/**
* sa-token持久层的实现类, 基于redis
*/
@Component
public class SaTokenDaoRedis implements SaTokenDao {
/**
* string专用
*/
@Autowired
public StringRedisTemplate stringRedisTemplate;
/**
* SaSession专用
*/
public RedisTemplate<String, SaSession> sessionRedisTemplate;
@Autowired
public void setSessionRedisTemplate(RedisConnectionFactory connectionFactory) {
// 指定相应的序列化方案
StringRedisSerializer keySerializer = new StringRedisSerializer();
JdkSerializationRedisSerializer valueSerializer = new JdkSerializationRedisSerializer();
// 构建RedisTemplate
RedisTemplate<String, SaSession> template = new RedisTemplate<String, SaSession>();
template.setConnectionFactory(connectionFactory);
template.setKeySerializer(keySerializer);
template.setHashKeySerializer(keySerializer);
template.setValueSerializer(valueSerializer);
template.setHashValueSerializer(valueSerializer);
template.afterPropertiesSet();
if(this.sessionRedisTemplate == null) {
this.sessionRedisTemplate = template;
}
}
/**
* 根据key获取value,如果没有,则返回空
*/
@Override
public String getValue(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
/**
* 写入指定key-value键值对,并设定过期时间(单位:秒)
*/
@Override
public void setValue(String key, String value, long timeout) {
// 判断是否为永不过期
if(timeout == SaTokenDao.NEVER_EXPIRE) {
stringRedisTemplate.opsForValue().set(key, value);
} else {
stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
}
}
/**
* 修改指定key-value键值对 (过期时间取原来的值)
*/
@Override
public void updateValue(String key, String value) {
long expire = getTimeout(key);
if(expire == SaTokenDao.NOT_VALUE_EXPIRE) { // -2 = 无此键
return;
}
this.setValue(key, value, expire);
}
/**
* 删除一个指定的key
*/
@Override
public void deleteKey(String key) {
stringRedisTemplate.delete(key);
}
/**
* 根据key获取value,如果没有,则返回空
*/
@Override
public long getTimeout(String key) {
return stringRedisTemplate.getExpire(key);
}
/**
* 修改指定key的剩余存活时间 (单位: 秒)
*/
@Override
public void updateTimeout(String key, long timeout) {
stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
/**
* 根据指定key的Session,如果没有,则返回空
*/
@Override
public SaSession getSession(String sessionId) {
return sessionRedisTemplate.opsForValue().get(sessionId);
}
/**
* 将指定Session持久化
*/
@Override
public void saveSession(SaSession session, long timeout) {
// 判断是否为永不过期
if(timeout == SaTokenDao.NEVER_EXPIRE) {
sessionRedisTemplate.opsForValue().set(session.getId(), session);
} else {
sessionRedisTemplate.opsForValue().set(session.getId(), session, timeout, TimeUnit.SECONDS);
}
}
/**
* 更新指定session
*/
@Override
public void updateSession(SaSession session) {
long expire = getSessionTimeout(session.getId());
if(expire == SaTokenDao.NOT_VALUE_EXPIRE) { // -2 = 无此键
return;
}
this.saveSession(session, expire);
}
/**
* 删除一个指定的session
*/
@Override
public void deleteSession(String sessionId) {
sessionRedisTemplate.delete(sessionId);
}
/**
* 获取指定SaSession的剩余存活时间 (单位: 秒)
*/
@Override
public long getSessionTimeout(String sessionId) {
return sessionRedisTemplate.getExpire(sessionId);
}
/**
* 修改指定SaSession的剩余存活时间 (单位: 秒)
*/
@Override
public void updateSessionTimeout(String sessionId, long timeout) {
sessionRedisTemplate.expire(sessionId, timeout, TimeUnit.SECONDS);
}
}
@@ -0,0 +1 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=cn.dev33.satoken.dao.SaTokenDaoRedis
+3 -1
View File
@@ -7,4 +7,6 @@ unpackage/
.classpath
.project
.idea/
.idea/
.factorypath
+33 -12
View File
@@ -25,26 +25,47 @@
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- 开发测试 -->
<!-- <dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-dev</artifactId>
<version>1.4.0</version>
</dependency> -->
<!-- sa-token 权限认证, 在线文档:http://sa-token.dev33.cn/ -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token</artifactId>
<version>1.4.0</version>
<artifactId>sa-token-spring-boot-starter</artifactId>
<version>1.8.0</version>
</dependency>
<!-- SpringBoot整合redis -->
<!-- sa-token整合redis (使用jdk默认序列化方式) -->
<!-- <dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-dao-redis</artifactId>
<version>1.8.0</version>
</dependency> -->
<!-- sa-token整合redis (使用jackson序列化方式) -->
<!-- <dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-dao-redis-jackson</artifactId>
<version>1.8.0</version>
</dependency> -->
<!-- 提供redis连接池 -->
<!-- <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency> -->
<!-- @ConfigurationProperties -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>RELEASE</version>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- hutool工具类,用来生成雪花算法唯一id -->
<!-- <dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.4</version>
</dependency> -->
</dependencies>
@@ -4,16 +4,13 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import cn.dev33.satoken.SaTokenManager;
import cn.dev33.satoken.spring.SaTokenSetup;
@SaTokenSetup // 必须有这个注解,用来标注加载sa-token
@SpringBootApplication
public class SaTokenDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SaTokenDemoApplication.class, args);
System.out.println("启动成功:sa-token配置如下:" + SaTokenManager.getConfig());
System.out.println("\n启动成功:sa-token配置如下:" + SaTokenManager.getConfig());
}
}
@@ -0,0 +1,21 @@
package com.pj.satoken;
import org.springframework.stereotype.Component;
import cn.dev33.satoken.action.SaTokenActionDefaultImpl;
/**
* 继承sa-token行为Bean默认实现, 重写部分逻辑
* @author kong
*
*/
@Component
public class MySaTokenAction extends SaTokenActionDefaultImpl {
// 重写token生成策略
// @Override
// public String createToken(Object loginId, String loginKey) {
// return SaTokenInsideUtil.getRandomString(60);
// }
}
@@ -1,13 +1,11 @@
package com.pj.satoken;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import cn.dev33.satoken.annotation.SaCheckInterceptor;
import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.interceptor.SaCheckInterceptor;
/**
* sa-token代码方式进行配置
@@ -15,18 +13,17 @@ import cn.dev33.satoken.config.SaTokenConfig;
@Configuration
public class MySaTokenConfig implements WebMvcConfigurer {
// 获取配置Bean (以代码的方式配置sa-token)
@Primary
@Bean(name="MySaTokenConfig")
// 获取配置Bean (以代码的方式配置sa-token, 此配置会覆盖yml中的配置 )
// @Primary
// @Bean(name="MySaTokenConfig")
public SaTokenConfig getSaTokenConfig() {
SaTokenConfig config = new SaTokenConfig();
config.setTokenName("satoken"); // token名称 (同时也是cookie名称)
config.setTimeout(30 * 24 * 60 * 60); // token有效期,单位s 默认30天
config.setIsShare(true); // 在多人登录同一账号时,是否共享会话 (为true时共用一个,为false时新登录挤掉旧登录)
config.setIsReadBody(true); // 是否尝试从请求体里读取token
config.setIsReadHead(true); // 是否尝试从header里读取token
config.setIsReadCookie(true); // 是否尝试从cookie里读取token
config.setIsV(true); // 是否在初始化配置时打印版本字符画
config.setActivityTimeout(-1); // token临时有效期 (指定时间内无操作就视为token过期) 单位: 秒
config.setAllowConcurrentLogin(true); // 是否允许同一账号并发登录 (为true时允许一起登录, 为false时新登录挤掉旧登录)
config.setIsShare(true); // 在多人登录同一账号时,是否共用一个token (为true时所有登录共用一个token, 为false时每次登录新建一个token)
config.setTokenStyle("uuid"); // token风格
return config;
}
@@ -1,91 +0,0 @@
package com.pj.satoken;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
// import org.springframework.stereotype.Component;
import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.session.SaSession;
/**
* sa-token持久层的实现类 , 基于redis
*/
// @Component // 打开此注解,保证此类被springboot扫描,即可完成sa-token与redis的集成
public class SaTokenDaoRedis implements SaTokenDao {
// string专用
@Autowired
StringRedisTemplate stringRedisTemplate;
// SaSession专用
RedisTemplate<String, SaSession> redisTemplate;
@Autowired
@SuppressWarnings({ "rawtypes", "unchecked" })
public void setRedisTemplate(RedisTemplate redisTemplate) {
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
this.redisTemplate = redisTemplate;
}
// 根据key获取value ,如果没有,则返回空
@Override
public String getValue(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
// 写入指定key-value键值对,并设定过期时间(单位:秒)
@Override
public void setValue(String key, String value, long timeout) {
stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
}
// 删除一个指定的key
@Override
public void delKey(String key) {
stringRedisTemplate.delete(key);
}
// 根据指定key的session,如果没有,则返回空
@Override
public SaSession getSaSession(String sessionId) {
return redisTemplate.opsForValue().get(sessionId);
}
// 将指定session持久化
@Override
public void saveSaSession(SaSession session, long timeout) {
redisTemplate.opsForValue().set(session.getId(), session, timeout, TimeUnit.SECONDS);
}
// 更新指定session
@Override
public void updateSaSession(SaSession session) {
long expire = redisTemplate.getExpire(session.getId());
if(expire == -2) { // -2 = 无此键
return;
}
redisTemplate.opsForValue().set(session.getId(), session, expire, TimeUnit.SECONDS);
}
// 删除一个指定的session
@Override
public void delSaSession(String sessionId) {
redisTemplate.delete(sessionId);
}
}
@@ -8,15 +8,17 @@ import org.springframework.stereotype.Component;
import cn.dev33.satoken.stp.StpInterface;
/**
* 自定义权限验证接口扩展
* 自定义权限验证接口扩展
*/
@Component // 打开此注解,保证此类被springboot扫描,即可完成sa-token的自定义权限验证扩展
public class StpInterfaceImpl implements StpInterface {
// 返回一个账号所拥有的权限码集合
/**
* 返回一个账号所拥有的权限码集合
*/
@Override
public List<Object> getPermissionCodeList(Object login_id, String login_key) {
List<Object> list = new ArrayList<Object>(); // 本list仅做模拟,实际项目中要根据具体业务逻辑来查询权限
public List<String> getPermissionList(Object login_id, String login_key) {
List<String> list = new ArrayList<String>(); // 本list仅做模拟,实际项目中要根据具体业务逻辑来查询权限
list.add("101");
list.add("user-add");
list.add("user-delete");
@@ -26,4 +28,15 @@ public class StpInterfaceImpl implements StpInterface {
return list;
}
/**
* 返回一个账号所拥有的角色标识集合
*/
@Override
public List<String> getRoleList(Object loginId, String loginKey) {
List<String> list = new ArrayList<String>(); // 本list仅做模拟,实际项目中要根据具体业务逻辑来查询角色
list.add("admin");
list.add("super-admin");
return list;
}
}
@@ -11,6 +11,7 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
/**
* 全局异常处理
@@ -24,6 +25,9 @@ public class GlobalException {
}
// 全局异常拦截(拦截项目中的所有异常)
@ExceptionHandler
public AjaxJson handlerException(Exception e, HttpServletRequest request, HttpServletResponse response)
@@ -35,7 +39,11 @@ public class GlobalException {
// 不同异常返回不同状态码
AjaxJson aj = null;
if (e instanceof NotLoginException) { // 如果是未登录异常
aj = AjaxJson.getNotLogin();
NotLoginException ee = (NotLoginException) e;
aj = AjaxJson.getNotLogin().setMsg(ee.getMessage());
} else if(e instanceof NotRoleException) { // 如果是角色异常
NotRoleException ee = (NotRoleException) e;
aj = AjaxJson.getNotJur("无此角色:" + ee.getRole());
} else if(e instanceof NotPermissionException) { // 如果是权限异常
NotPermissionException ee = (NotPermissionException) e;
aj = AjaxJson.getNotJur("无此权限:" + ee.getCode());
@@ -50,5 +58,41 @@ public class GlobalException {
// response.setContentType("application/json; charset=utf-8"); // http说明,我要返回JSON对象
// response.getWriter().print(new ObjectMapper().writeValueAsString(aj));
}
// 全局异常拦截(拦截项目中的NotLoginException异常)
// @ExceptionHandler(NotLoginException.class)
// public AjaxJson handlerNotLoginException(NotLoginException nle, HttpServletRequest request, HttpServletResponse response)
// throws Exception {
//
// // 打印堆栈,以供调试
// nle.printStackTrace();
//
// // 判断场景值,定制化异常信息
// String message = "";
// if(nle.getType().equals(NotLoginException.NOT_TOKEN)) {
// message = "未提供token";
// }
// else if(nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
// message = "token无效";
// }
// else if(nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
// message = "token已过期";
// }
// else if(nle.getType().equals(NotLoginException.BE_REPLACED)) {
// message = "token已被顶下线";
// }
// else if(nle.getType().equals(NotLoginException.KICK_OUT)) {
// message = "token已被踢下线";
// }
// else {
// message = "当前会话未登录";
// }
//
// // 返回给前端
// return AjaxJson.getError(message);
// }
}
@@ -1,12 +1,19 @@
package com.pj.test;
import java.util.Date;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.session.SaSessionCustomUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
/**
@@ -18,6 +25,7 @@ import cn.dev33.satoken.stp.StpUtil;
@RequestMapping("/test/")
public class TestController {
// 测试登录接口, 浏览器访问: http://localhost:8081/test/login
@RequestMapping("login")
public AjaxJson login(@RequestParam(defaultValue="10001") String id) {
@@ -25,31 +33,53 @@ public class TestController {
System.out.println("当前会话的token" + StpUtil.getTokenValue());
System.out.println("当前是否登录:" + StpUtil.isLogin());
System.out.println("当前登录账号:" + StpUtil.getLoginIdDefaultNull());
StpUtil.setLoginId(id); // 在当前会话登录此账号
System.out.println("登录成功");
System.out.println("当前是否登录:" + StpUtil.isLogin());
System.out.println("当前登录账号:" + StpUtil.getLoginId());
System.out.println("当前登录账号:" + StpUtil.getLoginIdAsInt()); // 获取登录id并转为int
// StpUtil.logout();
// System.out.println("注销登录");
// System.out.println("当前是否登录:" + StpUtil.isLogin());
// System.out.println("当前登录账号:" + StpUtil.getLoginIdDefaultNull());
// StpUtil.setLoginId(id); // 在当前会话登录此账号
// System.out.println("根据token找登录id" + StpUtil.getLoginIdByToken(StpUtil.getTokenValue()));
System.out.println("当前token信息:" + StpUtil.getTokenInfo()); // 获取登录id并转为int
System.out.println("当前登录账号:" + StpUtil.getLoginIdDefaultNull());
// System.out.println("当前token信息:" + StpUtil.getTokenInfo());
return AjaxJson.getSuccess();
}
// 测试权限接口 浏览器访问: http://localhost:8081/test/jur
@RequestMapping("jur")
public AjaxJson jur() {
// 测试退出登录 浏览器访问: http://localhost:8081/test/logout
@RequestMapping("logout")
public AjaxJson logout() {
StpUtil.logout();
// StpUtil.logoutByLoginId(10001);
return AjaxJson.getSuccess();
}
// 测试角色接口, 浏览器访问: http://localhost:8081/test/testRole
@RequestMapping("testRole")
public AjaxJson testRole() {
System.out.println("======================= 进入方法,测试角色接口 ========================= ");
System.out.println("是否具有角色标识 user " + StpUtil.hasRole("user"));
System.out.println("是否具有角色标识 admin " + StpUtil.hasRole("admin"));
System.out.println("没有admin权限就抛出异常");
StpUtil.checkRole("admin");
System.out.println("在【admin、user】中只要拥有一个就不会抛出异常");
StpUtil.checkRoleOr("admin", "user");
System.out.println("在【admin、user】中必须全部拥有才不会抛出异常");
StpUtil.checkRoleAnd("admin", "user");
System.out.println("角色测试通过");
return AjaxJson.getSuccess();
}
// 测试权限接口, 浏览器访问: http://localhost:8081/test/testJur
@RequestMapping("testJur")
public AjaxJson testJur() {
System.out.println("======================= 进入方法,测试权限接口 ========================= ");
System.out.println("是否具有权限101" + StpUtil.hasPermission(101));
System.out.println("是否具有权限101" + StpUtil.hasPermission("101"));
System.out.println("是否具有权限user-add" + StpUtil.hasPermission("user-add"));
System.out.println("是否具有权限article-get" + StpUtil.hasPermission("article-get"));
@@ -69,14 +99,15 @@ public class TestController {
// 测试会话session接口, 浏览器访问: http://localhost:8081/test/session
@RequestMapping("session")
public AjaxJson session() {
public AjaxJson session() throws JsonProcessingException {
System.out.println("======================= 进入方法,测试会话session接口 ========================= ");
System.out.println("当前是否登录:" + StpUtil.isLogin());
System.out.println("当前登录账号session的id" + StpUtil.getSession().getId());
System.out.println("当前登录账号session的id" + StpUtil.getSession().getId());
System.out.println("测试取值name" + StpUtil.getSession().getAttribute("name"));
StpUtil.getSession().setAttribute("name", "张三"); // 写入一个值
StpUtil.getSession().setAttribute("name", new Date()); // 写入一个值
System.out.println("测试取值name" + StpUtil.getSession().getAttribute("name"));
System.out.println( new ObjectMapper().writeValueAsString(StpUtil.getSession()));
return AjaxJson.getSuccess();
}
@@ -93,15 +124,31 @@ public class TestController {
return AjaxJson.getSuccess();
}
// ----------
// 测试token专属session 浏览器访问: http://localhost:8081/test/getTokenSession
@RequestMapping("getTokenSession")
public AjaxJson getTokenSession() {
System.out.println("======================= 进入方法,测试会话session接口 ========================= ");
System.out.println("当前是否登录:" + StpUtil.isLogin());
System.out.println("当前token专属session: " + StpUtil.getTokenSession().getId());
System.out.println("测试取值name" + StpUtil.getTokenSession().getAttribute("name"));
StpUtil.getTokenSession().setAttribute("name", "张三"); // 写入一个值
System.out.println("测试取值name" + StpUtil.getTokenSession().getAttribute("name"));
return AjaxJson.getSuccess();
}
// 打印当前token信息, 浏览器访问: http://localhost:8081/test/tokenInfo
@RequestMapping("tokenInfo")
public AjaxJson tokenInfo() {
System.out.println("======================= 进入方法,打印当前token信息 ========================= ");
System.out.println(StpUtil.getTokenInfo());
return AjaxJson.getSuccess();
SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
System.out.println(tokenInfo);
return AjaxJson.getSuccessData(tokenInfo);
}
// 测试注解式鉴权, 浏览器访问: http://localhost:8081/test/atCheck
@SaCheckLogin // 注解式鉴权:当前会话必须登录才能通过
@SaCheckPermission("user-add") // 注解式鉴权:当前会话必须具有指定权限才能通过
@@ -109,13 +156,46 @@ public class TestController {
public AjaxJson atCheck() {
System.out.println("======================= 进入方法,测试注解鉴权接口 ========================= ");
System.out.println("只有通过注解鉴权,才能进入此方法");
StpUtil.checkActivityTimeout();
StpUtil.updateLastActivityToNow();
return AjaxJson.getSuccess();
}
@SaCheckLogin // 注解式鉴权:当前会话必须登录才能通过
@RequestMapping("getInfo")
public AjaxJson getInfo() {
// 测试注解式鉴权 浏览器访问: http://localhost:8081/test/atJurOr
@RequestMapping("atJurOr")
@SaCheckPermission(value = {"user-add", "user-all", "user-delete"}, mode = SaMode.OR) // 注解式鉴权:只要具有其中一个权限即可通过校验
public AjaxJson atJurOr() {
return AjaxJson.getSuccessData("用户信息");
}
// [活动时间] 续签: http://localhost:8081/test/rene
@RequestMapping("rene")
public AjaxJson rene() {
StpUtil.checkActivityTimeout();
StpUtil.updateLastActivityToNow();
return AjaxJson.getSuccess("续签成功");
}
// 测试踢人下线 浏览器访问: http://localhost:8081/test/kickOut
@RequestMapping("kickOut")
public AjaxJson kickOut() {
// 先登录上
StpUtil.setLoginId(10001);
// 踢下线
StpUtil.logoutByLoginId(10001);
// 再尝试获取
StpUtil.getLoginId();
// 返回
return AjaxJson.getSuccess();
}
// 测试 浏览器访问: http://localhost:8081/test/test
@RequestMapping("test")
public AjaxJson test() {
StpUtil.getTokenSession().logout();
return AjaxJson.getSuccess();
}
}
@@ -7,20 +7,18 @@ spring:
sa-token:
# token名称 (同时也是cookie名称)
token-name: satoken
# token有效期,单位s 默认30天
# token有效期,单位s 默认30天, -1代表永不过期
timeout: 2592000
# 在多人登录同一账号时,是否共享会话 (为true时共用一个,为false时新登录挤掉旧登录)
# token临时有效期 (指定时间内无操作就视为token过期) 单位: 秒
activity-timeout: -1
# 是否允许同一账号并发登录 (为true时允许一起登录, 为false时新登录挤掉旧登录)
allow-concurrent-login: true
# 在多人登录同一账号时,是否共用一个token (为true时所有登录共用一个token, 为false时每次登录新建一个token)
is-share: true
# 是否尝试从请求体里读取token
is-read-body: true
# 是否尝试从header里读取token
is-read-head: true
# 是否尝试从cookie里读取token
is-read-cookie: true
# 是否在初始化配置时打印版本字符画
is-v: true
# token风格
token-style: uuid
# redis配置
redis:
# Redis数据库索引(默认为0
@@ -1,87 +0,0 @@
package cn.dev33.satoken;
import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.config.SaTokenConfigFactory;
import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.dao.SaTokenDaoDefault;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpInterfaceDefaultImpl;
import cn.dev33.satoken.util.SaTokenInsideUtil;
/**
* 管理sa-token所有对象
* @author kong
*
*/
public class SaTokenManager {
/**
* 配置文件 Bean
*/
private static SaTokenConfig config;
public static SaTokenConfig getConfig() {
if (config == null) {
initConfig();
}
return config;
}
public static void setConfig(SaTokenConfig config) {
SaTokenManager.config = config;
if(config.getIsV()) {
SaTokenInsideUtil.printSaToken();
}
}
public synchronized static void initConfig() {
if (config == null) {
setConfig(SaTokenConfigFactory.createConfig());
}
}
/**
* 持久化 Bean
*/
public static SaTokenDao dao;
public static SaTokenDao getDao() {
if (dao == null) {
initDao();
}
return dao;
}
public static void setDao(SaTokenDao dao) {
SaTokenManager.dao = dao;
}
public synchronized static void initDao() {
if (dao == null) {
setDao(new SaTokenDaoDefault());
}
}
/**
* 权限认证 Bean
*/
public static StpInterface stp;
public static StpInterface getStp() {
if (stp == null) {
initStp();
}
return stp;
}
public static void setStp(StpInterface stp) {
SaTokenManager.stp = stp;
}
public synchronized static void initStp() {
if (stp == null) {
setStp(new StpInterfaceDefaultImpl());
}
}
}
@@ -1,138 +0,0 @@
package cn.dev33.satoken.config;
/**
* sa-token 总配置类
* @author kong
*
*/
public class SaTokenConfig {
private String tokenName = "satoken"; // token名称 (同时也是cookie名称)
private long timeout = 30 * 24 * 60 * 60; // token有效期,单位s 默认30天
private Boolean isShare = true; // 在多人登录同一账号时,是否共享会话 (为true时共用一个,为false时新登录挤掉旧登录)
private Boolean isReadBody = true; // 是否尝试从请求体里读取token
private Boolean isReadHead = true; // 是否尝试从header里读取token
private Boolean isReadCookie = true; // 是否尝试从cookie里读取token
private Boolean isV = true; // 是否在初始化配置时打印版本字符画
/**
* @return tokenName
*/
public String getTokenName() {
return tokenName;
}
/**
* @param tokenName 要设置的 tokenName
*/
public void setTokenName(String tokenName) {
this.tokenName = tokenName;
}
/**
* @return timeout
*/
public long getTimeout() {
return timeout;
}
/**
* @param timeout 要设置的 timeout
*/
public void setTimeout(long timeout) {
this.timeout = timeout;
}
/**
* @return isShare
*/
public Boolean getIsShare() {
return isShare;
}
/**
* @param isShare 要设置的 isShare
*/
public void setIsShare(Boolean isShare) {
this.isShare = isShare;
}
/**
* @return isReadCookie
*/
public Boolean getIsReadCookie() {
return isReadCookie;
}
/**
* @param isReadCookie 要设置的 isReadCookie
*/
public void setIsReadCookie(Boolean isReadCookie) {
this.isReadCookie = isReadCookie;
}
/**
* @return isReadHead
*/
public Boolean getIsReadHead() {
return isReadHead;
}
/**
* @param isReadHead 要设置的 isReadHead
*/
public void setIsReadHead(Boolean isReadHead) {
this.isReadHead = isReadHead;
}
/**
* @return isReadBody
*/
public Boolean getIsReadBody() {
return isReadBody;
}
/**
* @param isReadBody 要设置的 isReadBody
*/
public void setIsReadBody(Boolean isReadBody) {
this.isReadBody = isReadBody;
}
/**
* @return isV
*/
public Boolean getIsV() {
return isV;
}
/**
* @param isV 要设置的 isV
*/
public void setIsV(Boolean isV) {
this.isV = isV;
}
@Override
public String toString() {
return "SaTokenConfig [tokenName=" + tokenName + ", timeout=" + timeout + ", isShare=" + isShare
+ ", isReadBody=" + isReadBody + ", isReadHead=" + isReadHead + ", isReadCookie=" + isReadCookie
+ ", isV=" + isV + "]";
}
}
@@ -1,63 +0,0 @@
package cn.dev33.satoken.dao;
import cn.dev33.satoken.session.SaSession;
/**
* sa-token持久层的接口
* @author kong
*
*/
public interface SaTokenDao {
/**
* 根据key获取value ,如果没有,则返回空
* @param key 键名称
* @return value
*/
public String getValue(String key);
/**
* 写入指定key-value键值对,并设定过期时间 (单位:秒)
* @param key 键名称
* @param value 值
* @param timeout 过期时间,单位:s
*/
public void setValue(String key, String value, long timeout);
/**
* 删除一个指定的key
* @param key 键名称
*/
public void delKey(String key);
/**
* 根据指定key的session,如果没有,则返回空
* @param sessionId 键名称
* @return SaSession
*/
public SaSession getSaSession(String sessionId);
/**
* 将指定session持久化
* @param session 要保存的session对象
* @param timeout 过期时间,单位: s
*/
public void saveSaSession(SaSession session, long timeout);
/**
* 更新指定session
* @param session 要更新的session对象
*/
public void updateSaSession(SaSession session);
/**
* 删除一个指定的session
* @param sessionId sessionId
*/
public void delSaSession(String sessionId);
}
@@ -1,64 +0,0 @@
package cn.dev33.satoken.dao;
import java.util.HashMap;
import java.util.Map;
import cn.dev33.satoken.session.SaSession;
/**
* sa-token持久层默认的实现类 , 基于内存Map
* @author kong
*
*/
public class SaTokenDaoDefault implements SaTokenDao {
/**
* 所有数据集合
*/
Map<String, Object> dataMap = new HashMap<String, Object>();
@Override
public String getValue(String key) {
return (String)dataMap.get(key);
}
@Override
public void setValue(String key, String value, long timeout) {
dataMap.put(key, value);
}
@Override
public void delKey(String key) {
dataMap.remove(key);
}
@Override
public SaSession getSaSession(String sessionId) {
return (SaSession)dataMap.get(sessionId);
}
@Override
public void saveSaSession(SaSession session, long timeout) {
dataMap.put(session.getId(), session);
}
@Override
public void updateSaSession(SaSession session) {
// 无动作
}
@Override
public void delSaSession(String sessionId) {
dataMap.remove(sessionId);
}
}
@@ -1,48 +0,0 @@
package cn.dev33.satoken.exception;
import cn.dev33.satoken.stp.StpUtil;
/**
* 没有登陆抛出的异常
* @author kong
*
*/
public class NotLoginException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 6806129545290130142L;
/**
* login_key
*/
private String loginKey;
/**
* 获得login_key
* @return login_key
*/
public String getLoginKey() {
return loginKey;
}
/**
* 创建一个
*/
public NotLoginException() {
this(StpUtil.stpLogic.loginKey);
}
/**
* 创建一个
* @param loginKey login_key
*/
public NotLoginException(String loginKey) {
// 这里到底要不要拼接上login_key呢?纠结
super("当前会话未登录");
this.loginKey = loginKey;
}
}
@@ -1,151 +0,0 @@
package cn.dev33.satoken.session;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import cn.dev33.satoken.SaTokenManager;
/**
* session会话
* @author kong
*
*/
public class SaSession implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 会话id
*/
private String id;
/**
* 当前会话创建时间
*/
private long createTime;
/**
* 当前会话键值对
*/
private Map<String, Object> dataMap;
/**
* 构建一个 session对象
* @param id
*/
public SaSession(String id) {
this.id = id;
this.createTime = System.currentTimeMillis();
this.dataMap = new HashMap<String, Object>();
}
/**
* 获取会话id
* @return id
*/
public String getId() {
return id;
}
/**
* 返回当前会话创建时间
* @return 时间戳
*/
public long getCreateTime() {
return createTime;
}
/**
* 写入一个值
* @param key 名称
* @param value 值
*/
public void setAttribute(String key, Object value) {
dataMap.put(key, value);
update();
}
/**
* 取出一个值
* @param key 名称
* @return 值
*/
public Object getAttribute(String key) {
return dataMap.get(key);
}
/**
* 取值,并指定取不到值时的默认值
* @param key 名称
* @param defaultValue 取不到值的时候返回的默认值
* @return value
*/
public Object getAttribute(String key, Object defaultValue) {
Object value = getAttribute(key);
if(value != null) {
return value;
}
return defaultValue;
}
/**
* 移除一个值
* @param key 要移除的值的名字
*/
public void removeAttribute(String key) {
dataMap.remove(key);
update();
}
/**
* 清空所有值
*/
public void clearAttribute() {
dataMap.clear();
update();
}
/**
* 是否含有指定key
* @param key 是否含有指定值
* @return 是否含有
*/
public boolean containsAttribute(String key) {
return dataMap.keySet().contains(key);
}
/**
* 返回当前session会话所有key
* @return 所有值的key列表
*/
public Set<String> getAttributeKeys() {
return dataMap.keySet();
}
/**
* 获取数据集合(如果更新map里的值,请调用session.update()方法避免数据过时
* @return 返回底层储存值的map对象
*/
public Map<String, Object> getDataMap() {
return dataMap;
}
/**
* 将这个session从持久库更新一下
*/
public void update() {
SaTokenManager.getDao().updateSaSession(this);
}
// /** 注销会话(注销后,此session会话将不再存储服务器上) */
// public void logout() {
// SaTokenManager.getDao().delSaSession(this.id);
// }
}
@@ -1,60 +0,0 @@
package cn.dev33.satoken.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import cn.dev33.satoken.SaTokenManager;
import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.stp.StpInterface;
/**
* 与SpringBoot集成, 保证此类被扫描,即可完成sa-token与SpringBoot的集成
* @author kong
*
*/
@Component
public class SpringSaToken {
/**
* 获取配置Bean
* @return
*/
@Bean
@ConfigurationProperties(prefix="spring.sa-token")
public SaTokenConfig getSaTokenConfig() {
return new SaTokenConfig();
}
/**
* 注入配置Bean
* @param saTokenConfig .
*/
@Autowired
public void setConfig(SaTokenConfig saTokenConfig){
SaTokenManager.setConfig(saTokenConfig);
}
/**
* 注入持久化Bean
* @param dao .
*/
@Autowired(required = false)
public void setDao(SaTokenDao dao){
SaTokenManager.setDao(dao);
}
/**
* 注入权限认证Bean
* @param stp .
*/
@Autowired(required = false)
public void setStp(StpInterface stp){
SaTokenManager.setStp(stp);
}
}
@@ -1,20 +0,0 @@
package cn.dev33.satoken.stp;
import java.util.List;
/**
* 开放权限验证接口,方便重写
* @author kong
*/
public interface StpInterface {
/**
* 返回指定login_id所拥有的权限码集合
* @param loginId 账号id
* @param loginKey 具体的stp标识
* @return
*/
public List<Object> getPermissionCodeList(Object loginId, String loginKey);
}
@@ -1,17 +0,0 @@
package cn.dev33.satoken.stp;
import java.util.ArrayList;
import java.util.List;
/**
* 权限验证接口 ,默认实现
* @author kong
*/
public class StpInterfaceDefaultImpl implements StpInterface {
@Override
public List<Object> getPermissionCodeList(Object loginId, String loginKey) {
return new ArrayList<Object>();
}
}
@@ -1,443 +0,0 @@
package cn.dev33.satoken.stp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import cn.dev33.satoken.SaTokenManager;
import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.util.SaCookieUtil;
import cn.dev33.satoken.util.SaTokenInsideUtil;
import cn.dev33.satoken.util.SpringMvcUtil;
/**
* sa-token 权限验证,逻辑 实现类
* <p>
* (stp = sa-token-permission 的缩写 )
* @author kong
*/
public class StpLogic {
/**
* 持久化的key前缀,多账号体系时以此值区分,比如:login、user、admin
*/
public String loginKey = "";
/**
* 初始化StpLogic, 并制定loginKey
* @param loginKey .
*/
public StpLogic(String loginKey) {
this.loginKey = loginKey;
}
// =================== 获取token 相关 ===================
/**
* 随机生成一个tokenValue
* @return 生成的tokenValue
*/
public String randomTokenValue() {
return UUID.randomUUID().toString();
}
/**
* 获取当前tokenValue
* @return 当前tokenValue
*/
public String getTokenValue(){
// 0、获取相应对象
HttpServletRequest request = SpringMvcUtil.getRequest();
SaTokenConfig config = SaTokenManager.getConfig();
String keyTokenName = getKeyTokenName();
// 1、尝试从request里读取
if(request.getAttribute(SaTokenInsideUtil.JUST_CREATED_SAVE_KEY) != null) {
return String.valueOf(request.getAttribute(SaTokenInsideUtil.JUST_CREATED_SAVE_KEY));
}
// 2、尝试从请求体里面读取
if(config.getIsReadBody() == true){
String tokenValue = request.getParameter(keyTokenName);
if(tokenValue != null) {
return tokenValue;
}
}
// 3、尝试从header力读取
if(config.getIsReadHead() == true){
String tokenValue = request.getHeader(keyTokenName);
if(tokenValue != null) {
return tokenValue;
}
}
// 4、尝试从cookie里读取
if(config.getIsReadCookie() == true){
Cookie cookie = SaCookieUtil.getCookie(request, keyTokenName);
if(cookie != null){
String tokenValue = cookie.getValue();
if(tokenValue != null) {
return tokenValue;
}
}
}
// 5、都读取不到,那算了吧还是
return null;
}
/**
* 获取指定id的tokenValue
* @param loginId .
* @return
*/
public String getTokenValueByLoginId(Object loginId) {
return SaTokenManager.getDao().getValue(getKeyLoginId(loginId));
}
/**
* 获取当前会话的token信息:tokenName与tokenValue
* @return 一个Map对象
*/
public Map<String, String> getTokenInfo() {
Map<String, String> map = new HashMap<String, String>();
map.put("tokenName", getKeyTokenName());
map.put("tokenValue", getTokenValue());
return map;
}
// =================== 登录相关操作 ===================
/**
* 在当前会话上登录id
* @param loginId 登录id ,建议的类型:(long | int | String
*/
public void setLoginId(Object loginId) {
// 1、获取相应对象
HttpServletRequest request = SpringMvcUtil.getRequest();
SaTokenConfig config = SaTokenManager.getConfig();
SaTokenDao dao = SaTokenManager.getDao();
// 2、获取tokenValue
String tokenValue = getTokenValueByLoginId(loginId); // 获取旧tokenValue
if(tokenValue == null){ // 为null则创建一个新的
tokenValue = randomTokenValue();
} else {
// 不为null, 并且配置不共享,则删掉原来,并且创建新的
if(config.getIsShare() == false){
dao.delKey(getKeyTokenValue(tokenValue));
tokenValue = randomTokenValue();
}
}
// 3、持久化
dao.setValue(getKeyTokenValue(tokenValue), String.valueOf(loginId), config.getTimeout()); // token -> uid
dao.setValue(getKeyLoginId(loginId), tokenValue, config.getTimeout()); // uid -> token
request.setAttribute(SaTokenInsideUtil.JUST_CREATED_SAVE_KEY, tokenValue); // 保存到本次request里
if(config.getIsReadCookie() == true){
SaCookieUtil.addCookie(SpringMvcUtil.getResponse(), getKeyTokenName(), tokenValue, "/", (int)config.getTimeout()); // cookie注入
}
}
/**
* 当前会话注销登录
*/
public void logout() {
Object loginId = getLoginIdDefaultNull();
if(loginId != null) {
logoutByLoginId(loginId);
// 清除cookie
if(SaTokenManager.getConfig().getIsReadCookie() == true){
SaCookieUtil.delCookie(SpringMvcUtil.getRequest(), SpringMvcUtil.getResponse(), getKeyTokenName());
}
}
}
/**
* 指定loginId的会话注销登录(踢人下线)
* @param loginId 账号id
*/
public void logoutByLoginId(Object loginId) {
// 获取相应tokenValue
String tokenValue = getTokenValueByLoginId(loginId);
if(tokenValue == null) {
return;
}
// 清除相关数据
SaTokenManager.getDao().delKey(getKeyTokenValue(tokenValue)); // 清除token-id键值对
SaTokenManager.getDao().delKey(getKeyLoginId(loginId)); // 清除id-token键值对
SaTokenManager.getDao().delKey(getKeySession(loginId)); // 清除其session
// SaCookieUtil.delCookie(SpringMVCUtil.getRequest(), SpringMVCUtil.getResponse(), getKey_tokenName()); // 清除cookie
}
// 查询相关
/**
* 获取当前会话是否已经登录
* @return 是否已登录
*/
public boolean isLogin() {
return getLoginIdDefaultNull() != null;
}
/**
* 检验当前会话是否已经登录,如未登录,则抛出异常
*/
public void checkLogin() {
getLoginId();
}
/**
* 获取当前会话登录id, 如果未登录,则抛出异常
* @return .
*/
public Object getLoginId() {
Object loginId = getLoginIdDefaultNull();
if(loginId == null) {
throw new NotLoginException(this.loginKey);
}
return loginId;
}
/**
* 获取当前会话登录id, 如果未登录,则返回默认值
* @param defaultValue .
* @return
*/
@SuppressWarnings("unchecked")
public <T>T getLoginId(T defaultValue) {
Object loginId = getLoginIdDefaultNull();
if(loginId == null) {
return defaultValue;
}
if(defaultValue instanceof Integer) {
return (T)Integer.valueOf(loginId.toString());
}
if(defaultValue instanceof Long) {
return (T)Long.valueOf(loginId.toString());
}
if(defaultValue instanceof String) {
return (T)loginId.toString();
}
return (T)loginId;
}
/**
* 获取当前会话登录id, 如果未登录,则返回null
* @return
*/
public Object getLoginIdDefaultNull() {
String tokenValue = getTokenValue();
if(tokenValue != null) {
Object loginId = SaTokenManager.getDao().getValue(getKeyTokenValue(tokenValue));
if(loginId != null) {
return loginId;
}
}
return null;
}
/**
* 获取当前会话登录id, 并转换为String
* @return
*/
public String getLoginIdAsString() {
return String.valueOf(getLoginId());
}
/**
* 获取当前会话登录id, 并转换为int
* @return
*/
public int getLoginIdAsInt() {
// Object loginId = getLoginId();
// if(loginId instanceof Integer) {
// return (Integer)loginId;
// }
return Integer.valueOf(String.valueOf(getLoginId()));
}
/**
* 获取当前会话登录id, 并转换为long
* @return
*/
public long getLoginIdAsLong() {
// Object loginId = getLoginId();
// if(loginId instanceof Long) {
// return (Long)loginId;
// }
return Long.valueOf(String.valueOf(getLoginId()));
}
/**
* 获取指定token对应的登录id,如果未登录,则返回 null
* @return .
*/
public Object getLoginIdByToken(String tokenValue) {
if(tokenValue != null) {
Object loginId = SaTokenManager.getDao().getValue(getKeyTokenValue(tokenValue));
if(loginId != null) {
return loginId;
}
}
return null;
}
// =================== session相关 ===================
/**
* 获取指定key的session, 如果没有,isCreate=是否新建并返回
* @param sessionId .
* @param isCreate .
* @return .
*/
protected SaSession getSessionBySessionId(String sessionId, boolean isCreate) {
SaSession session = SaTokenManager.getDao().getSaSession(sessionId);
if(session == null && isCreate) {
session = new SaSession(sessionId);
SaTokenManager.getDao().saveSaSession(session, SaTokenManager.getConfig().getTimeout());
}
return session;
}
/**
* 获取指定loginId的session, 如果没有,isCreate=是否新建并返回
* @param loginId 登录id
* @param isCreate 是否新建
* @return SaSession
*/
public SaSession getSessionByLoginId(Object loginId, boolean isCreate) {
return getSessionBySessionId(getKeySession(loginId), isCreate);
}
/**
* 获取指定loginId的session
* @param loginId .
* @return .
*/
public SaSession getSessionByLoginId(Object loginId) {
return getSessionByLoginId(getKeySession(loginId), false);
}
/**
* 获取当前会话的session
* @return
*/
public SaSession getSession() {
return getSessionBySessionId(getKeySession(getLoginId()), true);
}
// =================== 权限验证操作 ===================
/**
* 指定loginId是否含有指定权限
* @param loginId .
* @param pcode .
* @return .
*/
public boolean hasPermission(Object loginId, Object pcode) {
List<Object> pcodeList = SaTokenManager.getStp().getPermissionCodeList(loginId, loginKey);
return !(pcodeList == null || pcodeList.contains(pcode) == false);
}
/**
* 当前会话是否含有指定权限
* @param pcode .
* @return .
*/
public boolean hasPermission(Object pcode) {
return hasPermission(getLoginId(), pcode);
}
/**
* 当前账号是否含有指定权限 , 没有就抛出异常
* @param pcode .
*/
public void checkPermission(Object pcode) {
if(hasPermission(pcode) == false) {
throw new NotPermissionException(pcode, this.loginKey);
}
}
/**
* 当前账号是否含有指定权限 , 【指定多个,必须全都有】
* @param pcodeArray .
*/
public void checkPermissionAnd(Object... pcodeArray){
Object loginId = getLoginId();
List<Object> pcodeList = SaTokenManager.getStp().getPermissionCodeList(loginId, loginKey);
for (Object pcode : pcodeArray) {
if(pcodeList.contains(pcode) == false) {
throw new NotPermissionException(pcode, this.loginKey); // 没有权限抛出异常
}
}
}
/**
* 当前账号是否含有指定权限 , 【指定多个,有一个就可以了】
* @param pcodeArray .
*/
public void checkPermissionOr(Object... pcodeArray){
Object loginId = getLoginId();
List<Object> pcodeList = SaTokenManager.getStp().getPermissionCodeList(loginId, loginKey);
for (Object pcode : pcodeArray) {
if(pcodeList.contains(pcode) == true) {
return; // 有的话提前退出
}
}
if(pcodeArray.length > 0) {
throw new NotPermissionException(pcodeArray[0], this.loginKey); // 没有权限抛出异常
}
}
// =================== 返回相应key ===================
/**
* 获取key:客户端 tokenName
* @return
*/
public String getKeyTokenName() {
return SaTokenManager.getConfig().getTokenName();
}
/**
* 获取key tokenValue 持久化
* @param tokenValue .
* @return
*/
public String getKeyTokenValue(String tokenValue) {
return SaTokenManager.getConfig().getTokenName() + ":" + loginKey + ":token:" + tokenValue;
}
/**
* 获取key id 持久化
* @param loginId .
* @return
*/
public String getKeyLoginId(Object loginId) {
return SaTokenManager.getConfig().getTokenName() + ":" + loginKey + ":id:" + loginId;
}
/**
* 获取key session 持久化
* @param loginId .
* @return .
*/
public String getKeySession(Object loginId) {
return SaTokenManager.getConfig().getTokenName() + ":" + loginKey + ":session:" + loginId;
}
}
@@ -1,224 +0,0 @@
package cn.dev33.satoken.stp;
import java.util.Map;
import org.springframework.stereotype.Service;
import cn.dev33.satoken.session.SaSession;
/**
* 一个默认的实现
* @author kong
*/
@Service
public class StpUtil {
/**
* 底层的 StpLogic 对象
*/
public static StpLogic stpLogic = new StpLogic("login");
// =================== 获取token 相关 ===================
/**
* 获取当前tokenValue
* @return 当前tokenValue
*/
public static String getTokenValue() {
return stpLogic.getTokenValue();
}
/**
* 获取指定id的tokenValue
* @param loginId .
* @return
*/
public static String getTokenValueByLoginId(Object loginId) {
return stpLogic.getTokenValueByLoginId(loginId);
}
/**
* 获取当前会话的token信息:tokenName与tokenValue
* @return 一个Map对象
*/
public static Map<String, String> getTokenInfo() {
return stpLogic.getTokenInfo();
}
// =================== 登录相关操作 ===================
/**
* 在当前会话上登录id
* @param loginId 登录id ,建议的类型:(long | int | String
*/
public static void setLoginId(Object loginId) {
stpLogic.setLoginId(loginId);
}
/**
* 当前会话注销登录
*/
public static void logout() {
stpLogic.logout();
}
/**
* 指定loginId的会话注销登录(踢人下线)
* @param loginId 账号id
*/
public static void logoutByLoginId(Object loginId) {
stpLogic.logoutByLoginId(loginId);
}
// 查询相关
/**
* 获取当前会话是否已经登录
* @return 是否已登录
*/
public static boolean isLogin() {
return stpLogic.isLogin();
}
/**
* 检验当前会话是否已经登录,如未登录,则抛出异常
*/
public static void checkLogin() {
getLoginId();
}
/**
* 获取当前会话登录id, 如果未登录,则抛出异常
* @return .
*/
public static Object getLoginId() {
return stpLogic.getLoginId();
}
/**
* 获取当前会话登录id, 如果未登录,则返回默认值
* @param defaultValue .
* @return .
*/
public static <T> T getLoginId(T defaultValue) {
return stpLogic.getLoginId(defaultValue);
}
/**
* 获取当前会话登录id, 如果未登录,则返回null
* @return
*/
public static Object getLoginIdDefaultNull() {
return stpLogic.getLoginIdDefaultNull();
}
/**
* 获取当前会话登录id, 并转换为String
* @return
*/
public static String getLoginIdAsString() {
return stpLogic.getLoginIdAsString();
}
/**
* 获取当前会话登录id, 并转换为int
* @return
*/
public static int getLoginIdAsInt() {
return stpLogic.getLoginIdAsInt();
}
/**
* 获取当前会话登录id, 并转换为long
* @return
*/
public static long getLoginIdAsLong() {
return stpLogic.getLoginIdAsLong();
}
/**
* 获取指定token对应的登录id,如果未登录,则返回 null
* @return .
*/
public static Object getLoginIdByToken(String tokenValue) {
return stpLogic.getLoginIdByToken(tokenValue);
}
// =================== session相关 ===================
/**
* 获取指定loginId的session, 如果没有,isCreate=是否新建并返回
* @param loginId 登录id
* @param isCreate 是否新建
* @return SaSession
*/
public static SaSession getSessionByLoginId(Object loginId, boolean isCreate) {
return stpLogic.getSessionByLoginId(loginId, isCreate);
}
/**
* 获取指定loginId的session
* @param loginId .
* @return .
*/
public static SaSession getSessionByLoginId(Object loginId) {
return stpLogic.getSessionByLoginId(loginId);
}
/**
* 获取当前会话的session
* @return
*/
public static SaSession getSession() {
return stpLogic.getSession();
}
// =================== 权限验证操作 ===================
/**
* 指定loginId是否含有指定权限
* @param loginId .
* @param pcode .
* @return .
*/
public static boolean hasPermission(Object loginId, Object pcode) {
return stpLogic.hasPermission(loginId, pcode);
}
/**
* 当前会话是否含有指定权限
* @param pcode .
* @return .
*/
public static boolean hasPermission(Object pcode) {
return stpLogic.hasPermission(pcode);
}
/**
* 当前账号是否含有指定权限 , 没有就抛出异常
* @param pcode .
*/
public static void checkPermission(Object pcode) {
stpLogic.checkPermission(pcode);
}
/**
* 当前账号是否含有指定权限 , 【指定多个,必须全都有】
* @param pcodeArray .
*/
public static void checkPermissionAnd(Object... pcodeArray) {
stpLogic.checkPermissionAnd(pcodeArray);
}
/**
* 当前账号是否含有指定权限 , 【指定多个,有一个就可以了】
* @param pcodeArray .
*/
public static void checkPermissionOr(Object... pcodeArray) {
stpLogic.checkPermissionOr(pcodeArray);
}
}
@@ -1,95 +0,0 @@
package cn.dev33.satoken.util;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* cookie工具类
* @author kong
*
*/
public class SaCookieUtil {
/**
* 获取指定cookie .
* @param request .
* @param cookieName .
* @return .
*/
public static Cookie getCookie(HttpServletRequest request, String cookieName) {
Cookie[] cookies = request.getCookies();
if(cookies != null) {
for(int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if(cookie != null && cookieName.equals(cookie.getName())) {
return cookie;
}
}
}
return null;
}
/**
* 添加cookie
* @param response .
* @param name .
* @param value .
* @param path .
* @param timeout .
*/
public static void addCookie(HttpServletResponse response,String name,String value,String path,int timeout) {
Cookie cookie = new Cookie(name, value);
if(path == null) {
path = "/";
}
cookie.setPath(path);
cookie.setMaxAge(timeout);
response.addCookie(cookie);
}
/**
* 删除cookie .
* @param request .
* @param response .
* @param name .
*/
public static void delCookie(HttpServletRequest request,HttpServletResponse response,String name) {
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies) {
if(cookies != null && (name).equals(cookie.getName())) {
addCookie(response,name,null,null,0);
return;
}
}
}
}
/**
* 修改cookie的value值
* @param request .
* @param response .
* @param name .
* @param value .
*/
public static void updateCookie(HttpServletRequest request,HttpServletResponse response,String name,String value) {
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies) {
if(cookies != null && (name).equals(cookie.getName())) {
addCookie(response,name,value,cookie.getPath(),cookie.getMaxAge());
return;
}
}
}
}
}
@@ -1,40 +0,0 @@
package cn.dev33.satoken.util;
/**
* sa-token 工具类
* @author kong
*
*/
public class SaTokenInsideUtil {
/**
* sa-token 版本号
*/
public static final String VERSION_NO = "v1.4.0";
/**
* sa-token 开源地址
*/
public static final String GITHUB_URL= "https://github.com/click33/sa-token";
/**
* 打印 sa-token
*/
public static void printSaToken() {
String str =
"____ ____ ___ ____ _ _ ____ _ _ \r\n" +
"[__ |__| __ | | | |_/ |___ |\\ | \r\n" +
"___] | | | |__| | \\_ |___ | \\| \r\n" +
"sa-token" + VERSION_NO + " \r\n" +
"GitHub" + GITHUB_URL; // + "\r\n";
System.out.println(str);
}
/**
* 如果token为本次请求新创建的,则以此字符串为key存储在当前request中 JUST_CREATED_SAVE_KEY
*/
public static final String JUST_CREATED_SAVE_KEY = "JUST_CREATED_SAVE_KEY_";
}
View File
+79 -28
View File
@@ -1,11 +1,11 @@
<p align="center">
<img alt="logo" src="http://sa-token.dev33.cn/doc/logo.png" width="150" height="150" style="margin-bottom: 10px;">
<img alt="logo" src="https://gitee.com/sz6/sa-token/raw/master/sa-token-doc/doc/logo.png" width="150" height="150" style="margin-bottom: 10px;">
</p>
<h1 align="center" style="margin: 30px 0 30px; font-weight: bold;">sa-token v1.4.0</h1>
<h4 align="center">一个JavaWeb权限认证框架,强大、简单、好用</h4>
<h1 align="center" style="margin: 30px 0 30px; font-weight: bold;">sa-token v1.8.0</h1>
<h4 align="center">一个JavaWeb轻量级权限认证框架,功能全面,上手简单</h4>
<h4 align="center">
<a href="https://github.com/click33/sa-token"><img src="https://img.shields.io/badge/sa--token-v1.4.0-2B9939"></a>
<a href="https://github.com/click33/sa-token"><img src="https://img.shields.io/badge/language-java-2B9939"></a>
<a href="https://gitee.com/sz6/sa-token/stargazers"><img src="https://gitee.com/sz6/sa-token/badge/star.svg"></a>
<a href="https://github.com/click33/sa-token"><img src="https://img.shields.io/badge/sa--token-v1.8.0-2B9939"></a>
<a href="https://github.com/click33/sa-token/stargazers"><img src="https://img.shields.io/github/stars/click33/sa-token"></a>
<a href="https://github.com/click33/sa-token/watchers"><img src="https://img.shields.io/github/watchers/click33/sa-token"></a>
<a href="https://github.com/click33/sa-token/network/members"><img src="https://img.shields.io/github/forks/click33/sa-token"></a>
@@ -14,45 +14,96 @@
</h4>
---
## sa-token 😋
- 在线文档:[http://sa-token.dev33.cn/](http://sa-token.dev33.cn/)
- 需求提交:我们深知一个优秀的项目需要海纳百川,[点我在线提交需求](http://sa-app.dev33.cn/wall.html?name=sa-token)
- 开源不易,求鼓励,**点个`star`吧**
## 框架优点
与其它权限认证框架相比,sa-token尽力保证两点:
## 😘 在线资料
- [官网首页:http://sa-token.dev33.cn/](http://sa-token.dev33.cn/)
- [在线文档:http://sa-token.dev33.cn/doc/index.html](http://sa-token.dev33.cn/doc/index.html)
- [需求提交:我们深知一个优秀的项目需要海纳百川,点我在线提交需求](http://sa-app.dev33.cn/wall.html?name=sa-token)
- [开源不易,求鼓励,点个star吧](https://github.com/click33/sa-token)
## ⭐ sa-token是什么?
**sa-token是一个JavaWeb轻量级权限认证框架,其API调用非常简单,有多简单呢?以登录验证为例,你只需要:**
``` java
// 在登录时写入当前会话的账号id
StpUtil.setLoginId(10001);
// 然后在任意需要校验登录处调用以下API --- 如果当前会话未登录,这句代码会抛出 `NotLoginException`异常
StpUtil.checkLogin();
```
**没有复杂的封装!不要任何的配置!只需这两行简单的调用,即可轻松完成系统登录鉴权!**
## 🔥 框架设计思想
与其它权限认证框架相比,`sa-token`尽力保证两点:
- 上手简单:能自动化的配置全部自动化,不让你费脑子
- 功能强大:能涵盖的功能全部涵盖,不让你用个框架还要自己给框架打各种补丁
## 涵盖功能
- 登录验证
- 权限验证
- 自定义session会话
- 踢人下线
- 模拟他人账号
- 持久层扩展(集成redis
- 多账号认证体系(比如一个商城项目的user表和admin表)
- 无cookie模式(APP、小程序等前后台分离场景)
- 注解式鉴权(优雅的将鉴权与业务代码分离)
- 零配置与Spring等框架集成
- ...
## 贡献代码
**如果上面的示例能够证明`sa-token`的简单,那么以下API则可以证明`sa-token`的强大**
``` java
StpUtil.setLoginId(10001); // 标记当前会话登录的账号id
StpUtil.getLoginId(); // 获取当前会话登录的账号id
StpUtil.isLogin(); // 获取当前会话是否已经登录, 返回true或false
StpUtil.logout(); // 当前会话注销登录
StpUtil.logoutByLoginId(10001); // 让账号为10001的会话注销登录(踢人下线)
StpUtil.hasRole("super-admin"); // 查询当前账号是否含有指定角色标识, 返回true或false
StpUtil.hasPermission("user:add"); // 查询当前账号是否含有指定权限, 返回true或false
StpUtil.getSession(); // 获取当前账号id的Session
StpUtil.getSessionByLoginId(10001); // 获取账号id为10001的Session
StpUtil.getTokenValueByLoginId(10001); // 获取账号id为10001的token令牌值
```
**sa-token的API众多,请恕此处无法为您逐一展示,更多示例请戳官方在线文档**
## 💦️ 涵盖功能
- **登录验证** —— 轻松登录鉴权,并提供五种细分场景值
- **权限验证** —— 拦截违规调用,不同角色不同授权
- **Session会话** —— 专业的数据缓存中心
- **踢人下线** —— 将违规用户立刻清退下线
- **模拟他人账号** —— 实时操作任意用户状态数据
- **持久层扩展** —— 可集成redis、MongoDB等专业缓存中间件
- **多账号认证体系** —— 比如一个商城项目的user表和admin表分开鉴权
- **无Cookie模式** —— APP、小程序等前后台分离场景
- **注解式鉴权** —— 优雅的将鉴权与业务代码分离
- **花式token生成** —— 内置六种token风格,还可自定义token生成策略
- **自动续签** —— 提供两种token过期策略,灵活搭配使用,还可自动续签
- **组件自动注入** —— 零配置与Spring等框架集成
- **更多功能正在集成中...** —— 如有您有好想法或者建议,欢迎加群交流
## 🔨 贡献代码
sa-token欢迎大家贡献代码,为框架添砖加瓦
1. 在github上fork一份到自己的仓库
2. clone自己的仓库到本地电脑
3. 在本地电脑修改、commit、push
4. 提交pr(点击:New Pull Request(提交pr前请保证自己fork的仓库是最新版本,如若不是先强制更新一下)
4. 提交pr(点击:New Pull Request
5. 等待合并
## 建议贡献的地方
## 🌱 建议贡献的地方
- 修复源码现有bug,或增加新的实用功能
- 完善在线文档,或者修复现有错误之处
- 更多demo示例:比如SSM版搭建步骤
- 您可以参考项目issues与需求墙进行贡献
- 如果更新实用功能,可在文档友情链接处留下自己的推广链接
## 交流群
## 🚀 友情链接
[**[ okhttps ]** 一个轻量级http通信框架,支持 WebSocket 以及 Stomp 协议](https://gitee.com/ejlchina-zhxu/okhttps)
## 😎 交流群
QQ交流群:[1002350610 点击加入](https://jq.qq.com/?_wv=1027&k=45H977HM) ,欢迎你的加入
+10 -9
View File
@@ -8,25 +8,26 @@
- **使用**
- [登录验证](/use/login-auth)
- [权限验证](/use/jur-auth)
- [session会话](/use/session)
- [Session会话](/use/session)
- [踢人下线](/use/kick)
- [持久层扩展(集成redis)](/use/dao-extend)
- [cookie模式(前后台分离)](/use/not-cookie)
- [持久层扩展(集成Redis)](/use/dao-extend)
- [Cookie模式(前后台分离)](/use/not-cookie)
- [模拟他人](/use/mock-person)
- [多账号验证](/use/many-account)
- [注解式鉴权](/use/at-check)
- [花式token](/use/token-style)
- [框架配置](/use/config)
- **其它**
- [常见问题](/more/common-questions)
- [友情链接](/more/link)
- [更新日志](/more/update-log)
<!-- - [常见问题](/c1) -->
<!-- - [常用函数](/c1) -->
<!-- - [插件](/c1) -->
<!-- - [关于](/c1) -->
<!-- - eclipse插件 -->
<!-- - idea插件 -->
- **附录**
- [未登录场景值](/fun/not-login-scene)
- [token有效期详解](/fun/token-timeout)
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<p style="text-align: center;">----- 到底线了 -----</p>
+49
View File
@@ -0,0 +1,49 @@
# NotLoginException 场景值
本篇介绍如何根据`NotLoginException`异常的场景值,来定制化处理未登录的逻辑 <br/>
应用场景举例:未登录、被顶下线、被踢下线等场景需要不同方式来处理
## 何为场景值
- 在前面的章节中,我们了解到,在会话未登录的情况下尝试获取`loginId`会使框架抛出`NotLoginException`异常,而同为未登录异常却有五种抛出场景的区分 <br>
- 那么,如何获取场景值呢?废话少说直接上代码:
``` java
// 全局异常拦截(拦截项目中的NotLoginException异常)
@ExceptionHandler(NotLoginException.class)
public AjaxJson handlerNotLoginException(NotLoginException nle, HttpServletRequest request, HttpServletResponse response)
throws Exception {
// 打印堆栈,以供调试
nle.printStackTrace();
// 判断场景值,定制化异常信息
String message = "";
if(nle.getType().equals(NotLoginException.NOT_TOKEN)) {
message = "未提供token";
}
else if(nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
message = "token无效";
}
else if(nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
message = "token已过期";
}
else if(nle.getType().equals(NotLoginException.BE_REPLACED)) {
message = "token已被顶下线";
}
else if(nle.getType().equals(NotLoginException.KICK_OUT)) {
message = "token已被踢下线";
}
else {
message = "当前会话未登录";
}
// 返回给前端
return AjaxJson.getError(message);
}
```
<br/>
注意:以上代码并非处理逻辑的最佳方式,只为以最简单的代码演示出场景值的获取与应用,大家可以根据自己的项目需求来定制化处理
+45
View File
@@ -0,0 +1,45 @@
# token有效期详解
<!-- 本篇介绍token有效期的详细用法 -->
`sa-token` 提供两种token自动过期策略,分别是`timeout``activity-timeout`,其详细用法如下:
### timeout
- `timeout`代表token的长久有效期,单位/秒,例如将其配置为`2592000`(30天),代表在30天后,token必定过期,无法继续使用
- `timeout`无法续签,想要继续使用必须重新登录
- `timeout`的值配置为-1后,代表永久有效,不会过期
### activity-timeout
- `activity-timeout`代表临时有效期,单位/秒,例如将其配置为`1800`(30分钟),代表用户如果30分钟无操作,则此token会立即过期
- 如果在30分钟内用户有操作,则会再次续签30分钟,用户如果一直操作则会一直续签,直到连续30分钟无操作,token才会过期
- `activity-timeout`的值配置为-1后,代表永久有效,不会过期,此时也无需频繁续签
### 关于activity-timeout的续签
如果`activity-timeout`配置了大于零的值,`sa-token`会在登录时开始计时,在每次直接或间接调用`getLoginId()`时进行一次过期检查与续签操作。
此时会有两种情况:
- 一种是会话无操作时间太长,token已经过期,此时框架会抛出`NotLoginException`异常(场景值=-3)
- 另一种则是会话在`activity-timeout`有效期内通过检查,此时token可以成功续签
### 我可以手动续签吗?
**可以!**
如果框架的自动续签算法无法满足您的业务需求,你可以进行手动续签,`sa-token`提供两个API供你操作:
- `StpUtil.checkActivityTimeout()`: 检查当前token 是否已经[临时过期],如果已经过期则抛出异常
- `StpUtil.updateLastActivityToNow()`: 续签当前token:(将 [最后操作时间] 更新为当前时间戳)
- 注意:在手动续签时,即时token已经 [临时过期] 也可续签成功,如果此场景下需要提示续签失败,可采用先检查再续签的形式保证token有效性
- 例如以下代码:
``` java
// 先检查是否已过期
StpUtil.checkActivityTimeout();
// 检查通过后继续续签
StpUtil.updateLastActivityToNow();
```
### timeout与activity-timeout可以同时使用吗?
**可以同时使用!**
两者的认证逻辑彼此独立,互不干扰,可以同时使用。
-12
View File
@@ -1,12 +0,0 @@
.logo-box {position: absolute;left: 30px;top: 10px;cursor: pointer;color: #000;}
.logo-box img {width: 50px;height: 50px;vertical-align: middle;}
.logo-box .logo-text {display: inline-block;vertical-align: middle;font-size: 24px;font-weight: 400;}
#main {padding-bottom: 100px;}
#main h2 {font-size: 1.6rem;}
#main h3 {font-size: 1.25rem;}
.main-box .markdown-section{ padding: 30px 20px;}
@media screen and (max-width: 800px) {
.logo-box {display: none;}
.main-box .markdown-section{max-width: 1000px;}
}
+13 -5
View File
@@ -7,9 +7,9 @@
<meta name="description" content="Description">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta name="keywords" content="sa-token|sa-token框架|sa-token文档|sa-token在线文档|权限认证框架">
<meta name="description" content="sa-token是一个JavaWeb权限认证框架,强大、简单、好用,登录验证、权限验证、自定义session会话、踢人下线、持久层扩展、无cookie模式、模拟他人账号、多账号体系、注解式鉴权、Spring集成...,零配置开箱即用,覆盖所有应用场景,你所需要的功能,这里都有">
<meta name="description" content="sa-token是一个JavaWeb权限认证框架,功能全面,上手简单,登录验证、权限验证、Session会话、踢人下线、集成Redis、前后台分离、模拟他人账号、多账号体系、注解式鉴权、花式token、自动续签、Spring集成...,零配置开箱即用,覆盖所有应用场景,你所需要的功能,这里都有">
<link rel="stylesheet" href="https://unpkg.com/docsify@4.11.3/lib/themes/vue.css">
<link rel="stylesheet" href="./index.css">
<link rel="stylesheet" href="./lib/index.css">
<link rel="shortcut icon" type="image/x-icon" href="logo.png">
</head>
<body>
@@ -20,6 +20,13 @@
</div>
</a>
<nav>
<select onchange="location.href=this.value">
<option value="http://sa-token.dev33.cn/doc/index.html">最新版</option>
<option value="http://sa-token.dev33.cn/v/v1.7.0/doc/index.html">v1.7.0</option>
<option value="http://sa-token.dev33.cn/v/v1.6.0/doc/index.html">v1.6.0</option>
<option value="http://sa-token.dev33.cn/v/v1.5.1/doc/index.html">v1.5.1</option>
<option value="http://sa-token.dev33.cn/v/v1.4.0/doc/index.html">v1.4.0</option>
</select>
<a href="/">首页</a>
<a href="/doc/">文档</a>
<a href="http://sa-app.dev33.cn/wall.html?name=sa-token" target="_blank">需求墙</a>
@@ -30,7 +37,7 @@
</div>
<script>
var name = '<img style="width: 50px; height: 50px; vertical-align: middle;" src="logo.png" alt="logo" /> ';
name += '<b style="font-size: 24px; vertical-align: middle;">sa-token</b> <sub>v1.4.0</sub>'
name += '<b style="font-size: 24px; vertical-align: middle;">sa-token</b> <sub>v1.8.0</sub>'
window.$docsify = {
name: name, // 名字
repo: 'https://github.com/click33/sa-token', // github地址
@@ -54,11 +61,12 @@
function(hook, vm) {
// 解析之后执行
hook.afterEach(function(html) {
var url = 'https://github.com/click33/sa-token/tree/master/sa-token-doc/doc/' + vm.route.file;
var url = 'https://gitee.com/sz6/sa-token/tree/dev/sa-token-doc/doc/' + vm.route.file;
var url2 = 'https://github.com/click33/sa-token/tree/dev/sa-token-doc/doc/' + vm.route.file;
var footer = [
'<br/><br/><br/><br/><br/><br/><br/><hr/>',
'<footer>',
'&emsp;<span>发现错误?想参与编辑? <a href="' + url + '" target="_blank">GitHub 上编辑此页!</a> </span>',
'<span>发现错误?想参与编辑? <a href="' + url + '" target="_blank">Gitee</a> 或 <a href="' + url2 + '" target="_blank">GitHub</a> 上编辑此页!</span>',
'</footer>'
].join('');
return html + footer;
+48
View File
@@ -0,0 +1,48 @@
.logo-box {position: absolute;left: 30px;top: 10px;cursor: pointer;color: #000;}
.logo-box img {width: 50px;height: 50px;vertical-align: middle;}
.logo-box .logo-text {display: inline-block;vertical-align: middle;font-size: 24px;font-weight: 400;}
#main {padding-bottom: 100px;}
#main h2 {font-size: 1.6rem;}
#main h3 {font-size: 1.25rem;}
.main-box .markdown-section{ padding: 30px 20px;}
@media screen and (max-width: 800px) {
.logo-box {display: none;}
.main-box .markdown-section{max-width: 1000px;}
}
/* ============== 样式优化 ================ */
/* 背景变黑 */
.main-box [data-lang]{padding: 0px !important; border-radius: 8px; overflow: hidden;}
.main-box [class^="lang-"]{border: 0px red solid; padding: 1.5em 1.2em;/* background-color: #282828; */ background-color: #090300; color: #FFF;}
.main-box [data-lang]{overflow: auto;}
/* .main-box h2{margin-top: 70px;} */
/* xml语言样式优化 */
.lang-xml .token.comment{color: #CDAB53;}
.lang-xml .token.tag *{color: #db2d20;}
.lang-xml .token.attr-value{color: #A6E22E;}
/* java语言样式优化 */
.main-box .lang-java{color: #01a252; opacity: 1;}
.lang-java .token.keyword{color: #db2d20;}
.lang-java .token.namespace,.lang-java .token.namespace *{color: #01A252; opacity: 1;}
.lang-java .token.class-name,.lang-java .cm-variable{color: #55b5db; opacity: 1;}
.lang-java .token.comment{color: #CDAB53;}
.lang-java .token.annotation.punctuation{color: #ddd;}
.lang-java .token.punctuation{color: #ddd;}
/* js语言样式优化 */
.main-box .lang-js{color: #01a252;}
.lang-js .token.comment{color: #CDAB53;}
/* .lang-js .token.string{color: #fded02;} */
.lang-js .token.string{color: #ddd;}
.lang-js .token.punctuation{color: #ddd;}
/* 调整表格的响应式 */
#main table{margin-left: 25px;}
@media screen and (min-width: 800px) {
#main table tr th{min-width: 150px;}
}
+59 -5
View File
@@ -1,14 +1,65 @@
# 更新日志
### 2020-12-24 @v1.8.0
- 优化:优化源码注释
- 修复:修复部分文档错别字
- 修复:修复项目文件夹名称错误
- 优化:优化文档配色,更舒服的代码展示
- 新增:提供`sa-token`集成 `redis``spring-boot-starter` 方案 **[重要]**
- 新增:新增集成 `redis` 时,以`jackson`作为序列化方案 **[重要]**
- 新增:dao层默认实现增加定时清理过期数据功能 **[重要]**
- 新增:新增`token专属session`, 更灵活的会话管理 **[重要]**
- 新增:增加配置,指定在获取`token专属session`时是否必须登录
- 新增:在无token时自动创建会话,完美兼容`token-session`会话模型! **[重要]**
- 修改:权限码限定必须为String类型
- 优化:注解验证模式由boolean属性改为枚举方式
- 删除:`StpUtil`删除部分冗长API,保持API清爽性
- 新增:新增角色验证 (角色验证与权限验证已完全分离) **[重要]**
- 优化:移除`StpUtil.kickoutByLoginId()`API,由`logoutByLoginId`代替
- 升级:开源协议修改为`Apache-2.0`
### 2020-12-24 @v1.7.0
- 优化:项目架构改为maven多模块形式,方便增加新模块 **[重要]**
- 优化:与`springboot`的集成改为`springboot-starter`模式,无需`@SaTokenSetup`注解即可完成自动装配 **[重要]**
- 新增:新增`activity-timeout`配置,可控制token临时过期与续签功能 **[重要]**
- 新增:`timeout`过期时间新增-1值,代表永不过期
- 新增:`StpUtil.getTokenInfo()`改为对象形式,新增部分常用字段
- 优化:解决在无cookie模式下,不集成redis时会话无法主动过期的问题
- 修复:修复文档首页样式问题
### 2020-12-17 @v1.6.0
- 新增:花式token生成方案 **[重要]**
- 优化:优化`readme.md`
- 修复:修复`SaCookieOper``SaTokenAction`无法自动注入的问题
### 2020-12-16 @v1.5.1
- 新增:细化未登录异常类型,提供五种场景值:未提供token、token无效、token已过期 、token已被顶下线、token已被踢下线 **[重要]**
- 修复:修复`StpUtil.getSessionByLoginId(String loginId)`方法转换key出错的bug,感谢群友 @(#°Д°)、@一米阳光 发现的bug
- 优化:修改方法`StpUtil.getSessionByLoginId(Object loginId)`的isCreate值默认为true
- 修改:`方法delSaSession`修改为`deleteSaSession`,更加语义化的函数名称
- 新增:新增`StpUtil.getTokenName()`方法,更语义化的获取tokenName
- 新增:新增`SaTokenAction`框架行为Bean,方便重写逻辑
- 优化:`Cookie操作`改为接口代理模式,使其可以被重写
- 优化:文档里集成redis部分增加redis的pom依赖示例
- 修复:登录验证-> `StpUtil.getLoginId_defaultNull()` 修复方法名错误的问题
- 优化:优化`readme.md`
- 升级:开源协议修改为`MIT`
### 2020-9-7 @v1.4.0
- 优化:修改一些函数、变量名称,使其更符合阿里java代码规范
- 优化:`tokenValue`的读取优先级改为:`request` > `body` > `header` > `cookie`
- 优化:`tokenValue`的读取优先级改为:`request` > `body` > `header` > `cookie` **[重要]**
- 新增:新增`isReadCookie`配置,决定是否从`cookie`里读取`token`信息
- 优化:如果`isReadCookie`配置为`false`,那么在登录时也不会把`cookie`写入`cookie`
- 新增:新增`getSessionByLoginId(Object loginId, boolean isCreate)`方法
- 修复:修复文档部分错误,修正群号码
### 2020-5-2 @v1.0.3
### 2020-5-2 @v1.3.0
- 新增:新增 `StpUtil.checkLogin()` 方法,更符合语义化的鉴权方法
- 新增:注册拦截器时可设置 `StpLogic` ,方便不同模块不同鉴权方式
- 新增:抛出异常时增加 `loginKey` 区分,方便多账号体系鉴权处理
@@ -16,13 +67,16 @@
- 修复:修复文档部分不正确之处
- 新增:新增文档的友情链接
### 2020-3-7 @v1.0.2
- 新增:新增注解式验证,可在路由方法中使用注解进行权限验证
### 2020-3-7 @v1.2.0
- 新增:新增注解式验证,可在路由方法中使用注解进行权限验证 **[重要]**
- 参考:[注解式验证](use/at-check)
### 2020-2-12 @v1.0.1
### 2020-2-12 @v1.1.0
- 修复:修复`StpUtil.getLoginId(T defaultValue)`取值转换错误的bug
### 2020-2-4 @v1.0.0
- 第一个版本出炉
- GitHub[https://github.com/click33/sa-token](https://github.com/click33/sa-token)
+18 -10
View File
@@ -2,14 +2,14 @@
------
## maven依赖
## Maven依赖
在项目中直接通过 `pom.xml` 导入 `sa-token` 的依赖即可
``` xml
<!-- sa-token 权限认证, 在线文档:http://sa-token.dev33.cn/ -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token</artifactId>
<version>1.4.0</version>
<artifactId>sa-token-spring-boot-starter</artifactId>
<version>1.8.0</version>
</dependency>
```
@@ -21,17 +21,25 @@
- github地址:[https://github.com/click33/sa-token](https://github.com/click33/sa-token)
- gitee地址:[https://gitee.com/sz6/sa-token](https://gitee.com/sz6/sa-token)
- 开源不易,求鼓励,给个`star`吧
- 源码目录介绍
- sa-token-dev: 源码
- sa-token-demo-springboot: springboot集成示例
- sa-token-doc: 文档介绍
- 源码目录介绍:
```
── sa-token
├── sa-token-core // sa-token核心模块
├── sa-token-spring-boot-starter // sa-token整合springboot快速集成
├── sa-token-dao-redis // sa-token整合redis (使用jdk默认序列化方式)
├── sa-token-dao-redis-jackson // sa-token整合redis (使用jackson序列化方式)
├── sa-token-demo-springboot // sa-token示例
├── sa-token-doc // sa-token开发文档
├──pom.xml
```
## jar包下载
[点击下载:sa-token-1.4.0.jar](https://color-test.oss-cn-qingdao.aliyuncs.com/sa-token/sa-token-1.4.0.jar)
[点击下载:sa-token-1.6.0.jar](https://oss.dev33.cn/sa-token/sa-token-1.6.0.jar)
(注意:当前仅提供`v1.6.0`版本jar包下载,更多版本请前往maven中央仓库获取)
+13 -16
View File
@@ -17,13 +17,13 @@
<!-- sa-token 权限认证, 在线文档:http://sa-token.dev33.cn/ -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token</artifactId>
<version>1.4.0</version>
<artifactId>sa-token-spring-boot-starter</artifactId>
<version>1.8.0</version>
</dependency>
```
#### 3、配置文件
- 你可以零配置启动项目
- 你可以**零配置启动项目**
- 但同时你也可以在`application.yml`中增加如下配置,定制性使用框架:
``` java
@@ -32,18 +32,16 @@ spring:
sa-token:
# token名称 (同时也是cookie名称)
token-name: satoken
# token有效期,单位s 默认30天
# token有效期,单位s 默认30天, -1代表永不过期
timeout: 2592000
# 在多人登录同一账号时,是否共享会话 (为true时共用一个,为false时新登录挤掉旧登录)
is-share: true
# 是否尝试从请求体里读取token
is-read-body: true
# 是否尝试从header里读取token
is-read-head: true
# 是否尝试从cookie里读取token
is-read-cookie: true
# 是否在初始化配置时打印版本字符画
is-v: true
# token临时有效期 (指定时间内无操作就视为token过期) 单位: 秒
activity-timeout: -1
# 是否允许同一账号并发登录 (为true时允许一起登录, 为false时新登录挤掉旧登录)
allow-concurrent-login: false
# 在多人登录同一账号时,是否共用一个token (为true时所有登录共用一个token, 为false时每次登录新建一个token)
is-share: false
# token风格
token-style: uuid
```
> - 如果你习惯于 `application.properties` 类型的配置文件,那也很好办:
@@ -53,11 +51,10 @@ spring:
在项目中新建包 `com.pj` ,在此包内新建主类 `SaTokenDemoApplication.java`,输入以下代码:
``` java
@SaTokenSetup // 标注启动 sa-token
@SpringBootApplication
public class SaTokenDemoApplication {
public static void main(String[] args) throws JsonProcessingException {
SpringApplication.run(SaTokenDemoApplication.class, args); // run-->
SpringApplication.run(SaTokenDemoApplication.class, args);
System.out.println("启动成功:sa-token配置如下:" + SaTokenManager.getConfig());
}
}
+37 -8
View File
@@ -2,8 +2,7 @@
---
- 尽管我们可以方便的一句代码完成权限验证,但是有时候我们仍希望可以将鉴权代码与我们的业务代码分离开来
- 怎么做?
- `sa-token`内置两个注解,帮助你使用注解完成鉴权操作
- 怎么做?`sa-token`内置三个注解,帮助你使用注解完成鉴权操作
## 1、注册拦截器
@@ -28,29 +27,59 @@
#### 登录验证
``` java
@SaCheckLogin // 注解式鉴权:当前会话必须登录才能通过
// 注解式鉴权:当前会话必须登录才能通过
@SaCheckLogin
@RequestMapping("info")
public String info() {
return "查询用户信息";
}
```
#### 权限验证
#### 角色验证
``` java
@SaCheckPermission("user-add") // 注解式鉴权:当前会话必须具有指定权限才能通过
// 注解式鉴权:当前会话必须具有指定角色标识才能通过
@SaCheckRole("super-admin")
@RequestMapping("add")
public String add() {
return "用户增加";
}
```
#### 注意事项
#### 权限验证
``` java
// 注解式鉴权:当前会话必须具有指定权限才能通过
@SaCheckPermission("user-add")
@RequestMapping("add")
public String add() {
return "用户增加";
}
```
<br>
以上两个注解都可以加在类上,代表为这个类所有方法进行鉴权
## 3、设定校验模式
`@SaCheckRole`与`@SaCheckPermission`注解可设置校验模式,例如:
``` java
// 注解式鉴权:只要具有其中一个权限即可通过校验
@RequestMapping("atJurOr")
@SaCheckPermission(value = {"user-add", "user-all", "user-delete"}, mode = SaMode.OR)
public AjaxJson atJurOr() {
return AjaxJson.getSuccessData("用户信息");
}
```
## 3、扩展
- mode有两种取值:
- `SaMode.AND`, 标注一组权限,会话必须全部具有才可通过校验
- `SaMode.OR`, 标注一组权限,会话只要具有其一即可通过校验
<!-- ## 3、扩展
- 其实在注册拦截器时,我们也可以根据路由前缀设置不同 `StpLogic`, 从而达到不同模块不同鉴权方式的目的
- 以下为参考示例:
``` java
@@ -63,7 +92,7 @@
registry.addInterceptor(new SaCheckInterceptor(StpUserUtil.stpLogic)).addPathPatterns("/user/**");
}
}
```
``` -->
+53 -51
View File
@@ -1,50 +1,12 @@
# 框架配置
- 你可以零配置启动框架
- 你可以**零配置启动框架**
- 但同时你也可以通过配置,定制性使用框架,`sa-token`支持多种方式配置框架信息
---
### 所有可配置项
| 参数名称 | 类型 | 默认值 | 说明 |
| :-------- | :-------- | :-------- | :-------- |
| tokenName | String | satoken | token名称(同时也是cookie名称) |
| timeout | long | 2592000 | token有效期,单位s 默认30天 |
| isShare | Boolean | true | 在多人登录同一账号时,是否共享会话(为true时共用一个,为false时新登录挤掉旧登录)|
| isReadBody | Boolean | true | 是否尝试从请求体里读取token |
| isReadHead | Boolean | true | 是否尝试从header里读取token |
| isReadCookie | Boolean | true | 是否尝试从cookie里读取token |
| isV | Boolean | true | 是否在初始化配置时打印版本字符画 |
### 方式1、通过代码配置
``` java
/**
* sa-token代码方式进行配置
*/
@Configuration
public class MySaTokenConfig {
// 获取配置Bean (以代码的方式配置sa-token)
@Primary
@Bean(name="MySaTokenConfig")
public SaTokenConfig getSaTokenConfig() {
SaTokenConfig config = new SaTokenConfig();
config.setTokenName("satoken"); // token名称 (同时也是cookie名称)
config.setTimeout(30 * 24 * 60 * 60); // token有效期,单位s 默认30天
config.setIsShare(true); // 在多人登录同一账号时,是否共享会话 (为true时共用一个,为false时新登录挤掉旧登录)
config.setIsReadBody(true); // 是否尝试从请求体里读取token
config.setIsReadHead(true); // 是否尝试从header里读取token
config.setIsReadCookie(true); // 是否尝试从cookie里读取token
config.setIsV(true); // 是否在初始化配置时打印版本字符画
return config;
}
}
```
### 方式2、在`application.yml`配置
### 方式1、在`application.yml`配置
``` java
spring:
@@ -52,21 +14,61 @@ spring:
sa-token:
# token名称 (同时也是cookie名称)
token-name: satoken
# token有效期,单位s 默认30天
# token有效期,单位s 默认30天, -1代表永不过期
timeout: 2592000
# 在多人登录同一账号时,是否共享会话 (为true时共用一个,为false时新登录挤掉旧登录)
is-share: true
# 是否尝试从请求体里读取token
is-read-body: true
# 是否尝试从header里读取token
is-read-head: true
# 是否尝试从cookie里读取token
is-read-cookie: true
# 是否在初始化配置时打印版本字符画
is-v: true
# token临时有效期 (指定时间内无操作就视为token过期) 单位: 秒
activity-timeout: -1
# 是否允许同一账号并发登录 (为true时允许一起登录, 为false时新登录挤掉旧登录)
allow-concurrent-login: false
# 在多人登录同一账号时,是否共用一个token (为true时所有登录共用一个token, 为false时每次登录新建一个token)
is-share: false
# token风格
token-style: uuid
```
- 如果你习惯于 `application.properties` 类型的配置文件,那也很好办:
- 百度: [springboot properties与yml 配置文件的区别](https://www.baidu.com/s?ie=UTF-8&wd=springboot%20properties%E4%B8%8Eyml%20%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E7%9A%84%E5%8C%BA%E5%88%AB)
### 方式2、通过代码配置
``` java
/**
* sa-token代码方式进行配置
*/
@Configuration
public class MySaTokenConfig {
// 获取配置Bean (以代码的方式配置sa-token, 此配置会覆盖yml中的配置)
@Primary
@Bean(name="MySaTokenConfig")
public SaTokenConfig getSaTokenConfig() {
SaTokenConfig config = new SaTokenConfig();
config.setTokenName("satoken"); // token名称 (同时也是cookie名称)
config.setTimeout(30 * 24 * 60 * 60); // token有效期,单位s 默认30天
config.setActivityTimeout(-1); // token临时有效期 (指定时间内无操作就视为token过期) 单位: 秒
config.setAllowConcurrentLogin(true); // 是否允许同一账号并发登录 (为true时允许一起登录, 为false时新登录挤掉旧登录)
config.setIsShare(true); // 在多人登录同一账号时,是否共用一个token (为true时所有登录共用一个token, 为false时每次登录新建一个token)
config.setTokenStyle("uuid"); // token风格
return config;
}
}
```
---
### 所有可配置项
| 参数名称 | 类型 | 默认值 | 说明 |
| :-------- | :-------- | :-------- | :-------- |
| tokenName | String | satoken | token名称 (同时也是cookie名称) |
| timeout | long | 2592000 | token有效期,单位/秒 默认30天,-1代表永久有效 [参考:token有效期详解](/fun/token-timeout) |
| activityTimeout | long | -1 | token临时有效期 (指定时间内无操作就视为token过期) 单位: 秒, 默认-1 代表不限制 (例如可以设置为1800代表30分钟内无操作就过期) [参考:token有效期详解](/fun/token-timeout) |
| allowConcurrentLogin | Boolean | true | 是否允许同一账号并发登录 (为true时允许一起登录, 为false时新登录挤掉旧登录) |
| isShare | Boolean | true | 在多人登录同一账号时,是否共用一个token (为true时所有登录共用一个token, 为false时每次登录新建一个token) |
| isReadBody | Boolean | true | 是否尝试从请求体里读取token |
| isReadHead | Boolean | true | 是否尝试从header里读取token |
| isReadCookie | Boolean | true | 是否尝试从cookie里读取token |
| tokenStyle | String | uuid | token风格, [参考:花式token](/use/token-style) |
| dataRefreshPeriod | int | 30 | 默认dao层实现类中,每次清理过期数据间隔的时间 (单位: 秒) ,默认值30秒,设置为-1代表不启动定时清理 |
| tokenSessionCheckLogin | Boolean | true | 获取token专属session时是否必须登录 (如果配置为true,会在每次获取token专属session时校验是否登录) |
| isV | Boolean | true | 是否在初始化配置时打印版本字符画 |
+36 -97
View File
@@ -1,109 +1,48 @@
# 持久层扩展
---
- 每次重启项目就得重新登录一,我想把登录数据都放在`redis`,这样重启项目也不用重新登录,行不行?
- 行!
- 你需要做的就是重写`sa-token`的dao层实现方式,参考以下方案:
- 每次重启项目都需要重新登录一,我想把会话数据都放在`Redis``MongoDB`等专业的缓存中间件中,这样重启项目也不用重新登录,行不行?**行!**
- sa-token 在架构设计时将数据持久操作全部抽象到接口`SaTokenDao`中,此设计可以保证开发者对数据持久层的灵活扩展
- 除了框架内部对`SaTokenDao`提供的基于内存的默认实现,官方仓库还提供了以下扩展方案:
## 具体代码
- 新建文件`SaTokenDaoRedis.java`,实现接口`SaTokenDao`, 并加上注解`@Component`,保证此类被springboot扫描到
- 代码参考:
```java
package com.pj.satoken;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.session.SaSession;
/**
* sa-token持久层的实现类 , 基于redis
*/
@Component // 保证此类被springboot扫描,即可完成sa-token与redis的集成
public class SaTokenDaoRedis implements SaTokenDao {
### 1. sa-token 整合 Redis (使用jdk默认序列化方式)
``` xml
<!-- sa-token整合redis (使用jdk默认序列化方式) -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-dao-redis</artifactId>
<version>1.8.0</version>
</dependency>
```
优点:兼容性好,缺点:session序列化后基本不可读,对开发者来讲等同于乱码
// string专用
@Autowired
StringRedisTemplate stringRedisTemplate;
// SaSession专用
RedisTemplate<String, SaSession> redisTemplate;
@Autowired
@SuppressWarnings({ "rawtypes", "unchecked" })
public void setRedisTemplate(RedisTemplate redisTemplate) {
RedisSerializer stringSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringSerializer);
JdkSerializationRedisSerializer jrSerializer = new JdkSerializationRedisSerializer();
redisTemplate.setValueSerializer(jrSerializer);
this.redisTemplate = redisTemplate;
}
// 根据key获取value ,如果没有,则返回空
@Override
public String getValue(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
// 写入指定key-value键值对,并设定过期时间(单位:秒)
@Override
public void setValue(String key, String value, long timeout) {
stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
}
// 删除一个指定的key
@Override
public void delKey(String key) {
stringRedisTemplate.delete(key);
}
// 根据指定key的session,如果没有,则返回空
@Override
public SaSession getSaSession(String sessionId) {
return redisTemplate.opsForValue().get(sessionId);
}
// 将指定session持久化
@Override
public void saveSaSession(SaSession session, long timeout) {
redisTemplate.opsForValue().set(session.getId(), session, timeout, TimeUnit.SECONDS);
}
// 更新指定session
@Override
public void updateSaSession(SaSession session) {
long expire = redisTemplate.getExpire(session.getId());
if(expire == -2) { // -2 = 无此键
return;
}
redisTemplate.opsForValue().set(session.getId(), session, expire, TimeUnit.SECONDS);
}
// 删除一个指定的session
@Override
public void delSaSession(String sessionId) {
redisTemplate.delete(sessionId);
}
}
### 2. sa-token 整合 Redis (使用jackson序列化方式)
``` xml
<!-- sa-token整合redis (使用jackson序列化方式) -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-dao-redis-jackson</artifactId>
<version>1.8.0</version>
</dependency>
```
优点:session序列化后可读性强,可灵活手动修改,缺点:兼容性稍差
<br>
**请注意,无论使用哪种序列化方式,你都必须为项目提供一个Redis实例化方案,例如:**
``` xml
<!-- 提供redis连接池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
```
- 可参考代码:[码云:SaTokenDaoRedis.java](https://gitee.com/sz6/sa-token/blob/master/sa-token-demo-springboot/src/main/java/com/pj/satoken/SaTokenDaoRedis.java)
<br><br>
更多框架的集成方案正在更新中... (欢迎大家提交pr)
+14 -1
View File
@@ -30,7 +30,9 @@ import cn.dev33.satoken.stp.StpInterface;
@Component // 保证此类被springboot扫描,完成sa-token的自定义权限验证扩展
public class StpInterfaceImpl implements StpInterface {
// 返回一个账号所拥有的权限码集合
/**
* 返回一个账号所拥有的权限码集合
*/
@Override
public List<Object> getPermissionCodeList(Object loginId, String loginKey) {
List<Object> list = new ArrayList<Object>(); // 本list仅做模拟,实际项目中要根据具体业务逻辑来查询权限
@@ -43,6 +45,17 @@ public class StpInterfaceImpl implements StpInterface {
return list;
}
/**
* 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
*/
@Override
public List<String> getRoleList(Object loginId, String loginKey) {
List<String> list = new ArrayList<String>(); // 本list仅做模拟,实际项目中要根据具体业务逻辑来查询角色
list.add("admin");
list.add("super-admin");
return list;
}
}
```
+7 -6
View File
@@ -1,15 +1,16 @@
# 踢人下线
所谓踢人下线,核心操作就是找到其指定`loginId`的token,并设置其失效
---
## 核心思想
- 所谓踢人下线,核心操作就是找到其指定`loginId`的token,并设置其失效
## 具体API
#### StpUtil.logoutByLoginId(Object loginId)
- 让指定loginId的会话注销登录(踢人下线)
让指定loginId的会话注销登录(踢人下线),例如:
``` java
// 使账号id为10001的会话注销登录,待到10001再次访问系统时会抛出`NotLoginException`异常,场景值为-5
StpUtil.logoutByLoginId(10001);
```
+5 -3
View File
@@ -25,6 +25,7 @@
#### StpUtil.checkLogin()
- 检验当前会话是否已经登录, 如果未登录,则抛出异常:`NotLoginException`
- 扩展:`NotLoginException` 对象可通过 `getLoginKey()` 方法获取具体是哪个 `StpLogic` 抛出的异常
- 扩展:`NotLoginException` 对象可通过 `getType()` 方法获取具体的场景值,详细参考章节:[未登录场景值](/fun/not-login-scene)
#### StpUtil.getLoginId()
- 获取当前会话登录id, 如果未登录,则抛出异常:`NotLoginException`
@@ -36,9 +37,10 @@
#### StpUtil.getLoginId(T defaultValue)
- 获取当前会话登录id, 如果未登录,则返回默认值 (`defaultValue`可以为任意类型)
- 类似API还有:
- `StpUtil.getLoginId_defaultNull()` 获取当前会话登录id, 如果未登录,则返回null
- `StpUtil.getLoginIdDefaultNull()` 获取当前会话登录id, 如果未登录,则返回null
#### getLoginIdByToken(String tokenValue)
#### StpUtil.getLoginIdByToken(String tokenValue)
- 获取指定token对应的登录id,如果未登录,则返回 null
#### StpUtil.getTokenName()
- 获取当前`StpLogic`的token名称
+2 -2
View File
@@ -8,7 +8,7 @@
## 核心思想
- sa-token在设计时充分考虑了多账号体系时的各种逻辑
- 以上几篇介绍的api,都是经过 `StpUtil`类的各种静态方法进行各种验证,而如果你深入它的源码,[点此阅览](https://gitee.com/sz6/sa-token/blob/master/sa-token-dev/src/main/java/cn/dev33/satoken/stp/StpUtil.java)
- 以上几篇介绍的api,都是经过 `StpUtil`类的各种静态方法进行各种验证,而如果你深入它的源码,[点此阅览](https://gitee.com/sz6/sa-token/blob/master/sa-token-core/src/main/java/cn/dev33/satoken/stp/StpUtil.java)
- 就会发现,此类并没有任何代码逻辑,唯一做的事就是对成员变量`stpLogic`的各个API进行包装一下进行转发
- 这样做有两个优点
- `StpLogic`类的所有函数都可以被重写,按需扩展
@@ -19,7 +19,7 @@
1. 新建一个新的权限验证类,比如: `StpUserUtil.java`
2.`StpUtil.java`类的全部代码复制粘贴到 `StpUserUtil.java`
3. 更改一下其 `loginKey` 比如:
```
``` java
// 底层的 StpLogic 对象
public static StpLogic stpLogic = new StpLogic("user"); // loginKey改为user
```
+5 -1
View File
@@ -19,8 +19,12 @@
- 类似API还有:
- `StpUtil.getSessionByLoginId(Object loginId, boolean isCreate)` 获取当前会话登录id, `isCreate`代表指定是否在无`session`的情况下新建并返回
#### StpUtil.hasPermission(Object loginId, Object pcode)
#### StpUtil.hasRole(Object loginId, String role)
- 指定`loginId`是否含有指定角色
#### StpUtil.hasPermission(Object loginId, String permission)
- 指定`loginId`是否含有指定权限
+6 -6
View File
@@ -1,7 +1,7 @@
# 无cookie模式
---
## 何为无cookie
### 何为无cookie
- 常规PC端鉴权方法,一般由`cookie`进行
-`cookie`有两个特性:1、可由后端控制写入,2、每次请求自动提交
@@ -12,14 +12,14 @@
- 每次请求不能自动提交了,那就手动提交(难点在前端如何**将token传递到后端**,同时后端**将其读取出来**)
## 将token传递到前端
### 将token传递到前端
1. 首先调用 `StpUtil.setLoginId(Object loginId)` 进行登录
2. 调用 `StpUtil.getTokenInfo()` 返回当前会话的token值
- 此方法返回一个Map,有两个key`tokenName``tokenValue``token`的名称和`token`的值)
- 将此Map传递到前台,让前端人员将这两个值保存到本地
- 此方法返回一个对象,其有两个关键属性`tokenName``tokenValue``token`的名称和`token`的值)
- 将此对象传递到前台,让前端人员将这两个值保存到本地
## 前端将token提交到后端
### 前端将token提交到后端
1. 无论是app还是小程序,其传递方式都大同小异
2. 那就是,将`token`塞到请求`header`里 ,格式为:`{tokenName: tokenValue}`
3. 以经典跨端框架`uni-app`为例:
@@ -76,7 +76,7 @@
- 你当然不能每个`ajax`都写这么一坨,因为这种重复代码都是要封装在一个函数里统一调用的
## 其它解决方案?
### 其它解决方案?
- 如果你对`cookie`非常了解,那你就会明白,所谓`cookie`,本质上就是一个特殊的`header`参数而已,
- 而既然它只是一个`header`参数,我们就能就能手动模拟实现它,从而完成鉴权操作
- 这其实是对无`cookie`模式的另一种解决方案,有兴趣的同学可以百度了解一下,在此暂不赘述
+49 -28
View File
@@ -1,37 +1,58 @@
# session会话
# Session会话
---
## 账号session
账号`session`指的是为每个登录账号分配的`session`
#### StpUtil.getSession()
- 返回当前登录账号的`session`(必须是登录后才能调用)
Session是会话中专业的数据缓存组件,在`sa-token`中Session分为三种, 分别是:
- `账号Session`: 指的是框架为每个`loginId`分配的`Session`
- `令牌Session`: 指的是框架为每个`token`分配的`Session`
- `自定义Session`: 指的是以一个`特定的值`作为SessionId,来分配的`Session`
## 自定义session
自定义`session`指的是未登录状态下,以一个特定的值作为key,来分配的`session`
#### SaSessionCustomUtil.isExists(String sessionId)
- 查询指定key的`session`,是否存在
#### SaSessionCustomUtil.getSessionById(String sessionId)
- 获取指定key的`session`,如果没有,则新建并返回
#### SaSessionCustomUtil.delSessionById(String sessionId)
- 删除指定key的`session`
## 账号Session
有关账号Session的API如下:
``` java
StpUtil.getSession(); // 获取当前账号id的Session (必须是登录后才能调用)
StpUtil.getSession(true); // 获取当前账号id的Session, 并决定在Session尚未创建时,是否新建并返回
StpUtil.getSessionByLoginId(10001); // 获取账号id为10001的Session
StpUtil.getSessionByLoginId(10001, true); // 获取账号id为10001的Session, 并决定在Session尚未创建时,是否新建并返回
```
## session相关操作
## 令牌Session
有关令牌Session的API如下:
``` java
StpUtil.getTokenSession(); // 获取当前token的专属Session
StpUtil.getTokenSessionByToken(token); // 获取指定token的专属Session
```
## 自定义Session
自定义Session指的是以一个`特定的值`作为SessionId来分配的`Session`, 借助自定义Session,你可以为系统中的任意元素分配相应的session<br>
例如以商品id作为key为每个商品分配一个Session,以便于缓存和商品相关的数据,其相关API如下:
``` java
SaSessionCustomUtil.isExists("goods-10001"); // 查询指定key的Session是否存在
SaSessionCustomUtil.getSessionById("goods-10001"); // 获取指定key的Session,如果没有,则新建并返回
SaSessionCustomUtil.getSessionById("goods-10001", false); // 获取指定key的Session,如果没有,第二个参数决定是否新建并返回
SaSessionCustomUtil.deleteSessionById("goods-10001"); // 删除指定key的Session
```
在未登录状态下是否可以获取令牌Session?这取决于你配置的`tokenSessionCheckLogin`值是否为false,详见:[框架配置](/use/config?id=所有可配置项)
## Session相关操作
那么获取到的`SaSession`具体有哪些方法可供操作?
``` java
session.getId(); // 返回此Session的id
session.getCreateTime(); // 返回此Session的创建时间 (时间戳)
session.getAttribute('name'); // 在Session上获取一个值
session.getAttribute('name', 'zhang'); // 在Session上获取一个值,并指定取不到值时返回的默认值
session.setAttribute('name', 'zhang'); // 在Session上写入一个值
session.removeAttribute('name'); // 在Session上移除一个值
session.clearAttribute(); // 清空此Session的所有值
session.containsAttribute('name'); // 获取此Session是否含有指定key (返回true或false)
session.attributeKeys(); // 获取此Session会话上所有key (返回Set<String>)
session.getDataMap(); // 返回此Session会话上的底层数据对象(如果更新map里的值,请调用session.update()方法避免数据过时)
session.update(); // 将这个Session从持久库更新一下
session.logout(); // 注销此Session会话
```
具体可参考`javax.servlet.http.HttpSession``SaSession`所含方法与其大体类似
#### getId()
- 返回此`session`的id
#### setAttribute(String key, Object value)
- 在此`session`对象上写入值
#### getAttribute(String key)
- 在此`session`对象上查询值
具体可参考`javax.servlet.http.HttpSession``SaSession`所含方法与其大体类似
+116
View File
@@ -0,0 +1,116 @@
# 花式token
本篇介绍token生成的各种风格,以及自定义token生成策略
---
## 内置风格
- sa-token默认的token生成策略是uuid风格, 其模样类似于:`623368f0-ae5e-4475-a53f-93e4225f16ae`<br>
- 如果你对这种风格不太感冒,还可以将token生成设置为其他风格,
- 怎么设置呢?只需要在yml配置文件里设置 `spring.sa-token.token-style=风格类型` 即可,其有多种取值: <br>
1. token-style=`uuid`uuid风格 **(默认风格)**
``` html
623368f0-ae5e-4475-a53f-93e4225f16ae
```
2. token-style=`simple-uuid`,同上,uuid风格, 只不过去掉了中划线:
``` html
6fd4221395024b5f87edd34bc3258ee8
```
3. token-style=`random-32`,随机32位字符串:
``` html
qEjyPsEA1Bkc9dr8YP6okFr5umCZNR6W
```
4. token-style=`random-64`,随机64位字符串:
``` html
v4ueNLEpPwMtmOPMBtOOeIQsvP8z9gkMgIVibTUVjkrNrlfra5CGwQkViDjO8jcc
```
5. token-style=`random-128`,随机128位字符串:
``` html
nojYPmcEtrFEaN0Otpssa8I8jpk8FO53UcMZkCP9qyoHaDbKS6dxoRPky9c6QlftQ0pdzxRGXsKZmUSrPeZBOD6kJFfmfgiRyUmYWcj4WU4SSP2ilakWN1HYnIuX0Olj
```
6. token-style=`tik`tik风格:
``` html
gr_SwoIN0MC1ewxHX_vfCW3BothWDZMMtx__
```
## 自定义token生成策略
- 如果你觉着以上风格都不是你喜欢的类型,那么你还可以**自定义token生成策略**,来定制化token生成风格 <br>
- 怎么做呢?只需要重写`SaTokenAction`接口的`createToken`方法即可
#### 参考步骤如下:
1. 新建文件`MySaTokenAction.java`,继承`SaTokenActionDefaultImpl`默认实现类, 并添加上注解`@Component`,保证此类被`springboot`扫描到
``` java
package com.pj.satoken;
import org.springframework.stereotype.Component;
import cn.dev33.satoken.action.SaTokenActionDefaultImpl;
/**
* 继承sa-token行为Bean默认实现, 重写部分逻辑
*/
@Component
public class MySaTokenAction extends SaTokenActionDefaultImpl {
// 重写token生成策略
@Override
public String createToken(Object loginId, String loginKey) {
return SaTokenInsideUtil.getRandomString(60); // 随机60位字符串
}
}
```
2. 再次调用 `StpUtil.setLoginId(10001)`方法进行登录,观察其生成的token样式:
``` html
gfuPSwZsnUhwgz08GTCH4wOgasWtc3odP4HLwXJ7NDGOximTvT4OlW19zeLH
```
## 以雪花算法生成token
在此再举一个例子,以`自定义token生成策略`的方式集成`雪花算法`来生成token
1. 首先我们需要找一个合适的类库,帮助我们生成雪花算法唯一id,在此推荐 [Hutool](https://hutool.cn/docs/#/) ,在`pom.xml`里添加依赖:
``` xml
<!-- Hutool 一个小而全的Java工具类库 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.4</version>
</dependency>
```
2. 同上,我们需要新建文件`MySaTokenAction.java`,继承`SaTokenActionDefaultImpl`默认实现类, 并添加上注解`@Component`,保证此类被`springboot`扫描到
``` java
package com.pj.satoken;
import org.springframework.stereotype.Component;
import cn.dev33.satoken.action.SaTokenActionDefaultImpl;
import cn.hutool.core.util.IdUtil;
/**
* 继承sa-token行为Bean默认实现, 重写部分逻辑
*/
@Component
public class MySaTokenAction extends SaTokenActionDefaultImpl {
// 重写token生成策略
@Override
public String createToken(Object loginId, String loginKey) {
return IdUtil.getSnowflake(1, 1).nextIdStr(); // 以雪花算法生成token
}
}
```
3. 再次调用 `StpUtil.setLoginId(10001)`方法进行登录,观察其生成的token样式:
``` html
1339604338175250432
```
+11
View File
@@ -66,3 +66,14 @@ footer a:hover{text-decoration: underline;}
footer{position: static; line-height: 40px;}
}
/* 闪光背景 */
.z-div{
background-size: 500%;
background-image: linear-gradient(125deg,#BFFEBE,#F6F8B5,#FCD0B3,#BFB6F8,#E8D8B3);
animation: bganimation 15s infinite;
}
@keyframes bganimation{
0%{background-position: 0% 50%;}
50%{background-position: 100% 50%;}
100%{background-position: 0% 50%;}
}
+5 -5
View File
@@ -7,14 +7,14 @@
<meta name="description" content="Description">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta name="keywords" content="sa-token|sa-token框架|sa-token文档|sa-token在线文档|权限认证框架">
<meta name="description" content="sa-token是一个JavaWeb权限认证框架,强大、简单、好用,登录验证、权限验证、自定义session会话、踢人下线、持久层扩展、无cookie模式、模拟他人账号、多账号体系、注解式鉴权、Spring集成...,零配置开箱即用,覆盖所有应用场景,你所需要的功能,这里都有">
<meta name="description" content="sa-token是一个JavaWeb权限认证框架,功能全面,上手简单,登录验证、权限验证、Session会话、踢人下线、集成Redis、前后台分离、模拟他人账号、多账号体系、注解式鉴权、花式token、自动续签、Spring集成...,零配置开箱即用,覆盖所有应用场景,你所需要的功能,这里都有">
<link rel="stylesheet" href="https://unpkg.com/docsify@4.11.3/lib/themes/vue.css">
<link rel="shortcut icon" type="image/x-icon" href="doc/logo.png">
<link rel="stylesheet" href="index.css">
</head>
<body>
<div style="height: 100vh; overflow: auto;">
<div class="z-div" style="height: 100vh; overflow: auto;">
<header>
<a href="/" style="text-decoration: none;">
<div class="logo-box">
@@ -43,10 +43,10 @@
<!-- 内容部分 -->
<div class="main-box">
<div class="content-box">
<h1>sa-token<small>v1.4.0</small></h1>
<div class="sub-title">一个JavaWeb权限认证框架,强大、简单、好用</div>
<h1>sa-token<small>v1.8.0</small></h1>
<div class="sub-title">一个JavaWeb轻量级权限认证框架,功能全面,上手简单</div>
<!-- <p>0配置开箱即用,低学习成本</p> -->
<p>登录验证、权限验证、自定义session会话、踢人下线、持久层扩展、无cookie模式、模拟他人账号、多账号体系、注解式鉴权、Spring集成...</p>
<p>登录验证、权限验证、Session会话、踢人下线、集成Redis、前后台分离、模拟他人账号、多账号体系、注解式鉴权、花式token、自动续签、Spring集成...</p>
<p>零配置开箱即用,覆盖所有应用场景,你所需要的功能,这里都有</p>
<div class="btn-box">
<a href="https://github.com/click33/sa-token" target="_blank">GitHub</a>
+12
View File
@@ -0,0 +1,12 @@
target/
node_modules/
bin/
.settings/
unpackage/
.classpath
.project
.factorypath
.idea/
@@ -1,41 +1,39 @@
<?xml version='1.0' encoding='utf-8'?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- 基础信息 -->
<groupId>cn.dev33</groupId>
<artifactId>sa-token-dev</artifactId>
<packaging>jar</packaging>
<version>1.4.0</version>
<!-- SpringBoot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
</parent>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-parent</artifactId>
<version>1.8.0</version>
</parent>
<packaging>jar</packaging>
<name>sa-token-spring-boot-starter</name>
<artifactId>sa-token-spring-boot-starter</artifactId>
<description>springboot integrate sa-token</description>
<dependencies>
<!-- springboot依赖 -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-core</artifactId>
<version>1.8.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- @ConfigurationProperties -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.0.0.RELEASE</version>
<optional>true</optional>
</dependency>
</dependencies>
</project>
</project>
@@ -1,4 +1,4 @@
package cn.dev33.satoken.spring;
package cn.dev33.satoken.autowired;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
@@ -9,7 +9,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* 将此注解加到springboot启动类上即可完成sa-token与springboot的集成
* 将此注解加到springboot启动类上即可完成sa-token与springboot的集成
* <p>: v1.7版本以上已不再需要此注解直接引入sa-token-spring-boot-starter依赖即可
* @author kong
*
*/
@@ -17,7 +18,7 @@ import org.springframework.context.annotation.Import;
@Target({java.lang.annotation.ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Configuration
@Import({SpringSaToken.class})
@Import({SaTokenSpringAutowired.class})
public @interface SaTokenSetup {
}
@@ -0,0 +1,100 @@
package cn.dev33.satoken.autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import cn.dev33.satoken.SaTokenManager;
import cn.dev33.satoken.action.SaTokenAction;
import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.cookie.SaTokenCookie;
import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.servlet.SaTokenServlet;
import cn.dev33.satoken.spring.SaTokenServletSpringImpl;
import cn.dev33.satoken.stp.StpInterface;
/**
* 利用spring的自动装配来加载开发者重写的Bean
* @author kong
*
*/
@Component
public class SaTokenSpringAutowired {
/**
* 获取配置Bean
* @return 配置对象
*/
@Bean
@ConfigurationProperties(prefix="spring.sa-token")
public SaTokenConfig getSaTokenConfig() {
return new SaTokenConfig();
}
/**
* 注入配置Bean
* @param saTokenConfig 配置对象
*/
@Autowired
public void setConfig(SaTokenConfig saTokenConfig){
SaTokenManager.setConfig(saTokenConfig);
}
/**
* 注入持久化Bean
* @param saTokenDao .
*/
@Autowired(required = false)
public void setSaTokenDao(SaTokenDao saTokenDao){
SaTokenManager.setSaTokenDao(saTokenDao);
}
/**
* 注入权限认证Bean
* @param stpInterface .
*/
@Autowired(required = false)
public void setStpInterface(StpInterface stpInterface){
SaTokenManager.setStpInterface(stpInterface);
}
/**
* 注入Cookie操作Bean
* @param saTokenCookie .
*/
@Autowired(required = false)
public void setSaTokenCookie(SaTokenCookie saTokenCookie){
SaTokenManager.setSaTokenCookie(saTokenCookie);
}
/**
* 注入框架行为Bean
* @param saTokenAction .
*/
@Autowired(required = false)
public void setSaTokenAction(SaTokenAction saTokenAction){
SaTokenManager.setSaTokenAction(saTokenAction);
}
/**
* 获取Servlet操作Bean (Spring版)
* @return Servlet操作Bean (Spring版)
*/
@Bean
public SaTokenServlet getSaTokenServlet() {
return new SaTokenServletSpringImpl();
}
/**
* 注入Servlet操作Bean
* @param saTokenServlet .
*/
@Autowired
public void setSaTokenServlet(SaTokenServlet saTokenServlet){
SaTokenManager.setSaTokenServlet(saTokenServlet);
}
}
@@ -1,4 +1,4 @@
package cn.dev33.satoken.annotation;
package cn.dev33.satoken.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -6,6 +6,9 @@ import javax.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
@@ -22,7 +25,7 @@ public class SaCheckInterceptor implements HandlerInterceptor {
public StpLogic stpLogic = null;
/**
* 创建并指定一个默认的 StpLogic
* 创建并指定一个默认的 StpLogic
*/
public SaCheckInterceptor() {
this(StpUtil.stpLogic);
@@ -37,8 +40,6 @@ public class SaCheckInterceptor implements HandlerInterceptor {
}
/**
* 每次请求之前触发
*/
@@ -52,56 +53,36 @@ public class SaCheckInterceptor implements HandlerInterceptor {
}
HandlerMethod method = (HandlerMethod ) handler;
// 验证登录
// ----------- 验证登录
if(method.hasMethodAnnotation(SaCheckLogin.class) || method.getBeanType().isAnnotationPresent(SaCheckLogin.class)) {
stpLogic.checkLogin();
}
// 获取权限注解
// ----------- 验证权限
// 验证方法上的
SaCheckPermission scp = method.getMethodAnnotation(SaCheckPermission.class);
if(scp == null) {
scp = method.getBeanType().getAnnotation(SaCheckPermission.class);
if(scp != null) {
String[] permissionCodeArray = scp.value();
if(scp.mode() == SaMode.AND) {
stpLogic.checkPermissionAnd(permissionCodeArray); // 必须全部都有
} else {
stpLogic.checkPermissionOr(permissionCodeArray); // 有一个就行了
}
}
if(scp == null) {
return true;
// 验证类上的
scp = method.getBeanType().getAnnotation(SaCheckPermission.class);
if(scp != null) {
String[] permissionCodeArray = scp.value();
if(scp.mode() == SaMode.AND) {
stpLogic.checkPermissionAnd(permissionCodeArray); // 必须全部都有
} else {
stpLogic.checkPermissionOr(permissionCodeArray); // 有一个就行了
}
}
// 开始验证权限
Object[] codeArray = concatAbc(scp.value(), scp.valueInt(), scp.valueLong());
if(scp.isAnd()) {
stpLogic.checkPermissionAnd(codeArray); // 必须全部都有
} else {
stpLogic.checkPermissionOr(codeArray); // 有一个就行了
}
// 通过验证
return true;
}
/**
* 合并三个数组
* @param a .
* @param b .
* @param c .
* @return .
*/
private Object[] concatAbc(String[] a, int[] b, long[] c) {
// 循环赋值
Object[] d = new Object[a.length + b.length + c.length];
for (int i = 0; i < a.length; i++) {
d[i] = a[i];
}
for (int i = 0; i < b.length; i++) {
d[a.length + i] = b[i];
}
for (int i = 0; i < c.length; i++) {
d[a.length + b.length + i] = c[i];
}
return d;
}
@@ -0,0 +1,4 @@
/**
* sa-token集成SpringBoot的各个组件
*/
package cn.dev33.satoken;
@@ -0,0 +1,31 @@
package cn.dev33.satoken.spring;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.dev33.satoken.servlet.SaTokenServlet;
/**
* sa-token 对cookie的相关操作 接口实现类
* @author kong
*
*/
public class SaTokenServletSpringImpl implements SaTokenServlet {
/**
* 获取当前请求的Request对象
*/
@Override
public HttpServletRequest getRequest() {
return SpringMVCUtil.getRequest();
}
/**
* 获取当前请求的Response对象
*/
@Override
public HttpServletResponse getResponse() {
return SpringMVCUtil.getResponse();
}
}
@@ -1,4 +1,4 @@
package cn.dev33.satoken.util;
package cn.dev33.satoken.spring;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -11,11 +11,11 @@ import org.springframework.web.context.request.ServletRequestAttributes;
* @author kong
*
*/
public class SpringMvcUtil {
public class SpringMVCUtil {
/**
* 获取当前会话的 request
* @return
* @return request
*/
public static HttpServletRequest getRequest() {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();// 大善人SpringMVC提供的封装
@@ -26,8 +26,8 @@ public class SpringMvcUtil {
}
/**
* 获取当前会话的 response
* @return
* 获取当前会话的 response
* @return response
*/
public static HttpServletResponse getResponse() {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();// 大善人SpringMVC提供的封装
@@ -37,7 +37,4 @@ public class SpringMvcUtil {
return servletRequestAttributes.getResponse();
}
}

Some files were not shown because too many files have changed in this diff Show More