Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0a644f1

Browse files
重大改进:
1、改进jwt验证之后与shiro的token验证登录 2、移除用户信息参数传递的方法,此方法更灵活
1 parent 84d6f4d commit 0a644f1

File tree

8 files changed

+149
-135
lines changed

8 files changed

+149
-135
lines changed

‎src/main/java/com/geekcattle/controller/api/ApiMemberController.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,12 @@ public class ApiMemberController {
2828

2929

3030
@RequestMapping(value = "/index", method = RequestMethod.GET)
31-
public ModelMap index(HttpServletRequestrequest){
31+
public ModelMap index(){
3232
Subject subject = SecurityUtils.getSubject();
3333
if(subject.isAuthenticated()){
3434
PrincipalCollection principals = subject.getPrincipals();
3535
Member member = (Member) principals.getPrimaryPrincipal();
36-
return ReturnUtil.Success("登录成功", member);
36+
return ReturnUtil.Success("获取用户信息成功", member);
3737
}else{
3838
return ReturnUtil.Error("用户不存在");
3939
}

‎src/main/java/com/geekcattle/core/LoginEnum.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
*/
1111
public enum LoginEnum {
1212

13-
CUSTOMER("1"),ADMIN("2");
13+
ADMIN("1"),CUSTOMER("2"),TOKEN("3");
1414

1515
private String type;
1616

‎src/main/java/com/geekcattle/core/jwt/JwtShiroRealm.java‎

Lines changed: 36 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,11 @@
44

55
package com.geekcattle.core.jwt;
66

7+
import com.geekcattle.core.LoginEnum;
8+
import com.geekcattle.core.shiro.CustomerAuthenticationToken;
79
import com.geekcattle.model.member.Member;
810
import com.geekcattle.service.member.MemberService;
11+
import org.apache.commons.lang3.StringUtils;
912
import org.apache.shiro.authc.*;
1013
import org.apache.shiro.authz.AuthorizationInfo;
1114
import org.apache.shiro.authz.SimpleAuthorizationInfo;
@@ -16,6 +19,8 @@
1619
import org.slf4j.LoggerFactory;
1720
import org.springframework.beans.factory.annotation.Autowired;
1821

22+
import java.util.Optional;
23+
1924
/**
2025
* 前台身份校验核心类
2126
* author geekcattle
@@ -26,19 +31,20 @@ public class JwtShiroRealm extends AuthorizingRealm {
2631
private Logger logger = LoggerFactory.getLogger(this.getClass());
2732

2833
@Autowired
29-
private JwtUtiljwtUtil;
34+
private MemberServicememberService;
3035

36+
@Autowired
37+
private JwtConfig jwtConfig;
3138

3239
@Autowired
33-
private MemberServicememberService;
40+
private JwtUtiljwtUtil;
3441

35-
/**
36-
* 必须重写此方法,不然Shiro会报错
37-
*/
38-
@Override
42+
43+
44+
/* @Override
3945
public boolean supports(AuthenticationToken token) {
4046
return token instanceof JwtToken;
41-
}
47+
}*/
4248

4349

4450
/**
@@ -51,35 +57,40 @@ public boolean supports(AuthenticationToken token) {
5157
*/
5258
@Override
5359
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
54-
logger.info("前台登录认证:CustomShiroRealm.doGetAuthenticationInfo()");
55-
//获取用户的输入的账号.
56-
StringtmpToken = (String)token.getPrincipal();
57-
StringverifyToken = tmpToken.substring(7);
58-
Stringusername = jwtUtil.getUsernameFromToken(verifyToken);
59-
logger.info("登录用户:"+username);
60-
if (username == null) {
61-
throw new AuthenticationException("token invalid");
60+
logger.info("前台登录认证:JwtShiroRealm.doGetAuthenticationInfo()");
61+
Stringauth = (String) token.getCredentials();
62+
if (auth == null || auth.length() < 7 || StringUtils.isEmpty(auth)) {
63+
thrownewAuthenticationException("token为空");
64+
}
65+
StringheadStr = auth.substring(0, 6);
66+
if (headStr.compareTo(jwtConfig.getTokenHead()) != 0) {
67+
throw new AuthenticationException("token格式错误");
6268
}
69+
String tmpAuth = auth.substring(7, auth.length());
70+
String userName = jwtUtil.getUsernameFromToken(tmpAuth);
6371

64-
//通过username从数据库中查找 User对象,如果找到,没找到.
65-
//实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法
66-
Member userInfo = memberService.findByUsername(username);
72+
if (userName == null) {
73+
throw new AuthenticationException("用户名错误");
74+
}
75+
Member userInfo = memberService.findByUsername(userName);
6776
if(userInfo == null){
6877
throw new AuthenticationException("User didn't existed!");
6978
}
70-
if("0".equals(userInfo.getState().toString())) {
71-
throw new LockedAccountException(); //帐号锁定
79+
if(!jwtUtil.validateToken(tmpAuth, userInfo)){
80+
throw new AuthenticationException("token验证失败");
7281
}
82+
logger.info("登录用户:"+userName);
83+
//通过username从数据库中查找 User对象,如果找到,没找到.
84+
//实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法
7385

74-
if(jwtUtil.validateToken(verifyToken, userInfo)){
75-
throw new AuthenticationException("Token check fail");
86+
if("0".equals(userInfo.getState().toString())) {
87+
throw new LockedAccountException(); //帐号锁定
7688
}
7789

7890
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
7991
userInfo, //用户名
80-
token.getCredentials().toString(), //密码
81-
ByteSource.Util.bytes(userInfo.getSalt()),//salt=username+salt
82-
userInfo.getAccount() //realm name
92+
auth, //密码
93+
userInfo.getAccount()
8394
);
8495

8596
return authenticationInfo;

‎src/main/java/com/geekcattle/core/jwt/JwtToken.java‎

Lines changed: 0 additions & 22 deletions
This file was deleted.

‎src/main/java/com/geekcattle/core/shiro/CustomModularRealmAuthenticator.java‎

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -64,18 +64,16 @@ protected AuthenticationInfo doSingleRealmAuthentication(Realm realm,Authenticat
6464
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken)throws AuthenticationException {
6565
this.assertRealmsConfigured();
6666
Realm realm = null;
67-
String apiToken = authenticationToken.getPrincipal().toString();
68-
if(apiToken.substring(0,6).equals("Bearer")){
67+
CustomerAuthenticationToken token = (CustomerAuthenticationToken) authenticationToken;
68+
//判断是否是后台用户
69+
if (token.getLoginType().equals("2")) {
70+
realm = (Realm) this.definedRealms.get("customShiroRealm");
71+
}else if(token.getLoginType().equals("3")){
6972
realm = (Realm) this.definedRealms.get("jwtShiroRealm");
7073
}else{
71-
CustomerAuthenticationToken token = (CustomerAuthenticationToken) authenticationToken;
72-
//判断是否是后台用户
73-
if (token.getLoginType().equals("1")) {
74-
realm = (Realm) this.definedRealms.get("customShiroRealm");
75-
}else{
76-
realm = (Realm) this.definedRealms.get("adminShiroRealm");
77-
}
74+
realm = (Realm) this.definedRealms.get("adminShiroRealm");
7875
}
76+
7977
return this.doSingleRealmAuthentication(realm, authenticationToken);
8078
}
8179

‎src/main/java/com/geekcattle/core/shiro/CustomerAuthenticationToken.java‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,19 @@ public class CustomerAuthenticationToken extends UsernamePasswordToken {
2626
*/
2727
private String loginForm;
2828

29+
private String token;
30+
2931
public CustomerAuthenticationToken(String username, String password, boolean rememberMe) {
3032
super(username, password, rememberMe);
3133
}
3234

35+
public CustomerAuthenticationToken(String token, String loginType){
36+
this.token = token;
37+
this.loginType = loginType;
38+
}
39+
40+
41+
3342
public String getCaptcha() {
3443
return captcha;
3544
}
@@ -53,4 +62,31 @@ public String getLoginForm() {
5362
public void setLoginForm(String loginForm) {
5463
this.loginForm = loginForm;
5564
}
65+
66+
public String getToken() {
67+
return token;
68+
}
69+
70+
public void setToken(String token) {
71+
this.token = token;
72+
}
73+
74+
@Override
75+
public Object getPrincipal() {
76+
if(this.token != null){
77+
return this.token;
78+
}else{
79+
return this.getUsername();
80+
}
81+
82+
}
83+
84+
@Override
85+
public Object getCredentials() {
86+
if(this.token != null){
87+
return this.token;
88+
}else{
89+
return this.getPassword();
90+
}
91+
}
5692
}

‎src/main/java/com/geekcattle/core/shiro/ShiroConfiguration.java‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,13 @@
44

55
package com.geekcattle.core.shiro;
66

7+
import com.geekcattle.core.jwt.JwtShiroRealm;
78
import com.geekcattle.core.redis.RedisCacheManager;
89
import com.geekcattle.core.redis.RedisSessionDAO;
10+
import com.geekcattle.filter.ApiFilter;
911
import com.geekcattle.filter.CustomerLogoutFilter;
1012
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
13+
import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
1114
import org.apache.shiro.authc.pam.AuthenticationStrategy;
1215
import org.apache.shiro.authc.pam.FirstSuccessfulStrategy;
1316
import org.apache.shiro.authz.ModularRealmAuthorizer;
@@ -18,6 +21,7 @@
1821
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
1922
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
2023
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
24+
import org.apache.shiro.web.mgt.DefaultWebSubjectFactory;
2125
import org.apache.shiro.web.servlet.Cookie;
2226
import org.apache.shiro.web.servlet.ShiroHttpSession;
2327
import org.apache.shiro.web.servlet.SimpleCookie;
@@ -47,6 +51,18 @@ public class ShiroConfiguration {
4751

4852
private Logger logger = LoggerFactory.getLogger(this.getClass());
4953

54+
/**
55+
* token身份认证realm;
56+
* @return
57+
*/
58+
@Bean(name="jwtShiroRealm")
59+
public JwtShiroRealm jwtShiroRealm(){
60+
logger.debug("ShiroConfiguration.jwtShiroRealm()");
61+
JwtShiroRealm jwtShiroRealm = new JwtShiroRealm();
62+
jwtShiroRealm.setCredentialsMatcher(customHashedCredentialsMatcher());
63+
return new JwtShiroRealm();
64+
}
65+
5066
/**
5167
* 前台身份认证realm;
5268
* @return
@@ -147,6 +163,7 @@ public DefaultWebSecurityManager getDefaultWebSecurityManage(){
147163
Map<String, Object> shiroAuthenticatorRealms = new HashMap<>();
148164
shiroAuthenticatorRealms.put("adminShiroRealm", adminShiroRealm());
149165
shiroAuthenticatorRealms.put("customShiroRealm", customShiroRealm());
166+
shiroAuthenticatorRealms.put("jwtShiroRealm", jwtShiroRealm());
150167

151168
Collection<Realm> shiroAuthorizerRealms = new ArrayList<Realm>();
152169
shiroAuthorizerRealms.add(adminShiroRealm());
@@ -157,6 +174,7 @@ public DefaultWebSecurityManager getDefaultWebSecurityManage(){
157174
customModularRealmAuthenticator.setAuthenticationStrategy(authenticationStrategy());
158175
securityManager.setAuthenticator(customModularRealmAuthenticator);
159176
securityManager.setRealms(shiroAuthorizerRealms);
177+
securityManager.setSubjectFactory(new DefaultWebSubjectFactory());
160178
//注入缓存管理器;
161179
securityManager.setCacheManager(redisCacheManager());
162180
securityManager.setSessionManager(defaultWebSessionManager());
@@ -212,6 +230,7 @@ public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityMana
212230
filters.put("admin", new AdminFormAuthenticationFilter());
213231
filters.put("custom", new CustomFormAuthenticationFilter());
214232
filters.put("logout", new CustomerLogoutFilter());
233+
filters.put("jwt", new ApiFilter());
215234
shiroFilterFactoryBean.setFilters(filters);
216235
//拦截器.
217236
Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>();
@@ -240,6 +259,8 @@ public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityMana
240259
//配置记住我或认证通过可以访问的地址
241260
filterChainDefinitionMap.put("/console/**", "admin");
242261
filterChainDefinitionMap.put("/member/**", "custom");
262+
263+
filterChainDefinitionMap.put("/api/member/**", "jwt");
243264
// 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
244265
//shiroFilterFactoryBean.setLoginUrl("/member/login");
245266
// 登录成功后要跳转的链接
@@ -261,7 +282,7 @@ public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityMana
261282
@Bean(name="authenticationStrategy")
262283
public AuthenticationStrategy authenticationStrategy() {
263284
logger.debug("ShiroConfiguration.authenticationStrategy()");
264-
return new FirstSuccessfulStrategy();
285+
return new AtLeastOneSuccessfulStrategy();
265286
}
266287

267288
/**

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /